hash
stringlengths
40
40
date
stringdate
2018-12-11 14:31:19
2025-03-22 02:45:31
author
stringclasses
280 values
commit_message
stringlengths
14
176
is_merge
bool
1 class
git_diff
stringlengths
198
25.8M
type
stringclasses
83 values
masked_commit_message
stringlengths
8
170
a6ba3c05ab5eb2bf1f5caa76cb85cfa25c508d5e
2024-12-03 18:20:41
renovate[bot]
fix(deps): update module github.com/baidubce/bce-sdk-go to v0.9.203 (#15219)
false
diff --git a/go.mod b/go.mod index 5174a10e73330..b206bf405bcbb 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/alicebob/miniredis/v2 v2.33.0 github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible github.com/aws/aws-sdk-go v1.55.5 - github.com/baidubce/bce-sdk-go v0.9.202 + github.com/baidubce/bce-sdk-go v0.9.203 github.com/bmatcuk/doublestar/v4 v4.7.1 github.com/c2h5oh/datasize v0.0.0-20231215233829-aa82cc1e6500 github.com/cespare/xxhash/v2 v2.3.0 diff --git a/go.sum b/go.sum index 9d7fe1bb3c307..d9b51fe611825 100644 --- a/go.sum +++ b/go.sum @@ -1008,8 +1008,8 @@ github.com/aws/smithy-go v1.11.1 h1:IQ+lPZVkSM3FRtyaDox41R8YS6iwPMYIreejOgPW49g= github.com/aws/smithy-go v1.11.1/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= github.com/axiomhq/hyperloglog v0.2.0 h1:u1XT3yyY1rjzlWuP6NQIrV4bRYHOaqZaovqjcBEvZJo= github.com/axiomhq/hyperloglog v0.2.0/go.mod h1:GcgMjz9gaDKZ3G0UMS6Fq/VkZ4l7uGgcJyxA7M+omIM= -github.com/baidubce/bce-sdk-go v0.9.202 h1:TGRdO4g4CtiI2IZ6MxeUmkbKe6l8kq+mYH6SbxczO3g= -github.com/baidubce/bce-sdk-go v0.9.202/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= +github.com/baidubce/bce-sdk-go v0.9.203 h1:D4YBk4prtlIjrnwrh5nvsSSjLjataApDmeL0fxvI/KU= +github.com/baidubce/bce-sdk-go v0.9.203/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3 h1:6df1vn4bBlDDo4tARvBm7l6KA9iVMnE3NWizDeWSrps= github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3/go.mod h1:CIWtjkly68+yqLPbvwwR/fjNJA/idrtULjZWh2v1ys0= github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/config.go b/vendor/github.com/baidubce/bce-sdk-go/bce/config.go index 243b4c81ce93a..cd632ec2cd89a 100644 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/config.go +++ b/vendor/github.com/baidubce/bce-sdk-go/bce/config.go @@ -26,7 +26,7 @@ import ( // Constants and default values for the package bce const ( - SDK_VERSION = "0.9.202" + SDK_VERSION = "0.9.203" URI_PREFIX = "/" // now support uri without prefix "v1" so just set root path DEFAULT_DOMAIN = "baidubce.com" DEFAULT_PROTOCOL = "http" diff --git a/vendor/modules.txt b/vendor/modules.txt index e7e389624a74a..88462c29e7d15 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -465,7 +465,7 @@ github.com/aws/smithy-go/transport/http/internal/io # github.com/axiomhq/hyperloglog v0.2.0 ## explicit; go 1.21 github.com/axiomhq/hyperloglog -# github.com/baidubce/bce-sdk-go v0.9.202 +# github.com/baidubce/bce-sdk-go v0.9.203 ## explicit; go 1.11 github.com/baidubce/bce-sdk-go/auth github.com/baidubce/bce-sdk-go/bce
fix
update module github.com/baidubce/bce-sdk-go to v0.9.203 (#15219)
9eca39601df5619499dabce95317cc48b3936649
2023-06-24 02:23:12
Jim Gustavsson
helm: Add PDB when gateway autoscaling is enabled (#8439)
false
diff --git a/production/helm/loki/templates/gateway/poddisruptionbudget-gateway.yaml b/production/helm/loki/templates/gateway/poddisruptionbudget-gateway.yaml index 8664a46690868..0057c5653d5cc 100644 --- a/production/helm/loki/templates/gateway/poddisruptionbudget-gateway.yaml +++ b/production/helm/loki/templates/gateway/poddisruptionbudget-gateway.yaml @@ -1,5 +1,8 @@ {{- if and .Values.gateway.enabled }} -{{- if gt (int .Values.gateway.replicas) 1 }} +{{- if or + (and (not .Values.gateway.autoscaling.enabled) (gt (int .Values.gateway.replicas) 1)) + (and .Values.gateway.autoscaling.enabled (gt (int .Values.gateway.autoscaling.minReplicas) 1)) +}} apiVersion: policy/v1 kind: PodDisruptionBudget metadata:
helm
Add PDB when gateway autoscaling is enabled (#8439)
639ac74c485bd99ceddc5de498831cbc4f8982ff
2025-01-08 16:31:15
Jonathan Lange
feat(logcli): Include common labels (#15611)
false
diff --git a/cmd/logcli/main.go b/cmd/logcli/main.go index 835216c2bb83c..c65896228f444 100644 --- a/cmd/logcli/main.go +++ b/cmd/logcli/main.go @@ -597,6 +597,7 @@ func newQuery(instant bool, cmd *kingpin.CmdClause) *query.Query { cmd.Flag("no-labels", "Do not print any labels").Default("false").BoolVar(&q.NoLabels) cmd.Flag("exclude-label", "Exclude labels given the provided key during output.").StringsVar(&q.IgnoreLabelsKey) cmd.Flag("include-label", "Include labels given the provided key during output.").StringsVar(&q.ShowLabelsKey) + cmd.Flag("include-common-labels", "Include common labels in output for each log line.").Default("false").BoolVar(&q.IncludeCommonLabels) cmd.Flag("labels-length", "Set a fixed padding to labels").Default("0").IntVar(&q.FixedLabelsLen) cmd.Flag("store-config", "Execute the current query using a configured storage from a given Loki configuration file.").Default("").StringVar(&q.LocalConfig) cmd.Flag("remote-schema", "Execute the current query using a remote schema retrieved from the configured -schema-store.").Default("false").BoolVar(&q.FetchSchemaFromStorage) diff --git a/pkg/logcli/index/volume.go b/pkg/logcli/index/volume.go index b6a3205706912..902c9a33ee4f3 100644 --- a/pkg/logcli/index/volume.go +++ b/pkg/logcli/index/volume.go @@ -24,7 +24,7 @@ func GetVolumeRange(q *volume.Query, c client.Client, out output.LogOutput, stat func do(q *volume.Query, rangeQuery bool, c client.Client, out output.LogOutput, statistics bool) { resp := getVolume(q, rangeQuery, c) - resultsPrinter := print.NewQueryResultPrinter(nil, nil, q.Quiet, 0, false) + resultsPrinter := print.NewQueryResultPrinter(nil, nil, q.Quiet, 0, false, false) if statistics { resultsPrinter.PrintStats(resp.Data.Statistics) diff --git a/pkg/logcli/print/print.go b/pkg/logcli/print/print.go index 0f7d5d131151e..decb5ffa55844 100644 --- a/pkg/logcli/print/print.go +++ b/pkg/logcli/print/print.go @@ -19,20 +19,22 @@ import ( ) type QueryResultPrinter struct { - ShowLabelsKey []string - IgnoreLabelsKey []string - Quiet bool - FixedLabelsLen int - Forward bool + ShowLabelsKey []string + IgnoreLabelsKey []string + Quiet bool + FixedLabelsLen int + Forward bool + IncludeCommonLabels bool } -func NewQueryResultPrinter(showLabelsKey []string, ignoreLabelsKey []string, quiet bool, fixedLabelsLen int, forward bool) *QueryResultPrinter { +func NewQueryResultPrinter(showLabelsKey []string, ignoreLabelsKey []string, quiet bool, fixedLabelsLen int, forward bool, includeCommonLabels bool) *QueryResultPrinter { return &QueryResultPrinter{ - ShowLabelsKey: showLabelsKey, - IgnoreLabelsKey: ignoreLabelsKey, - Quiet: quiet, - FixedLabelsLen: fixedLabelsLen, - Forward: forward, + ShowLabelsKey: showLabelsKey, + IgnoreLabelsKey: ignoreLabelsKey, + Quiet: quiet, + FixedLabelsLen: fixedLabelsLen, + Forward: forward, + IncludeCommonLabels: includeCommonLabels, } } @@ -83,8 +85,11 @@ func (r *QueryResultPrinter) printStream(streams loghttp.Streams, out output.Log // calculate the max labels length maxLabelsLen := r.FixedLabelsLen for i, s := range streams { + ls := s.Labels // Remove common labels - ls := subtract(s.Labels, common) + if !r.IncludeCommonLabels { + ls = subtract(s.Labels, common) + } if len(r.ShowLabelsKey) > 0 { ls = matchLabels(true, ls, r.ShowLabelsKey) diff --git a/pkg/logcli/query/query.go b/pkg/logcli/query/query.go index cb693a0125139..0551e076f742e 100644 --- a/pkg/logcli/query/query.go +++ b/pkg/logcli/query/query.go @@ -50,6 +50,7 @@ type Query struct { NoLabels bool IgnoreLabelsKey []string ShowLabelsKey []string + IncludeCommonLabels bool FixedLabelsLen int ColoredOutput bool LocalConfig string @@ -118,7 +119,7 @@ func (q *Query) DoQuery(c client.Client, out output.LogOutput, statistics bool) out = out.WithWriter(partFile) } - result := print.NewQueryResultPrinter(q.ShowLabelsKey, q.IgnoreLabelsKey, q.Quiet, q.FixedLabelsLen, q.Forward) + result := print.NewQueryResultPrinter(q.ShowLabelsKey, q.IgnoreLabelsKey, q.Quiet, q.FixedLabelsLen, q.Forward, q.IncludeCommonLabels) if q.isInstant() { resp, err = c.Query(q.QueryString, q.Limit, q.Start, d, q.Quiet) @@ -523,7 +524,7 @@ func (q *Query) DoLocalQuery(out output.LogOutput, statistics bool, orgID string return err } - resPrinter := print.NewQueryResultPrinter(q.ShowLabelsKey, q.IgnoreLabelsKey, q.Quiet, q.FixedLabelsLen, q.Forward) + resPrinter := print.NewQueryResultPrinter(q.ShowLabelsKey, q.IgnoreLabelsKey, q.Quiet, q.FixedLabelsLen, q.Forward, q.IncludeCommonLabels) if statistics { resPrinter.PrintStats(result.Statistics) }
feat
Include common labels (#15611)
5b145ab2d79e22a1d230c348dcf3594f6c6f09de
2024-03-05 17:04:31
Robert Jacob
feat(operator): Allow setting explicit CredentialMode in LokiStack storage spec (#12106)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index e2d030a5c0187..14f7d7e1812ea 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [12106](https://github.com/grafana/loki/pull/12106) **xperimental**: Allow setting explicit CredentialMode in LokiStack storage spec - [11968](https://github.com/grafana/loki/pull/11968) **xperimental**: Extend status to show difference between running and ready - [12007](https://github.com/grafana/loki/pull/12007) **xperimental**: Extend Azure secret validation - [12008](https://github.com/grafana/loki/pull/12008) **xperimental**: Support using multiple buckets with AWS STS diff --git a/operator/apis/loki/v1/lokistack_types.go b/operator/apis/loki/v1/lokistack_types.go index 8e77e1674f21c..00ac658ec475b 100644 --- a/operator/apis/loki/v1/lokistack_types.go +++ b/operator/apis/loki/v1/lokistack_types.go @@ -529,6 +529,14 @@ type ObjectStorageSecretSpec struct { // +kubebuilder:validation:Required // +operator-sdk:csv:customresourcedefinitions:type=spec,xDescriptors="urn:alm:descriptor:io.kubernetes:Secret",displayName="Object Storage Secret Name" Name string `json:"name"` + + // CredentialMode can be used to set the desired credential mode for authenticating with the object storage. + // If this is not set, then the operator tries to infer the credential mode from the provided secret and its + // own configuration. + // + // +optional + // +kubebuilder:validation:Optional + CredentialMode CredentialMode `json:"credentialMode,omitempty"` } // ObjectStorageSchemaVersion defines the storage schema version which will be diff --git a/operator/bundle/community-openshift/manifests/loki.grafana.com_lokistacks.yaml b/operator/bundle/community-openshift/manifests/loki.grafana.com_lokistacks.yaml index e1a7e5578965a..a2a9d644383da 100644 --- a/operator/bundle/community-openshift/manifests/loki.grafana.com_lokistacks.yaml +++ b/operator/bundle/community-openshift/manifests/loki.grafana.com_lokistacks.yaml @@ -606,6 +606,16 @@ spec: description: Secret for object storage authentication. Name of a secret in the same namespace as the LokiStack custom resource. properties: + credentialMode: + description: CredentialMode can be used to set the desired + credential mode for authenticating with the object storage. + If this is not set, then the operator tries to infer the + credential mode from the provided secret and its own configuration. + enum: + - static + - token + - managed + type: string name: description: Name of a secret in the namespace configured for object storage secrets. diff --git a/operator/bundle/community/manifests/loki.grafana.com_lokistacks.yaml b/operator/bundle/community/manifests/loki.grafana.com_lokistacks.yaml index f92665f5095d2..c51487318616b 100644 --- a/operator/bundle/community/manifests/loki.grafana.com_lokistacks.yaml +++ b/operator/bundle/community/manifests/loki.grafana.com_lokistacks.yaml @@ -606,6 +606,16 @@ spec: description: Secret for object storage authentication. Name of a secret in the same namespace as the LokiStack custom resource. properties: + credentialMode: + description: CredentialMode can be used to set the desired + credential mode for authenticating with the object storage. + If this is not set, then the operator tries to infer the + credential mode from the provided secret and its own configuration. + enum: + - static + - token + - managed + type: string name: description: Name of a secret in the namespace configured for object storage secrets. diff --git a/operator/bundle/openshift/manifests/loki.grafana.com_lokistacks.yaml b/operator/bundle/openshift/manifests/loki.grafana.com_lokistacks.yaml index 3163752ad36f0..04bdd9b903cc9 100644 --- a/operator/bundle/openshift/manifests/loki.grafana.com_lokistacks.yaml +++ b/operator/bundle/openshift/manifests/loki.grafana.com_lokistacks.yaml @@ -606,6 +606,16 @@ spec: description: Secret for object storage authentication. Name of a secret in the same namespace as the LokiStack custom resource. properties: + credentialMode: + description: CredentialMode can be used to set the desired + credential mode for authenticating with the object storage. + If this is not set, then the operator tries to infer the + credential mode from the provided secret and its own configuration. + enum: + - static + - token + - managed + type: string name: description: Name of a secret in the namespace configured for object storage secrets. diff --git a/operator/config/crd/bases/loki.grafana.com_lokistacks.yaml b/operator/config/crd/bases/loki.grafana.com_lokistacks.yaml index d603ef2a9b644..f49217c8a21c7 100644 --- a/operator/config/crd/bases/loki.grafana.com_lokistacks.yaml +++ b/operator/config/crd/bases/loki.grafana.com_lokistacks.yaml @@ -588,6 +588,16 @@ spec: description: Secret for object storage authentication. Name of a secret in the same namespace as the LokiStack custom resource. properties: + credentialMode: + description: CredentialMode can be used to set the desired + credential mode for authenticating with the object storage. + If this is not set, then the operator tries to infer the + credential mode from the provided secret and its own configuration. + enum: + - static + - token + - managed + type: string name: description: Name of a secret in the namespace configured for object storage secrets. diff --git a/operator/controllers/loki/lokistack_controller.go b/operator/controllers/loki/lokistack_controller.go index eb30a1a9bf555..df768c6d4dd06 100644 --- a/operator/controllers/loki/lokistack_controller.go +++ b/operator/controllers/loki/lokistack_controller.go @@ -180,7 +180,7 @@ func (r *LokiStackReconciler) updateResources(ctx context.Context, req ctrl.Requ } if r.FeatureGates.OpenShift.ManagedAuthEnv { - if err := handlers.CreateCredentialsRequest(ctx, r.Log, r.Scheme, r.AuthConfig, r.Client, req); err != nil { + if err := handlers.CreateUpdateDeleteCredentialsRequest(ctx, r.Log, r.Scheme, r.AuthConfig, r.Client, req); err != nil { return "", err } } diff --git a/operator/docs/operator/api.md b/operator/docs/operator/api.md index d943bc8fad9fa..88256ec496bdb 100644 --- a/operator/docs/operator/api.md +++ b/operator/docs/operator/api.md @@ -1103,7 +1103,7 @@ string ## CredentialMode { #loki-grafana-com-v1-CredentialMode } (<code>string</code> alias) <p> -(<em>Appears on:</em><a href="#loki-grafana-com-v1-LokiStackStorageStatus">LokiStackStorageStatus</a>) +(<em>Appears on:</em><a href="#loki-grafana-com-v1-LokiStackStorageStatus">LokiStackStorageStatus</a>, <a href="#loki-grafana-com-v1-ObjectStorageSecretSpec">ObjectStorageSecretSpec</a>) </p> <div> <p>CredentialMode represents the type of authentication used for accessing the object storage.</p> @@ -2706,6 +2706,22 @@ string <p>Name of a secret in the namespace configured for object storage secrets.</p> </td> </tr> +<tr> +<td> +<code>credentialMode</code><br/> +<em> +<a href="#loki-grafana-com-v1-CredentialMode"> +CredentialMode +</a> +</em> +</td> +<td> +<em>(Optional)</em> +<p>CredentialMode can be used to set the desired credential mode for authenticating with the object storage. +If this is not set, then the operator tries to infer the credential mode from the provided secret and its +own configuration.</p> +</td> +</tr> </tbody> </table> diff --git a/operator/internal/handlers/credentialsrequest.go b/operator/internal/handlers/credentialsrequest.go index 0d562332dc9d5..0592a9602fa71 100644 --- a/operator/internal/handlers/credentialsrequest.go +++ b/operator/internal/handlers/credentialsrequest.go @@ -6,6 +6,7 @@ import ( "github.com/ViaQ/logerr/v2/kverrors" "github.com/go-logr/logr" + cloudcredentialv1 "github.com/openshift/cloud-credential-operator/pkg/apis/cloudcredential/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -19,9 +20,9 @@ import ( "github.com/grafana/loki/operator/internal/manifests/openshift" ) -// CreateCredentialsRequest creates a new CredentialsRequest resource for a Lokistack +// CreateUpdateDeleteCredentialsRequest creates a new CredentialsRequest resource for a Lokistack // to request a cloud credentials Secret resource from the OpenShift cloud-credentials-operator. -func CreateCredentialsRequest(ctx context.Context, log logr.Logger, scheme *runtime.Scheme, managedAuth *config.ManagedAuthConfig, k k8s.Client, req ctrl.Request) error { +func CreateUpdateDeleteCredentialsRequest(ctx context.Context, log logr.Logger, scheme *runtime.Scheme, managedAuth *config.ManagedAuthConfig, k k8s.Client, req ctrl.Request) error { ll := log.WithValues("lokistack", req.NamespacedName, "event", "createCredentialsRequest") var stack lokiv1.LokiStack @@ -34,6 +35,24 @@ func CreateCredentialsRequest(ctx context.Context, log logr.Logger, scheme *runt return kverrors.Wrap(err, "failed to lookup LokiStack", "name", req.String()) } + if !hasManagedCredentialMode(&stack) { + // Operator is running in managed-mode, but stack specifies non-managed mode -> skip CredentialsRequest + var credReq cloudcredentialv1.CredentialsRequest + if err := k.Get(ctx, req.NamespacedName, &credReq); err != nil { + if apierrors.IsNotFound(err) { + // CredentialsRequest does not exist -> this is what we want + return nil + } + + return kverrors.Wrap(err, "failed to lookup CredentialsRequest", "name", req.String()) + } + + if err := k.Delete(ctx, &credReq); err != nil { + return kverrors.Wrap(err, "failed to remove CredentialsRequest", "name", req.String()) + } + return nil + } + opts := openshift.Options{ BuildOpts: openshift.BuildOptions{ LokiStackName: stack.Name, @@ -71,3 +90,19 @@ func CreateCredentialsRequest(ctx context.Context, log logr.Logger, scheme *runt return nil } + +// hasManagedCredentialMode returns true, if the LokiStack is configured to run in managed-mode. +// This function assumes only being called when the operator is running in managed-credentials mode, so it is +// only returning false when the credential-mode has been explicitly configured, even if the target storage +// is not supporting managed-mode at all. +func hasManagedCredentialMode(stack *lokiv1.LokiStack) bool { + switch stack.Spec.Storage.Secret.CredentialMode { + case lokiv1.CredentialModeStatic, lokiv1.CredentialModeToken: + return false + case lokiv1.CredentialModeManaged: + return true + default: + } + + return true +} diff --git a/operator/internal/handlers/credentialsrequest_test.go b/operator/internal/handlers/credentialsrequest_test.go index dd6dfb50d77dc..e9835bd5c81e6 100644 --- a/operator/internal/handlers/credentialsrequest_test.go +++ b/operator/internal/handlers/credentialsrequest_test.go @@ -39,7 +39,7 @@ func credentialsRequestFakeClient(cr *cloudcredentialv1.CredentialsRequest, loki return k } -func TestCreateCredentialsRequest_CreateNewResource(t *testing.T) { +func TestCreateUpdateDeleteCredentialsRequest_CreateNewResource(t *testing.T) { wantServiceAccountNames := []string{ "my-stack", "my-stack-ruler", @@ -63,7 +63,7 @@ func TestCreateCredentialsRequest_CreateNewResource(t *testing.T) { }, } - err := CreateCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) + err := CreateUpdateDeleteCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) require.NoError(t, err) require.Equal(t, 1, k.CreateCallCount()) @@ -74,7 +74,7 @@ func TestCreateCredentialsRequest_CreateNewResource(t *testing.T) { require.Equal(t, wantServiceAccountNames, credReq.Spec.ServiceAccountNames) } -func TestCreateCredentialsRequest_CreateNewResourceAzure(t *testing.T) { +func TestCreateUpdateDeleteCredentialsRequest_CreateNewResourceAzure(t *testing.T) { wantRegion := "test-region" lokistack := &lokiv1.LokiStack{ @@ -98,7 +98,7 @@ func TestCreateCredentialsRequest_CreateNewResourceAzure(t *testing.T) { }, } - err := CreateCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) + err := CreateUpdateDeleteCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) require.NoError(t, err) require.Equal(t, 1, k.CreateCallCount()) @@ -112,7 +112,7 @@ func TestCreateCredentialsRequest_CreateNewResourceAzure(t *testing.T) { require.Equal(t, wantRegion, providerSpec.AzureRegion) } -func TestCreateCredentialsRequest_DoNothing_WhenCredentialsRequestExist(t *testing.T) { +func TestCreateUpdateDeleteCredentialsRequest_Update_WhenCredentialsRequestExist(t *testing.T) { req := ctrl.Request{ NamespacedName: client.ObjectKey{Name: "my-stack", Namespace: "ns"}, } @@ -138,9 +138,85 @@ func TestCreateCredentialsRequest_DoNothing_WhenCredentialsRequestExist(t *testi k := credentialsRequestFakeClient(cr, lokistack) - err := CreateCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) + err := CreateUpdateDeleteCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) require.NoError(t, err) require.Equal(t, 2, k.GetCallCount()) require.Equal(t, 0, k.CreateCallCount()) require.Equal(t, 1, k.UpdateCallCount()) } + +func TestCreateUpdateDeleteCredentialsRequest_DeleteExisting_WhenNotManagedMode(t *testing.T) { + req := ctrl.Request{ + NamespacedName: client.ObjectKey{Name: "my-stack", Namespace: "ns"}, + } + + managedAuth := &config.ManagedAuthConfig{ + AWS: &config.AWSEnvironment{ + RoleARN: "a-role-arn", + }, + } + + cr := &cloudcredentialv1.CredentialsRequest{ + ObjectMeta: metav1.ObjectMeta{ + Name: "my-stack", + Namespace: "ns", + }, + } + lokistack := &lokiv1.LokiStack{ + ObjectMeta: metav1.ObjectMeta{ + Name: "my-stack", + Namespace: "ns", + }, + Spec: lokiv1.LokiStackSpec{ + Storage: lokiv1.ObjectStorageSpec{ + Secret: lokiv1.ObjectStorageSecretSpec{ + CredentialMode: lokiv1.CredentialModeStatic, + }, + }, + }, + } + + k := credentialsRequestFakeClient(cr, lokistack) + + err := CreateUpdateDeleteCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) + require.NoError(t, err) + require.Equal(t, 2, k.GetCallCount()) + require.Equal(t, 0, k.CreateCallCount()) + require.Equal(t, 0, k.UpdateCallCount()) + require.Equal(t, 1, k.DeleteCallCount()) +} + +func TestCreateUpdateDeleteCredentialsRequest_DoNothing_WhenNotManagedMode(t *testing.T) { + req := ctrl.Request{ + NamespacedName: client.ObjectKey{Name: "my-stack", Namespace: "ns"}, + } + + managedAuth := &config.ManagedAuthConfig{ + AWS: &config.AWSEnvironment{ + RoleARN: "a-role-arn", + }, + } + + lokistack := &lokiv1.LokiStack{ + ObjectMeta: metav1.ObjectMeta{ + Name: "my-stack", + Namespace: "ns", + }, + Spec: lokiv1.LokiStackSpec{ + Storage: lokiv1.ObjectStorageSpec{ + Secret: lokiv1.ObjectStorageSecretSpec{ + CredentialMode: lokiv1.CredentialModeStatic, + }, + }, + }, + } + + k := credentialsRequestFakeClient(nil, lokistack) + + err := CreateUpdateDeleteCredentialsRequest(context.Background(), logger, scheme, managedAuth, k, req) + require.NoError(t, err) + require.Equal(t, 2, k.GetCallCount()) + require.Equal(t, 0, k.CreateCallCount()) + require.Equal(t, 0, k.UpdateCallCount()) + require.Equal(t, 0, k.DeleteCallCount()) +} diff --git a/operator/internal/handlers/internal/storage/secrets.go b/operator/internal/handlers/internal/storage/secrets.go index 80dde97b61367..11cb93a6365ea 100644 --- a/operator/internal/handlers/internal/storage/secrets.go +++ b/operator/internal/handlers/internal/storage/secrets.go @@ -31,10 +31,9 @@ var ( errSecretUnknownSSEType = errors.New("unsupported SSE type (supported: SSE-KMS, SSE-S3)") errSecretHashError = errors.New("error calculating hash for secret") - errS3NoAuth = errors.New("missing secret fields for static or sts authentication") + errSecretUnknownCredentialMode = errors.New("unknown credential mode") + errSecretUnsupportedCredentialMode = errors.New("combination of storage type and credential mode not supported") - errAzureNoCredentials = errors.New("azure storage secret does contain neither account_key or client_id") - errAzureMixedCredentials = errors.New("azure storage secret can not contain both account_key and client_id") errAzureManagedIdentityNoOverride = errors.New("when in managed mode, storage secret can not contain credentials") errAzureInvalidEnvironment = errors.New("azure environment invalid (valid values: AzureGlobal, AzureChinaCloud, AzureGermanCloud, AzureUSGovernment)") errAzureInvalidAccountKey = errors.New("azure account key is not valid base64") @@ -75,11 +74,9 @@ func getSecrets(ctx context.Context, k k8s.Client, stack *lokiv1.LokiStack, fg c managedAuthCredsKey := client.ObjectKey{Name: secretName, Namespace: stack.Namespace} if err := k.Get(ctx, managedAuthCredsKey, &managedAuthSecret); err != nil { if apierrors.IsNotFound(err) { - return nil, nil, &status.DegradedError{ - Message: "Missing OpenShift cloud credentials secret", - Reason: lokiv1.ReasonMissingManagedAuthSecret, - Requeue: true, - } + // We don't know if this is an error yet, need to wait for evaluation of CredentialMode + // For now we go with empty "managed secret", the eventual DegradedError will be returned later. + return &storageSecret, nil, nil } return nil, nil, fmt.Errorf("failed to lookup OpenShift CCO managed authentication credentials secret: %w", err) } @@ -92,54 +89,112 @@ func getSecrets(ctx context.Context, k k8s.Client, stack *lokiv1.LokiStack, fg c // extractSecrets reads the k8s obj storage secret into a manifest object storage struct if valid. // The managed auth is also read into the manifest object under the right circumstances. -func extractSecrets(secretType lokiv1.ObjectStorageSecretType, objStore, managedAuth *corev1.Secret, fg configv1.FeatureGates) (storage.Options, error) { +func extractSecrets(secretSpec lokiv1.ObjectStorageSecretSpec, objStore, managedAuth *corev1.Secret, fg configv1.FeatureGates) (storage.Options, error) { hash, err := hashSecretData(objStore) if err != nil { return storage.Options{}, errSecretHashError } - storageOpts := storage.Options{ - SecretName: objStore.Name, - SecretSHA1: hash, - SharedStore: secretType, + openShiftOpts := storage.OpenShiftOptions{ + Enabled: fg.OpenShift.Enabled, } - - if fg.OpenShift.ManagedAuthEnv { + if managedAuth != nil { var managedAuthHash string managedAuthHash, err = hashSecretData(managedAuth) if err != nil { return storage.Options{}, errSecretHashError } - storageOpts.OpenShift = storage.OpenShiftOptions{ - CloudCredentials: storage.CloudCredentials{ - SecretName: managedAuth.Name, - SHA1: managedAuthHash, - }, + openShiftOpts.CloudCredentials = storage.CloudCredentials{ + SecretName: managedAuth.Name, + SHA1: managedAuthHash, } } - switch secretType { + storageOpts := storage.Options{ + SecretName: objStore.Name, + SecretSHA1: hash, + SharedStore: secretSpec.Type, + OpenShift: openShiftOpts, + } + + credentialMode, err := determineCredentialMode(secretSpec, objStore, fg) + if err != nil { + return storage.Options{}, err + } + storageOpts.CredentialMode = credentialMode + + switch secretSpec.Type { case lokiv1.ObjectStorageSecretAzure: - storageOpts.Azure, err = extractAzureConfigSecret(objStore, fg) + storageOpts.Azure, err = extractAzureConfigSecret(objStore, credentialMode) case lokiv1.ObjectStorageSecretGCS: - storageOpts.GCS, err = extractGCSConfigSecret(objStore) + storageOpts.GCS, err = extractGCSConfigSecret(objStore, credentialMode) case lokiv1.ObjectStorageSecretS3: - storageOpts.S3, err = extractS3ConfigSecret(objStore, fg) + storageOpts.S3, err = extractS3ConfigSecret(objStore, credentialMode) case lokiv1.ObjectStorageSecretSwift: storageOpts.Swift, err = extractSwiftConfigSecret(objStore) case lokiv1.ObjectStorageSecretAlibabaCloud: storageOpts.AlibabaCloud, err = extractAlibabaCloudConfigSecret(objStore) default: - return storage.Options{}, fmt.Errorf("%w: %s", errSecretUnknownType, secretType) + return storage.Options{}, fmt.Errorf("%w: %s", errSecretUnknownType, secretSpec.Type) } if err != nil { return storage.Options{}, err } + return storageOpts, nil } +func keyPresent(secret *corev1.Secret, key string) bool { + data, ok := secret.Data[key] + if !ok { + return false + } + + return len(data) > 0 +} + +func determineCredentialMode(spec lokiv1.ObjectStorageSecretSpec, secret *corev1.Secret, fg configv1.FeatureGates) (lokiv1.CredentialMode, error) { + if spec.CredentialMode != "" { + // Return user-defined credential mode if defined + return spec.CredentialMode, nil + } + + if fg.OpenShift.ManagedAuthEnv { + // Default to managed credential mode on a managed-auth installation + return lokiv1.CredentialModeManaged, nil + } + + switch spec.Type { + case lokiv1.ObjectStorageSecretAzure: + if keyPresent(secret, storage.KeyAzureStorageClientID) { + return lokiv1.CredentialModeToken, nil + } + case lokiv1.ObjectStorageSecretGCS: + _, credentialType, err := extractGoogleCredentialSource(secret) + if err != nil { + return "", err + } + + if credentialType == gcpAccountTypeExternal { + return lokiv1.CredentialModeToken, nil + } + case lokiv1.ObjectStorageSecretS3: + if keyPresent(secret, storage.KeyAWSRoleArn) { + return lokiv1.CredentialModeToken, nil + } + case lokiv1.ObjectStorageSecretSwift: + // does only support static mode + case lokiv1.ObjectStorageSecretAlibabaCloud: + // does only support static mode + default: + return "", fmt.Errorf("%w: %s", errSecretUnknownType, spec.Type) + } + + return lokiv1.CredentialModeStatic, nil +} + func hashSecretData(s *corev1.Secret) (string, error) { keys := make([]string, 0, len(s.Data)) for k := range s.Data { @@ -169,7 +224,7 @@ func hashSecretData(s *corev1.Secret) (string, error) { return fmt.Sprintf("%x", h.Sum(nil)), nil } -func extractAzureConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage.AzureStorageConfig, error) { +func extractAzureConfigSecret(s *corev1.Secret, credentialMode lokiv1.CredentialMode) (*storage.AzureStorageConfig, error) { // Extract and validate mandatory fields env := string(s.Data[storage.KeyAzureEnvironmentName]) if env == "" { @@ -190,7 +245,7 @@ func extractAzureConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*stor return nil, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageContainerName) } - workloadIdentity, err := validateAzureCredentials(s, fg) + workloadIdentity, err := validateAzureCredentials(s, credentialMode) if err != nil { return nil, err } @@ -212,47 +267,46 @@ func extractAzureConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*stor }, nil } -func validateAzureCredentials(s *corev1.Secret, fg configv1.FeatureGates) (workloadIdentity bool, err error) { +func validateAzureCredentials(s *corev1.Secret, credentialMode lokiv1.CredentialMode) (workloadIdentity bool, err error) { accountKey := s.Data[storage.KeyAzureStorageAccountKey] clientID := s.Data[storage.KeyAzureStorageClientID] tenantID := s.Data[storage.KeyAzureStorageTenantID] subscriptionID := s.Data[storage.KeyAzureStorageSubscriptionID] - if fg.OpenShift.ManagedAuthEnv { - if len(accountKey) > 0 || len(clientID) > 0 || len(tenantID) > 0 || len(subscriptionID) > 0 { - return false, errAzureManagedIdentityNoOverride + switch credentialMode { + case lokiv1.CredentialModeStatic: + if len(accountKey) == 0 { + return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageAccountKey) } - return true, nil - } - - if len(accountKey) == 0 && len(clientID) == 0 { - return false, errAzureNoCredentials - } - - if len(accountKey) > 0 && len(clientID) > 0 { - return false, errAzureMixedCredentials - } - - if len(accountKey) > 0 { if err := validateBase64(accountKey); err != nil { return false, errAzureInvalidAccountKey } - // have both account_name and account_key -> no workload identity federation return false, nil - } + case lokiv1.CredentialModeToken: + if len(clientID) == 0 { + return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageClientID) + } - // assume workload-identity from here on - if len(tenantID) == 0 { - return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageTenantID) - } + if len(tenantID) == 0 { + return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageTenantID) + } + + if len(subscriptionID) == 0 { + return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageSubscriptionID) + } + + return true, nil + case lokiv1.CredentialModeManaged: + if len(accountKey) > 0 || len(clientID) > 0 || len(tenantID) > 0 || len(subscriptionID) > 0 { + return false, errAzureManagedIdentityNoOverride + } - if len(subscriptionID) == 0 { - return false, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyAzureStorageSubscriptionID) + return true, nil } - return true, nil + return false, fmt.Errorf("%w: %s", errSecretUnknownCredentialMode, credentialMode) } func validateBase64(data []byte) error { @@ -262,17 +316,10 @@ func validateBase64(data []byte) error { return err } -func extractGCSConfigSecret(s *corev1.Secret) (*storage.GCSStorageConfig, error) { - // Extract and validate mandatory fields - bucket := s.Data[storage.KeyGCPStorageBucketName] - if len(bucket) == 0 { - return nil, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyGCPStorageBucketName) - } - - // Check if google authentication credentials is provided - keyJSON := s.Data[storage.KeyGCPServiceAccountKeyFilename] +func extractGoogleCredentialSource(secret *corev1.Secret) (sourceFile, sourceType string, err error) { + keyJSON := secret.Data[storage.KeyGCPServiceAccountKeyFilename] if len(keyJSON) == 0 { - return nil, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyGCPServiceAccountKeyFilename) + return "", "", fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyGCPServiceAccountKeyFilename) } credentialsFile := struct { @@ -282,33 +329,56 @@ func extractGCSConfigSecret(s *corev1.Secret) (*storage.GCSStorageConfig, error) } `json:"credential_source"` }{} - err := json.Unmarshal(keyJSON, &credentialsFile) + err = json.Unmarshal(keyJSON, &credentialsFile) if err != nil { - return nil, errGCPParseCredentialsFile + return "", "", errGCPParseCredentialsFile } - var ( - audience = s.Data[storage.KeyGCPWorkloadIdentityProviderAudience] - isWorkloadIdentity = credentialsFile.CredentialsType == gcpAccountTypeExternal - ) - if isWorkloadIdentity { - if len(audience) == 0 { + return credentialsFile.CredentialsSource.File, credentialsFile.CredentialsType, nil +} + +func extractGCSConfigSecret(s *corev1.Secret, credentialMode lokiv1.CredentialMode) (*storage.GCSStorageConfig, error) { + // Extract and validate mandatory fields + bucket := s.Data[storage.KeyGCPStorageBucketName] + if len(bucket) == 0 { + return nil, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyGCPStorageBucketName) + } + + switch credentialMode { + case lokiv1.CredentialModeStatic: + return &storage.GCSStorageConfig{ + Bucket: string(bucket), + }, nil + case lokiv1.CredentialModeToken: + audience := string(s.Data[storage.KeyGCPWorkloadIdentityProviderAudience]) + if audience == "" { return nil, fmt.Errorf("%w: %s", errSecretMissingField, storage.KeyGCPWorkloadIdentityProviderAudience) } - if credentialsFile.CredentialsSource.File != storage.ServiceAccountTokenFilePath { + // Check if correct credential source is used + credentialSource, _, err := extractGoogleCredentialSource(s) + if err != nil { + return nil, err + } + + if credentialSource != storage.ServiceAccountTokenFilePath { return nil, fmt.Errorf("%w: %s", errGCPWrongCredentialSourceFile, storage.ServiceAccountTokenFilePath) } + + return &storage.GCSStorageConfig{ + Bucket: string(bucket), + WorkloadIdentity: true, + Audience: audience, + }, nil + case lokiv1.CredentialModeManaged: + return nil, fmt.Errorf("%w: type: %s credentialMode: %s", errSecretUnsupportedCredentialMode, lokiv1.ObjectStorageSecretGCS, credentialMode) + default: } - return &storage.GCSStorageConfig{ - Bucket: string(bucket), - WorkloadIdentity: isWorkloadIdentity, - Audience: string(audience), - }, nil + return nil, fmt.Errorf("%w: %s", errSecretUnknownCredentialMode, credentialMode) } -func extractS3ConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage.S3StorageConfig, error) { +func extractS3ConfigSecret(s *corev1.Secret, credentialMode lokiv1.CredentialMode) (*storage.S3StorageConfig, error) { // Extract and validate mandatory fields buckets := s.Data[storage.KeyAWSBucketNames] if len(buckets) == 0 { @@ -338,13 +408,8 @@ func extractS3ConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage SSE: sseCfg, } - var ( - isManagedAuthEnv = len(roleArn) != 0 - isStaticAuthEnv = !isManagedAuthEnv - ) - - switch { - case fg.OpenShift.ManagedAuthEnv: + switch credentialMode { + case lokiv1.CredentialModeManaged: cfg.STS = true cfg.Audience = string(audience) // Do not allow users overriding the role arn provided on Loki Operator installation @@ -357,7 +422,7 @@ func extractS3ConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage } return cfg, nil - case isStaticAuthEnv: + case lokiv1.CredentialModeStatic: cfg.Endpoint = string(endpoint) if len(endpoint) == 0 { @@ -371,7 +436,7 @@ func extractS3ConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage } return cfg, nil - case isManagedAuthEnv: // Extract STS from user provided values + case lokiv1.CredentialModeToken: // Extract STS from user provided values cfg.STS = true cfg.Audience = string(audience) @@ -381,7 +446,7 @@ func extractS3ConfigSecret(s *corev1.Secret, fg configv1.FeatureGates) (*storage } return cfg, nil default: - return nil, errS3NoAuth + return nil, fmt.Errorf("%w: %s", errSecretUnknownCredentialMode, credentialMode) } } diff --git a/operator/internal/handlers/internal/storage/secrets_test.go b/operator/internal/handlers/internal/storage/secrets_test.go index 647de5632b4bf..6e4fc98f11241 100644 --- a/operator/internal/handlers/internal/storage/secrets_test.go +++ b/operator/internal/handlers/internal/storage/secrets_test.go @@ -65,7 +65,10 @@ func TestHashSecretData(t *testing.T) { func TestUnknownType(t *testing.T) { wantError := "unknown secret type: test-unknown-type" - _, err := extractSecrets("test-unknown-type", &corev1.Secret{}, nil, configv1.FeatureGates{}) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: "test-unknown-type", + } + _, err := extractSecrets(spec, &corev1.Secret{}, nil, configv1.FeatureGates{}) require.EqualError(t, err, wantError) } @@ -112,32 +115,6 @@ func TestAzureExtract(t *testing.T) { }, wantError: "missing secret field: container", }, - { - name: "no account_key or client_id", - secret: &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "test"}, - Data: map[string][]byte{ - "environment": []byte("AzureGlobal"), - "container": []byte("this,that"), - "account_name": []byte("id"), - }, - }, - wantError: errAzureNoCredentials.Error(), - }, - { - name: "both account_key and client_id set", - secret: &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "test"}, - Data: map[string][]byte{ - "environment": []byte("AzureGlobal"), - "container": []byte("this,that"), - "account_name": []byte("test-account-name"), - "account_key": []byte("test-account-key"), - "client_id": []byte("test-client-id"), - }, - }, - wantError: errAzureMixedCredentials.Error(), - }, { name: "missing tenant_id", secret: &corev1.Secret{ @@ -280,13 +257,17 @@ func TestAzureExtract(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretAzure, tst.secret, tst.managedSecret, tst.featureGates) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretAzure, + } + + opts, err := extractSecrets(spec, tst.secret, tst.managedSecret, tst.featureGates) if tst.wantError == "" { require.NoError(t, err) require.NotEmpty(t, opts.SecretName) require.NotEmpty(t, opts.SecretSHA1) require.Equal(t, lokiv1.ObjectStorageSecretAzure, opts.SharedStore) - require.Equal(t, tst.wantCredentialMode, opts.CredentialMode()) + require.Equal(t, tst.wantCredentialMode, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } @@ -303,18 +284,20 @@ func TestGCSExtract(t *testing.T) { } table := []test{ { - name: "missing bucketname", - secret: &corev1.Secret{}, - wantError: "missing secret field: bucketname", + name: "missing key.json", + secret: &corev1.Secret{ + Data: map[string][]byte{}, + }, + wantError: "missing secret field: key.json", }, { - name: "missing key.json", + name: "missing bucketname", secret: &corev1.Secret{ Data: map[string][]byte{ - "bucketname": []byte("here"), + "key.json": []byte("{\"type\": \"service_account\"}"), }, }, - wantError: "missing secret field: key.json", + wantError: "missing secret field: bucketname", }, { name: "missing audience", @@ -368,10 +351,14 @@ func TestGCSExtract(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretGCS, tst.secret, nil, configv1.FeatureGates{}) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretGCS, + } + + opts, err := extractSecrets(spec, tst.secret, nil, configv1.FeatureGates{}) if tst.wantError == "" { require.NoError(t, err) - require.Equal(t, tst.wantCredentialMode, opts.CredentialMode()) + require.Equal(t, tst.wantCredentialMode, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } @@ -549,13 +536,17 @@ func TestS3Extract(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretS3, tst.secret, nil, configv1.FeatureGates{}) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretS3, + } + + opts, err := extractSecrets(spec, tst.secret, nil, configv1.FeatureGates{}) if tst.wantError == "" { require.NoError(t, err) require.NotEmpty(t, opts.SecretName) require.NotEmpty(t, opts.SecretSHA1) require.Equal(t, lokiv1.ObjectStorageSecretS3, opts.SharedStore) - require.Equal(t, tst.wantCredentialMode, opts.CredentialMode()) + require.Equal(t, tst.wantCredentialMode, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } @@ -624,7 +615,11 @@ func TestS3Extract_WithOpenShiftManagedAuth(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretS3, tst.secret, tst.managedAuthSecret, fg) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretS3, + } + + opts, err := extractSecrets(spec, tst.secret, tst.managedAuthSecret, fg) if tst.wantError == "" { require.NoError(t, err) require.NotEmpty(t, opts.SecretName) @@ -633,7 +628,7 @@ func TestS3Extract_WithOpenShiftManagedAuth(t *testing.T) { require.True(t, opts.S3.STS) require.Equal(t, tst.managedAuthSecret.Name, opts.OpenShift.CloudCredentials.SecretName) require.NotEmpty(t, opts.OpenShift.CloudCredentials.SHA1) - require.Equal(t, lokiv1.CredentialModeManaged, opts.CredentialMode()) + require.Equal(t, lokiv1.CredentialModeManaged, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } @@ -776,13 +771,17 @@ func TestSwiftExtract(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretSwift, tst.secret, nil, configv1.FeatureGates{}) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretSwift, + } + + opts, err := extractSecrets(spec, tst.secret, nil, configv1.FeatureGates{}) if tst.wantError == "" { require.NoError(t, err) require.NotEmpty(t, opts.SecretName) require.NotEmpty(t, opts.SecretSHA1) require.Equal(t, lokiv1.ObjectStorageSecretSwift, opts.SharedStore) - require.Equal(t, lokiv1.CredentialModeStatic, opts.CredentialMode()) + require.Equal(t, lokiv1.CredentialModeStatic, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } @@ -850,13 +849,17 @@ func TestAlibabaCloudExtract(t *testing.T) { t.Run(tst.name, func(t *testing.T) { t.Parallel() - opts, err := extractSecrets(lokiv1.ObjectStorageSecretAlibabaCloud, tst.secret, nil, configv1.FeatureGates{}) + spec := lokiv1.ObjectStorageSecretSpec{ + Type: lokiv1.ObjectStorageSecretAlibabaCloud, + } + + opts, err := extractSecrets(spec, tst.secret, nil, configv1.FeatureGates{}) if tst.wantError == "" { require.NoError(t, err) require.NotEmpty(t, opts.SecretName) require.NotEmpty(t, opts.SecretSHA1) require.Equal(t, lokiv1.ObjectStorageSecretAlibabaCloud, opts.SharedStore) - require.Equal(t, lokiv1.CredentialModeStatic, opts.CredentialMode()) + require.Equal(t, lokiv1.CredentialModeStatic, opts.CredentialMode) } else { require.EqualError(t, err, tst.wantError) } diff --git a/operator/internal/handlers/internal/storage/storage.go b/operator/internal/handlers/internal/storage/storage.go index 32b59522ef6a5..dee185a72c85a 100644 --- a/operator/internal/handlers/internal/storage/storage.go +++ b/operator/internal/handlers/internal/storage/storage.go @@ -27,7 +27,7 @@ func BuildOptions(ctx context.Context, k k8s.Client, stack *lokiv1.LokiStack, fg return storage.Options{}, err } - objStore, err := extractSecrets(stack.Spec.Storage.Secret.Type, storageSecret, managedAuthSecret, fg) + objStore, err := extractSecrets(stack.Spec.Storage.Secret, storageSecret, managedAuthSecret, fg) if err != nil { return storage.Options{}, &status.DegradedError{ Message: fmt.Sprintf("Invalid object storage secret contents: %s", err), @@ -35,7 +35,15 @@ func BuildOptions(ctx context.Context, k k8s.Client, stack *lokiv1.LokiStack, fg Requeue: false, } } - objStore.OpenShift.Enabled = fg.OpenShift.Enabled + + if objStore.CredentialMode == lokiv1.CredentialModeManaged && managedAuthSecret == nil { + // If we have no managed-auth secret at this point, it is an error + return storage.Options{}, &status.DegradedError{ + Message: "Missing OpenShift cloud credentials secret", + Reason: lokiv1.ReasonMissingManagedAuthSecret, + Requeue: true, + } + } storageSchemas, err := storage.BuildSchemaConfig( time.Now().UTC(), diff --git a/operator/internal/handlers/internal/storage/storage_test.go b/operator/internal/handlers/internal/storage/storage_test.go index 45f5b0f2865ba..9a11f6b2a8a02 100644 --- a/operator/internal/handlers/internal/storage/storage_test.go +++ b/operator/internal/handlers/internal/storage/storage_test.go @@ -53,7 +53,8 @@ var ( Namespace: "some-ns", }, Data: map[string][]byte{ - "region": []byte("a-region"), + "bucketnames": []byte("bucket1,bucket2"), + "region": []byte("a-region"), }, } diff --git a/operator/internal/handlers/lokistack_create_or_update.go b/operator/internal/handlers/lokistack_create_or_update.go index 47e7a309bf8b9..dbb5a110d3b07 100644 --- a/operator/internal/handlers/lokistack_create_or_update.go +++ b/operator/internal/handlers/lokistack_create_or_update.go @@ -214,7 +214,7 @@ func CreateOrUpdateLokiStack( metrics.Collect(&opts.Stack, opts.Name) } - return objStore.CredentialMode(), nil + return objStore.CredentialMode, nil } func dependentAnnotations(ctx context.Context, k k8s.Client, obj client.Object) (map[string]string, error) { diff --git a/operator/internal/manifests/storage/configure.go b/operator/internal/manifests/storage/configure.go index ede098425323d..a8c0b32fb15b2 100644 --- a/operator/internal/manifests/storage/configure.go +++ b/operator/internal/manifests/storage/configure.go @@ -301,16 +301,14 @@ func envVarFromValue(name, value string) corev1.EnvVar { } func managedAuthEnabled(opts Options) bool { - switch opts.SharedStore { - case lokiv1.ObjectStorageSecretS3: - return opts.S3 != nil && opts.S3.STS - case lokiv1.ObjectStorageSecretAzure: - return opts.Azure != nil && opts.Azure.WorkloadIdentity - case lokiv1.ObjectStorageSecretGCS: - return opts.GCS != nil && opts.GCS.WorkloadIdentity + switch opts.CredentialMode { + case lokiv1.CredentialModeToken, lokiv1.CredentialModeManaged: + return true + case lokiv1.CredentialModeStatic: + fallthrough default: - return false } + return false } func saTokenVolume(opts Options) corev1.Volume { diff --git a/operator/internal/manifests/storage/configure_test.go b/operator/internal/manifests/storage/configure_test.go index 2cd7b079a4b4a..cd2b5514b469d 100644 --- a/operator/internal/manifests/storage/configure_test.go +++ b/operator/internal/manifests/storage/configure_test.go @@ -171,8 +171,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage Azure with WIF", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeToken, Azure: &AzureStorageConfig{ WorkloadIdentity: true, }, @@ -295,8 +296,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage Azure with WIF and custom audience", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeToken, Azure: &AzureStorageConfig{ WorkloadIdentity: true, Audience: "custom-audience", @@ -420,8 +422,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage Azure with WIF and OpenShift Managed Credentials", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeManaged, Azure: &AzureStorageConfig{ WorkloadIdentity: true, }, @@ -607,8 +610,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage GCS with Workload Identity", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretGCS, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretGCS, + CredentialMode: lokiv1.CredentialModeToken, GCS: &GCSStorageConfig{ Audience: "test", WorkloadIdentity: true, @@ -762,8 +766,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage S3 in STS Mode", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretS3, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretS3, + CredentialMode: lokiv1.CredentialModeToken, S3: &S3StorageConfig{ STS: true, Audience: "test", @@ -854,8 +859,9 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { { desc: "object storage S3 in STS Mode in OpenShift", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretS3, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretS3, + CredentialMode: lokiv1.CredentialModeManaged, S3: &S3StorageConfig{ STS: true, }, @@ -951,6 +957,81 @@ func TestConfigureDeploymentForStorageType(t *testing.T) { }, }, }, + { + desc: "object storage S3 with static credentials in OpenShift CCO cluster", + opts: Options{ + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretS3, + CredentialMode: lokiv1.CredentialModeStatic, + }, + dpl: &appsv1.Deployment{ + Spec: appsv1.DeploymentSpec{ + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "loki-ingester", + }, + }, + }, + }, + }, + }, + want: &appsv1.Deployment{ + Spec: appsv1.DeploymentSpec{ + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "loki-ingester", + VolumeMounts: []corev1.VolumeMount{ + { + Name: "test", + ReadOnly: false, + MountPath: "/etc/storage/secrets", + }, + }, + Env: []corev1.EnvVar{ + { + Name: EnvAWSAccessKeyID, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test", + }, + Key: KeyAWSAccessKeyID, + }, + }, + }, + { + Name: EnvAWSAccessKeySecret, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test", + }, + Key: KeyAWSAccessKeySecret, + }, + }, + }, + }, + }, + }, + Volumes: []corev1.Volume{ + { + Name: "test", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "test", + }, + }, + }, + }, + }, + }, + }, + }, + }, { desc: "object storage S3 with SSE KMS encryption context", opts: Options{ @@ -1289,8 +1370,9 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { { desc: "object storage Azure with WIF", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeToken, Azure: &AzureStorageConfig{ WorkloadIdentity: true, }, @@ -1413,8 +1495,9 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { { desc: "object storage Azure with WIF and custom audience", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeToken, Azure: &AzureStorageConfig{ WorkloadIdentity: true, Audience: "custom-audience", @@ -1538,8 +1621,9 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { { desc: "object storage Azure with WIF and OpenShift Managed Credentials", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretAzure, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretAzure, + CredentialMode: lokiv1.CredentialModeManaged, Azure: &AzureStorageConfig{ WorkloadIdentity: true, }, @@ -1725,8 +1809,9 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { { desc: "object storage GCS with Workload Identity", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretGCS, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretGCS, + CredentialMode: lokiv1.CredentialModeManaged, GCS: &GCSStorageConfig{ Audience: "test", WorkloadIdentity: true, @@ -1880,8 +1965,9 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { { desc: "object storage S3 in STS Mode in OpenShift", opts: Options{ - SecretName: "test", - SharedStore: lokiv1.ObjectStorageSecretS3, + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretS3, + CredentialMode: lokiv1.CredentialModeManaged, S3: &S3StorageConfig{ STS: true, }, @@ -1977,6 +2063,91 @@ func TestConfigureStatefulSetForStorageType(t *testing.T) { }, }, }, + { + desc: "object storage S3 with static credentials in OpenShift CCO cluster", + opts: Options{ + SecretName: "test", + SharedStore: lokiv1.ObjectStorageSecretS3, + CredentialMode: lokiv1.CredentialModeStatic, + S3: &S3StorageConfig{ + STS: true, + }, + OpenShift: OpenShiftOptions{ + Enabled: true, + CloudCredentials: CloudCredentials{ + SecretName: "cloud-credentials", + SHA1: "deadbeef", + }, + }, + }, + sts: &appsv1.StatefulSet{ + Spec: appsv1.StatefulSetSpec{ + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "loki-ingester", + }, + }, + }, + }, + }, + }, + want: &appsv1.StatefulSet{ + Spec: appsv1.StatefulSetSpec{ + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "loki-ingester", + VolumeMounts: []corev1.VolumeMount{ + { + Name: "test", + ReadOnly: false, + MountPath: "/etc/storage/secrets", + }, + }, + Env: []corev1.EnvVar{ + { + Name: EnvAWSAccessKeyID, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test", + }, + Key: KeyAWSAccessKeyID, + }, + }, + }, + { + Name: EnvAWSAccessKeySecret, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test", + }, + Key: KeyAWSAccessKeySecret, + }, + }, + }, + }, + }, + }, + Volumes: []corev1.Volume{ + { + Name: "test", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "test", + }, + }, + }, + }, + }, + }, + }, + }, + }, { desc: "object storage S3 with SSE KMS encryption Context", opts: Options{ diff --git a/operator/internal/manifests/storage/options.go b/operator/internal/manifests/storage/options.go index 56e2b8e870df1..4a29a59b83f0d 100644 --- a/operator/internal/manifests/storage/options.go +++ b/operator/internal/manifests/storage/options.go @@ -7,8 +7,9 @@ import ( // Options is used to configure Loki to integrate with // supported object storages. type Options struct { - Schemas []lokiv1.ObjectStorageSchema - SharedStore lokiv1.ObjectStorageSecretType + Schemas []lokiv1.ObjectStorageSchema + SharedStore lokiv1.ObjectStorageSecretType + CredentialMode lokiv1.CredentialMode Azure *AzureStorageConfig GCS *GCSStorageConfig @@ -23,40 +24,6 @@ type Options struct { OpenShift OpenShiftOptions } -// CredentialMode returns which mode is used by the current storage configuration. -// This defaults to CredentialModeStatic, but can be CredentialModeToken -// or CredentialModeManaged depending on the object storage provide, the provided -// secret and whether the operator is running in a managed-auth cluster. -func (o Options) CredentialMode() lokiv1.CredentialMode { - if o.Azure != nil { - if o.OpenShift.ManagedAuthEnabled() { - return lokiv1.CredentialModeManaged - } - - if o.Azure.WorkloadIdentity { - return lokiv1.CredentialModeToken - } - } - - if o.GCS != nil { - if o.GCS.WorkloadIdentity { - return lokiv1.CredentialModeToken - } - } - - if o.S3 != nil { - if o.OpenShift.ManagedAuthEnabled() { - return lokiv1.CredentialModeManaged - } - - if o.S3.STS { - return lokiv1.CredentialModeToken - } - } - - return lokiv1.CredentialModeStatic -} - // AzureStorageConfig for Azure storage config type AzureStorageConfig struct { Env string
feat
Allow setting explicit CredentialMode in LokiStack storage spec (#12106)
f22527f3d91b58c230b8ea1f831b5221060d1bbe
2025-02-10 21:05:55
Paul Rogers
fix(ci): Pass image tag details to logcli docker build (#16159)
false
diff --git a/cmd/logcli/Dockerfile b/cmd/logcli/Dockerfile index ddccaff2a7813..c35f7fbe07dd3 100644 --- a/cmd/logcli/Dockerfile +++ b/cmd/logcli/Dockerfile @@ -1,9 +1,10 @@ ARG GO_VERSION=1.23 +ARG IMAGE_TAG FROM golang:${GO_VERSION} AS build COPY . /src/loki WORKDIR /src/loki -RUN make clean && make BUILD_IN_CONTAINER=false logcli +RUN make clean && make BUILD_IN_CONTAINER=false IMAGE_TAG=${IMAGE_TAG} logcli FROM gcr.io/distroless/static:debug
fix
Pass image tag details to logcli docker build (#16159)
663b950ef16e6a4f022efd18a86c247050d5b509
2024-12-14 03:29:50
renovate[bot]
chore(deps): update anchore/sbom-action action to v0.17.9 (#15414)
false
diff --git a/.github/workflows/syft-sbom-ci.yml b/.github/workflows/syft-sbom-ci.yml index 8c5e437c4a34e..7c4f664faed59 100644 --- a/.github/workflows/syft-sbom-ci.yml +++ b/.github/workflows/syft-sbom-ci.yml @@ -14,7 +14,7 @@ jobs: uses: actions/checkout@v4 - name: Anchore SBOM Action - uses: anchore/[email protected] + uses: anchore/[email protected] with: artifact-name: ${{ github.event.repository.name }}-spdx.json
chore
update anchore/sbom-action action to v0.17.9 (#15414)
13d45bc5127adc3ec55848ee4b5e25cc597d309b
2024-04-13 01:20:04
Paul Rogers
test: Fix deadlock in table_manager relating to Stop/SyncTables (#12597)
false
diff --git a/pkg/storage/store_test.go b/pkg/storage/store_test.go index a60c183fe022f..45a505be3f439 100644 --- a/pkg/storage/store_test.go +++ b/pkg/storage/store_test.go @@ -1932,6 +1932,76 @@ func TestStore_BoltdbTsdbSameIndexPrefix(t *testing.T) { } } +func TestStore_SyncStopInteraction(t *testing.T) { + tempDir := t.TempDir() + + ingesterName := "ingester-1" + limits, err := validation.NewOverrides(validation.Limits{}, nil) + require.NoError(t, err) + + // config for BoltDB Shipper + boltdbShipperConfig := boltdb.IndexCfg{} + flagext.DefaultValues(&boltdbShipperConfig) + boltdbShipperConfig.ActiveIndexDirectory = path.Join(tempDir, "boltdb-index") + boltdbShipperConfig.CacheLocation = path.Join(tempDir, "boltdb-shipper-cache") + boltdbShipperConfig.Mode = indexshipper.ModeReadWrite + boltdbShipperConfig.IngesterName = ingesterName + boltdbShipperConfig.ResyncInterval = time.Millisecond + + // config for tsdb Shipper + tsdbShipperConfig := indexshipper.Config{} + flagext.DefaultValues(&tsdbShipperConfig) + tsdbShipperConfig.ActiveIndexDirectory = path.Join(tempDir, "tsdb-index") + tsdbShipperConfig.CacheLocation = path.Join(tempDir, "tsdb-shipper-cache") + tsdbShipperConfig.Mode = indexshipper.ModeReadWrite + tsdbShipperConfig.IngesterName = ingesterName + tsdbShipperConfig.ResyncInterval = time.Millisecond + + // dates for activation of boltdb shippers + boltdbShipperStartDate := parseDate("2019-01-01") + tsdbStartDate := parseDate("2019-01-02") + + cfg := Config{ + FSConfig: local.FSConfig{Directory: path.Join(tempDir, "chunks")}, + BoltDBShipperConfig: boltdbShipperConfig, + TSDBShipperConfig: tsdbShipperConfig, + } + + schemaConfig := config.SchemaConfig{ + Configs: []config.PeriodConfig{ + { + From: config.DayTime{Time: timeToModelTime(boltdbShipperStartDate)}, + IndexType: "boltdb-shipper", + ObjectType: types.StorageTypeFileSystem, + Schema: "v12", + IndexTables: config.IndexPeriodicTableConfig{ + PathPrefix: "index/", + PeriodicTableConfig: config.PeriodicTableConfig{ + Prefix: "index_", + Period: time.Hour * 24, + }}, + RowShards: 2, + }, + { + From: config.DayTime{Time: timeToModelTime(tsdbStartDate)}, + IndexType: "tsdb", + ObjectType: types.StorageTypeFileSystem, + Schema: "v12", + IndexTables: config.IndexPeriodicTableConfig{ + PathPrefix: "index/", + PeriodicTableConfig: config.PeriodicTableConfig{ + Prefix: "index_", + Period: time.Hour * 24, + }}, + }, + }, + } + + store, err := NewStore(cfg, config.ChunkStoreConfig{}, schemaConfig, limits, cm, nil, log.NewNopLogger(), constants.Loki) + require.NoError(t, err) + store.Stop() +} + func TestQueryReferencingStructuredMetadata(t *testing.T) { ctx := user.InjectOrgID(context.Background(), "fake") tempDir := t.TempDir() diff --git a/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go b/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go index 12e8a9373ed7d..9f2401c209d0e 100644 --- a/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go +++ b/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go @@ -153,10 +153,9 @@ func (tm *tableManager) loop() { func (tm *tableManager) Stop() { tm.cancel() - + tm.wg.Wait() tm.tablesMtx.Lock() defer tm.tablesMtx.Unlock() - tm.wg.Wait() for _, table := range tm.tables { table.Close()
test
Fix deadlock in table_manager relating to Stop/SyncTables (#12597)
08615bf7519b31e825903577427f7407194baf74
2024-07-11 20:56:26
Karsten Jeschkies
fix: Return empty vector instead of nil for empty evaluator. (#13485)
false
diff --git a/pkg/logql/engine.go b/pkg/logql/engine.go index f35a1b397a3b0..0a26520b673c7 100644 --- a/pkg/logql/engine.go +++ b/pkg/logql/engine.go @@ -378,11 +378,10 @@ func (q *query) evalSample(ctx context.Context, expr syntax.SampleExpr) (promql_ return nil, fmt.Errorf("unsupported result type: %T", r) } } - return nil, nil + return nil, errors.New("unexpected empty result") } func (q *query) JoinSampleVector(next bool, r StepResult, stepEvaluator StepEvaluator, maxSeries int) (promql_parser.Value, error) { - seriesIndex := map[uint64]*promql.Series{} vec := promql.Vector{} diff --git a/pkg/logql/engine_test.go b/pkg/logql/engine_test.go index b409422c1c8fc..23bcbac91e0f6 100644 --- a/pkg/logql/engine_test.go +++ b/pkg/logql/engine_test.go @@ -65,15 +65,17 @@ func TestEngine_LogsRateUnwrap(t *testing.T) { {newSeries(testSize, offset(46, constantValue(1)), `{app="foo"}`)}, }, []SelectSampleParams{ - {&logproto.SampleQueryRequest{ - Start: time.Unix(30, 0), - End: time.Unix(60, 0), - Selector: `rate({app="foo"} | unwrap foo[30s])`, - Plan: &plan.QueryPlan{ - AST: syntax.MustParseExpr(`rate({app="foo"} | unwrap foo[30s])`), + { + &logproto.SampleQueryRequest{ + Start: time.Unix(30, 0), + End: time.Unix(60, 0), + Selector: `rate({app="foo"} | unwrap foo[30s])`, + Plan: &plan.QueryPlan{ + AST: syntax.MustParseExpr(`rate({app="foo"} | unwrap foo[30s])`), + }, }, }, - }}, + }, // there are 15 samples (from 47 to 61) matched from the generated series // SUM(n=47, 61, 1) = 15 // 15 / 30 = 0.5 @@ -955,7 +957,6 @@ func TestEngine_InstantQuery(t *testing.T) { } { test := test t.Run(fmt.Sprintf("%s %s", test.qs, test.direction), func(t *testing.T) { - eng := NewEngine(EngineOpts{}, newQuerierRecorder(t, test.data, test.params), NoLimits, log.NewNopLogger()) params, err := NewLiteralParams(test.qs, test.ts, test.ts, 0, 0, test.direction, test.limit, nil, nil) @@ -1590,10 +1591,12 @@ func TestEngine_RangeQuery(t *testing.T) { promql.Series{ // vector result Metric: labels.Labels(nil), - Floats: []promql.FPoint{{T: 60000, F: 0}, {T: 80000, F: 0}, {T: 100000, F: 0}, {T: 120000, F: 0}, {T: 140000, F: 0}, {T: 160000, F: 0}, {T: 180000, F: 0}}}, + Floats: []promql.FPoint{{T: 60000, F: 0}, {T: 80000, F: 0}, {T: 100000, F: 0}, {T: 120000, F: 0}, {T: 140000, F: 0}, {T: 160000, F: 0}, {T: 180000, F: 0}}, + }, promql.Series{ Metric: labels.FromStrings("app", "foo"), - Floats: []promql.FPoint{{T: 60000, F: 0.03333333333333333}, {T: 80000, F: 0.06666666666666667}, {T: 100000, F: 0.06666666666666667}, {T: 120000, F: 0.03333333333333333}, {T: 180000, F: 0.03333333333333333}}}, + Floats: []promql.FPoint{{T: 60000, F: 0.03333333333333333}, {T: 80000, F: 0.06666666666666667}, {T: 100000, F: 0.06666666666666667}, {T: 120000, F: 0.03333333333333333}, {T: 180000, F: 0.03333333333333333}}, + }, }, }, { @@ -2635,6 +2638,31 @@ func TestHashingStability(t *testing.T) { } } +func TestUnexpectedEmptyResults(t *testing.T) { + ctx := user.InjectOrgID(context.Background(), "fake") + + mock := &mockEvaluatorFactory{SampleEvaluatorFunc(func(context.Context, SampleEvaluatorFactory, syntax.SampleExpr, Params) (StepEvaluator, error) { + return EmptyEvaluator[SampleVector]{value: nil}, nil + })} + + eng := NewEngine(EngineOpts{}, nil, NoLimits, log.NewNopLogger()) + params, err := NewLiteralParams(`first_over_time({a=~".+"} | logfmt | unwrap value [1s])`, time.Now(), time.Now(), 0, 0, logproto.BACKWARD, 0, nil, nil) + require.NoError(t, err) + q := eng.Query(params).(*query) + q.evaluator = mock + + _, err = q.Exec(ctx) + require.Error(t, err) +} + +type mockEvaluatorFactory struct { + SampleEvaluatorFactory +} + +func (*mockEvaluatorFactory) NewIterator(context.Context, syntax.LogSelectorExpr, Params) (iter.EntryIterator, error) { + return nil, errors.New("unimplemented mock EntryEvaluatorFactory") +} + func getLocalQuerier(size int64) Querier { return &querierRecorder{ series: map[string][]logproto.Series{ diff --git a/pkg/logql/first_last_over_time.go b/pkg/logql/first_last_over_time.go index e24133d13bfec..6d0329cacf8d2 100644 --- a/pkg/logql/first_last_over_time.go +++ b/pkg/logql/first_last_over_time.go @@ -14,7 +14,8 @@ import ( // of a windowed aggregation. func newFirstWithTimestampIterator( it iter.PeekingSampleIterator, - selRange, step, start, end, offset int64) RangeVectorIterator { + selRange, step, start, end, offset int64, +) RangeVectorIterator { inner := &batchRangeVectorIterator{ iter: it, step: step, @@ -67,7 +68,8 @@ func (r *firstWithTimestampBatchRangeVectorIterator) agg(samples []promql.FPoint func newLastWithTimestampIterator( it iter.PeekingSampleIterator, - selRange, step, start, end, offset int64) RangeVectorIterator { + selRange, step, start, end, offset int64, +) RangeVectorIterator { inner := &batchRangeVectorIterator{ iter: it, step: step, @@ -129,10 +131,7 @@ type mergeOverTimeStepEvaluator struct { // Next returns the first or last element within one step of each matrix. func (e *mergeOverTimeStepEvaluator) Next() (bool, int64, StepResult) { - - var ( - vec promql.Vector - ) + var vec promql.Vector e.ts = e.ts.Add(e.step) if e.ts.After(e.end) { @@ -158,10 +157,6 @@ func (e *mergeOverTimeStepEvaluator) Next() (bool, int64, StepResult) { vec[i].T = ts } - if len(vec) == 0 { - return e.hasNext(), ts, SampleVector(vec) - } - return true, ts, SampleVector(vec) } @@ -179,18 +174,6 @@ func (e *mergeOverTimeStepEvaluator) inRange(t, ts int64) bool { return (ts-e.step.Milliseconds()) <= t && t < ts } -func (e *mergeOverTimeStepEvaluator) hasNext() bool { - for _, m := range e.matrices { - for _, s := range m { - if len(s.Floats) != 0 { - return true - } - } - } - - return false -} - func (*mergeOverTimeStepEvaluator) Close() error { return nil } func (*mergeOverTimeStepEvaluator) Error() error { return nil }
fix
Return empty vector instead of nil for empty evaluator. (#13485)
dc41c0d9ef86a26e7174aae700114d9384917800
2024-07-15 21:45:28
J Stickler
docs: Add Explore Logs to Release Notes (#13529)
false
diff --git a/docs/sources/release-notes/v3-1.md b/docs/sources/release-notes/v3-1.md index b32f02ee43852..d67370a4acae2 100644 --- a/docs/sources/release-notes/v3-1.md +++ b/docs/sources/release-notes/v3-1.md @@ -22,6 +22,8 @@ Key features in Loki 3.1.0 include the following: - **lokitool:** Add `lokitool` to replace `cortextool`. ([#12166](https://github.com/grafana/loki/issues/12166)) ([7b7d3d4](https://github.com/grafana/loki/commit/7b7d3d4cd2c979c778d3741156f0d765a9e531b2)). Introduce `index audit` to `lokitool` ([#13008](https://github.com/grafana/loki/issues/13008)) ([47f0236](https://github.com/grafana/loki/commit/47f0236ea8f33a67a0a1abf6e6d6b3582661c4ba)). +- **Explore Logs:** Explore Logs, which lets you explore your Loki data without writing LogQL queries, is now available in public preview. If you are a Grafana Cloud user, you can access Explore Logs in the Grafana Cloud main navigation menu. If you are not a Grafana Cloud user, you can install the [Explore Logs plugin](https://grafana.com/docs/grafana-cloud/visualizations/simplified-exploration/logs/access/). For more information, refer to the [Explore Logs documentation](https://grafana.com/docs/grafana-cloud/visualizations/simplified-exploration/logs/). + - **Docs:** Added a video to the Getting Started demo and updated for Grafana Alloy. Added an interactive sandbox to the Loki Quickstart tutorial. Updated the documentation for the SSD and microservices deployment modes using the Helm charts. Documented the new meta-monitoring Helm chart. Other improvements include the following:
docs
Add Explore Logs to Release Notes (#13529)
1763ebb5e98fa12b9c70c47c34ced97617ad47fe
2023-02-06 20:36:49
Periklis Tsirakidis
operator: Update operand Loki to v2.7.3 (#8397)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index f5fe1ccb1c6fb..f4d3a91a9e55a 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [8397](https://github.com/grafana/loki/pull/8397) **periklis**: Update Loki operand to v2.7.3 - [8308](https://github.com/grafana/loki/pull/8308) **aminesnow**: operator: Cleanup ruler resources when disabled - [8336](https://github.com/grafana/loki/pull/8336) **periklis**: Update Loki operand to v2.7.2 - [8253](https://github.com/grafana/loki/pull/8253) **aminesnow**: Add watch on the Alertmanager in openshift-monitoring and decouple it from the user-workload AM diff --git a/operator/bundle/manifests/loki-operator.clusterserviceversion.yaml b/operator/bundle/manifests/loki-operator.clusterserviceversion.yaml index 4d4f1c736efcb..1c7ccb508a297 100644 --- a/operator/bundle/manifests/loki-operator.clusterserviceversion.yaml +++ b/operator/bundle/manifests/loki-operator.clusterserviceversion.yaml @@ -1458,7 +1458,7 @@ spec: - /manager env: - name: RELATED_IMAGE_LOKI - value: quay.io/openshift-logging/loki:v2.7.2 + value: quay.io/openshift-logging/loki:v2.7.3 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA @@ -1579,7 +1579,7 @@ spec: provider: name: Grafana.com relatedImages: - - image: quay.io/openshift-logging/loki:v2.7.2 + - image: quay.io/openshift-logging/loki:v2.7.3 name: loki - image: quay.io/observatorium/api:latest name: gateway diff --git a/operator/config/overlays/development/manager_related_image_patch.yaml b/operator/config/overlays/development/manager_related_image_patch.yaml index bd48d13ab2f2d..eaf9c5070235f 100644 --- a/operator/config/overlays/development/manager_related_image_patch.yaml +++ b/operator/config/overlays/development/manager_related_image_patch.yaml @@ -9,6 +9,6 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.7.2 + value: docker.io/grafana/loki:2.7.3 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest diff --git a/operator/config/overlays/openshift/manager_related_image_patch.yaml b/operator/config/overlays/openshift/manager_related_image_patch.yaml index 7d266c6804022..01af25c31c53a 100644 --- a/operator/config/overlays/openshift/manager_related_image_patch.yaml +++ b/operator/config/overlays/openshift/manager_related_image_patch.yaml @@ -9,7 +9,7 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: quay.io/openshift-logging/loki:v2.7.2 + value: quay.io/openshift-logging/loki:v2.7.3 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA diff --git a/operator/config/overlays/production/manager_related_image_patch.yaml b/operator/config/overlays/production/manager_related_image_patch.yaml index bd48d13ab2f2d..eaf9c5070235f 100644 --- a/operator/config/overlays/production/manager_related_image_patch.yaml +++ b/operator/config/overlays/production/manager_related_image_patch.yaml @@ -9,6 +9,6 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.7.2 + value: docker.io/grafana/loki:2.7.3 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest diff --git a/operator/docs/operator/compatibility.md b/operator/docs/operator/compatibility.md index 0adb3df640eff..78b5dad5af8eb 100644 --- a/operator/docs/operator/compatibility.md +++ b/operator/docs/operator/compatibility.md @@ -29,3 +29,4 @@ The versions of Loki compatible to be run with the Loki Operator are: * v2.7.1 * v2.7.2 +* v2.7.3 diff --git a/operator/internal/manifests/var.go b/operator/internal/manifests/var.go index 3010fb893bf5c..f4d1d5b6f7f94 100644 --- a/operator/internal/manifests/var.go +++ b/operator/internal/manifests/var.go @@ -52,7 +52,7 @@ const ( EnvRelatedImageGateway = "RELATED_IMAGE_GATEWAY" // DefaultContainerImage declares the default fallback for loki image. - DefaultContainerImage = "docker.io/grafana/loki:2.7.2" + DefaultContainerImage = "docker.io/grafana/loki:2.7.3" // DefaultLokiStackGatewayImage declares the default image for lokiStack-gateway. DefaultLokiStackGatewayImage = "quay.io/observatorium/api:latest"
operator
Update operand Loki to v2.7.3 (#8397)
1f3089282a2b4139e4b04a98ccb246f81b4a7cde
2024-10-07 23:13:34
renovate[bot]
chore(deps): update dependency fluent-plugin-multi-format-parser to '~>1.1.0' (#14396)
false
diff --git a/clients/cmd/fluentd/docker/Gemfile b/clients/cmd/fluentd/docker/Gemfile index 981d6e701e63b..f52d506bc3bf9 100644 --- a/clients/cmd/fluentd/docker/Gemfile +++ b/clients/cmd/fluentd/docker/Gemfile @@ -3,4 +3,4 @@ source 'https://rubygems.org' gem 'fluentd', '1.15.3' -gem 'fluent-plugin-multi-format-parser', '~>1.0.0' +gem 'fluent-plugin-multi-format-parser', '~>1.1.0'
chore
update dependency fluent-plugin-multi-format-parser to '~>1.1.0' (#14396)
6d307e5da74d0c1ad123de1ef4f6f0b7688ae4fd
2024-04-20 21:01:52
Greg
chore(helm): set Singlebinary as trigger for replicas (#12590)
false
diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index 2927e1f5e0331..d109756fdc742 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -13,6 +13,10 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) +## 6.3.3 + +- [ENHANCEMENT] make the singlebinary set 0 the replicas number of backend, write,read. + ## 6.3.2 - [BUGFIX] Missing password for Loki-Canary when loki.auth_enabled is true diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 044ec14ad158a..176e87af7d8b6 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -3,7 +3,7 @@ name: loki description: Helm chart for Grafana Loki in simple, scalable mode type: application appVersion: 3.0.0 -version: 6.3.2 +version: 6.3.3 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index 5c99119350fb3..b9ce79499a610 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.3.2](https://img.shields.io/badge/Version-6.3.2-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.0.0](https://img.shields.io/badge/AppVersion-3.0.0-informational?style=flat-square) +![Version: 6.3.3](https://img.shields.io/badge/Version-6.3.3-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.0.0](https://img.shields.io/badge/AppVersion-3.0.0-informational?style=flat-square) Helm chart for Grafana Loki in simple, scalable mode diff --git a/production/helm/loki/templates/backend/statefulset-backend.yaml b/production/helm/loki/templates/backend/statefulset-backend.yaml index 1b7ead3ae1ad2..3deb4aa6b6c81 100644 --- a/production/helm/loki/templates/backend/statefulset-backend.yaml +++ b/production/helm/loki/templates/backend/statefulset-backend.yaml @@ -19,8 +19,12 @@ metadata: {{- end }} {{- end }} spec: -{{- if not .Values.backend.autoscaling.enabled }} - replicas: {{ .Values.backend.replicas }} +{{- if not .Values.write.autoscaling.enabled }} + {{- if eq .Values.deploymentMode "SingleBinary" }} + replicas: 0 + {{- else }} + replicas: {{ .Values.write.replicas }} + {{- end }} {{- end }} podManagementPolicy: {{ .Values.backend.podManagementPolicy }} updateStrategy: diff --git a/production/helm/loki/templates/read/statefulset-read.yaml b/production/helm/loki/templates/read/statefulset-read.yaml index 46d163442cc92..29d79c7d0c785 100644 --- a/production/helm/loki/templates/read/statefulset-read.yaml +++ b/production/helm/loki/templates/read/statefulset-read.yaml @@ -19,8 +19,12 @@ metadata: {{- end }} {{- end }} spec: -{{- if not .Values.read.autoscaling.enabled }} - replicas: {{ .Values.read.replicas }} +{{- if not .Values.write.autoscaling.enabled }} + {{- if eq .Values.deploymentMode "SingleBinary" }} + replicas: 0 + {{- else }} + replicas: {{ .Values.write.replicas }} + {{- end }} {{- end }} podManagementPolicy: {{ .Values.read.podManagementPolicy }} updateStrategy: diff --git a/production/helm/loki/templates/write/statefulset-write.yaml b/production/helm/loki/templates/write/statefulset-write.yaml index 0c89cde090ab5..54c936958b559 100644 --- a/production/helm/loki/templates/write/statefulset-write.yaml +++ b/production/helm/loki/templates/write/statefulset-write.yaml @@ -20,7 +20,11 @@ metadata: {{- end }} spec: {{- if not .Values.write.autoscaling.enabled }} + {{- if eq .Values.deploymentMode "SingleBinary" }} + replicas: 0 + {{- else }} replicas: {{ .Values.write.replicas }} + {{- end }} {{- end }} podManagementPolicy: {{ .Values.write.podManagementPolicy }} updateStrategy:
chore
set Singlebinary as trigger for replicas (#12590)
d8f0c06e5ad22bf6a640698cab07d74acc4cffd2
2025-02-24 18:29:06
renovate[bot]
fix(deps): update dependency @tanstack/react-query to v5.66.9 (main) (#16421)
false
diff --git a/pkg/ui/frontend/package-lock.json b/pkg/ui/frontend/package-lock.json index 80ce67da79524..37c15e2a543e4 100644 --- a/pkg/ui/frontend/package-lock.json +++ b/pkg/ui/frontend/package-lock.json @@ -2450,9 +2450,9 @@ } }, "node_modules/@tanstack/react-query": { - "version": "5.66.7", - "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.66.7.tgz", - "integrity": "sha512-qd3q/tUpF2K1xItfPZddk1k/8pSXnovg41XyCqJgPoyYEirMBtB0sVEVVQ/CsAOngzgWtBPXimVf4q4kM9uO6A==", + "version": "5.66.9", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.66.9.tgz", + "integrity": "sha512-NRI02PHJsP5y2gAuWKP+awamTIBFBSKMnO6UVzi03GTclmHHHInH5UzVgzi5tpu4+FmGfsdT7Umqegobtsp23A==", "license": "MIT", "dependencies": { "@tanstack/query-core": "5.66.4"
fix
update dependency @tanstack/react-query to v5.66.9 (main) (#16421)
b5b861c348bc768254fd083fb40d2820cf347be6
2024-07-17 03:30:33
Grot (@grafanabot)
fix(helm): Update yaml file `./production/helm/loki/Chart.yaml` (+1 other) (#13392)
false
diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index e09399178e205..525cf8245ac49 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -13,6 +13,10 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) +## 6.7.1 + +- [CHANGE] Changed version of Loki to 3.1.0 + ## 6.7.0 - [CHANGE] Changed version of Grafana Enterprise Logs to 3.1.0 diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 14500b78b3962..eb9a96beae195 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: loki description: Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. type: application -appVersion: 3.0.0 -version: 6.7.0 +appVersion: 3.1.0 +version: 6.7.1 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index 1197ff2090bf9..acb17fe25f140 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.7.0](https://img.shields.io/badge/Version-6.7.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.0.0](https://img.shields.io/badge/AppVersion-3.0.0-informational?style=flat-square) +![Version: 6.7.1](https://img.shields.io/badge/Version-6.7.1-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.1.0](https://img.shields.io/badge/AppVersion-3.1.0-informational?style=flat-square) Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes.
fix
Update yaml file `./production/helm/loki/Chart.yaml` (+1 other) (#13392)
ed061b3edd2a8006fddf6cad5b8226a2a1f337d6
2025-01-28 21:53:30
Christian Haudum
ci: Move IMAGE_TAG Dockerfile ARG into build phase (#15983)
false
diff --git a/clients/cmd/promtail/Dockerfile b/clients/cmd/promtail/Dockerfile index b7a1cc8659a89..2b3b0f18b5944 100644 --- a/clients/cmd/promtail/Dockerfile +++ b/clients/cmd/promtail/Dockerfile @@ -1,7 +1,7 @@ ARG GO_VERSION=1.23 -ARG IMAGE_TAG FROM golang:${GO_VERSION}-bookworm as build +ARG IMAGE_TAG COPY . /src/loki WORKDIR /src/loki diff --git a/cmd/loki-canary-boringcrypto/Dockerfile b/cmd/loki-canary-boringcrypto/Dockerfile index de0e814d5df07..a3435ac86ddf1 100644 --- a/cmd/loki-canary-boringcrypto/Dockerfile +++ b/cmd/loki-canary-boringcrypto/Dockerfile @@ -1,6 +1,6 @@ ARG GO_VERSION=1.23 -ARG IMAGE_TAG FROM golang:${GO_VERSION} as build +ARG IMAGE_TAG COPY . /src/loki WORKDIR /src/loki diff --git a/cmd/loki-canary/Dockerfile b/cmd/loki-canary/Dockerfile index f3532c804e46f..46a8a9bc5f53e 100644 --- a/cmd/loki-canary/Dockerfile +++ b/cmd/loki-canary/Dockerfile @@ -1,6 +1,6 @@ ARG GO_VERSION=1.23 -ARG IMAGE_TAG FROM golang:${GO_VERSION} AS build +ARG IMAGE_TAG COPY . /src/loki WORKDIR /src/loki diff --git a/cmd/loki/Dockerfile b/cmd/loki/Dockerfile index 13e2f80dfffb6..3718e4a3c2005 100644 --- a/cmd/loki/Dockerfile +++ b/cmd/loki/Dockerfile @@ -1,5 +1,4 @@ ARG GO_VERSION=1.23 -ARG IMAGE_TAG # UI build stage FROM node:20-alpine AS ui-builder @@ -10,6 +9,7 @@ RUN make -C pkg/dataobj/explorer/ui build # Go build stage FROM golang:${GO_VERSION} AS build +ARG IMAGE_TAG COPY . /src/loki COPY --from=ui-builder /src/loki/pkg/dataobj/explorer/dist /src/loki/pkg/dataobj/explorer/dist WORKDIR /src/loki diff --git a/cmd/querytee/Dockerfile b/cmd/querytee/Dockerfile index 9fc23f8ce316b..166bcaf49c00d 100644 --- a/cmd/querytee/Dockerfile +++ b/cmd/querytee/Dockerfile @@ -1,9 +1,10 @@ ARG GO_VERSION=1.23 FROM golang:${GO_VERSION} as build +ARG IMAGE_TAG COPY . /src/loki WORKDIR /src/loki -RUN make clean && make BUILD_IN_CONTAINER=false loki-querytee +RUN make clean && make BUILD_IN_CONTAINER=false IMAGE_TAG=${IMAGE_TAG} loki-querytee FROM gcr.io/distroless/static:debug COPY --from=build /src/loki/cmd/querytee/querytee /usr/bin/querytee
ci
Move IMAGE_TAG Dockerfile ARG into build phase (#15983)
83339cbde08139eba6f08742f3c7749f901b79ce
2025-01-28 21:31:37
Karsten Jeschkies
fix: Adjust with offset in last, first and quantile over time queries. (#15915)
false
diff --git a/pkg/logql/downstream.go b/pkg/logql/downstream.go index 6a577026a49b2..78af117c80518 100644 --- a/pkg/logql/downstream.go +++ b/pkg/logql/downstream.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/go-kit/log" "github.com/go-kit/log/level" @@ -304,6 +305,7 @@ func (e *QuantileSketchMergeExpr) Walk(f syntax.WalkFn) { type MergeFirstOverTimeExpr struct { syntax.SampleExpr downstreams []DownstreamSampleExpr + offset time.Duration } func (e MergeFirstOverTimeExpr) String() string { @@ -332,6 +334,7 @@ func (e *MergeFirstOverTimeExpr) Walk(f syntax.WalkFn) { type MergeLastOverTimeExpr struct { syntax.SampleExpr downstreams []DownstreamSampleExpr + offset time.Duration } func (e MergeLastOverTimeExpr) String() string { @@ -590,7 +593,7 @@ func (ev *DownstreamEvaluator) NewStepEvaluator( } } - return NewMergeFirstOverTimeStepEvaluator(params, xs), nil + return NewMergeFirstOverTimeStepEvaluator(params, xs, e.offset), nil case *MergeLastOverTimeExpr: queries := make([]DownstreamQuery, len(e.downstreams)) @@ -625,7 +628,7 @@ func (ev *DownstreamEvaluator) NewStepEvaluator( return nil, fmt.Errorf("unexpected type (%s) uncoercible to StepEvaluator", data.Type()) } } - return NewMergeLastOverTimeStepEvaluator(params, xs), nil + return NewMergeLastOverTimeStepEvaluator(params, xs, e.offset), nil case *CountMinSketchEvalExpr: queries := make([]DownstreamQuery, len(e.downstreams)) diff --git a/pkg/logql/downstream_test.go b/pkg/logql/downstream_test.go index 615bf80a9c276..b3c0e1ede7f15 100644 --- a/pkg/logql/downstream_test.go +++ b/pkg/logql/downstream_test.go @@ -64,6 +64,7 @@ func TestMappingEquivalence(t *testing.T) { {`avg_over_time({a=~".+"} | logfmt | drop level | unwrap value [1s])`, true, nil}, {`avg_over_time({a=~".+"} | logfmt | drop level | unwrap value [1s]) without (stream)`, true, nil}, {`quantile_over_time(0.99, {a=~".+"} | logfmt | unwrap value [1s])`, true, []string{ShardQuantileOverTime}}, + {`quantile_over_time(0.99, {a=~".+"} | logfmt | unwrap value [1s] offset 2s)`, true, []string{ShardQuantileOverTime}}, { ` (quantile_over_time(0.99, {a=~".+"} | logfmt | unwrap value [1s]) by (a) > 1) @@ -75,8 +76,12 @@ func TestMappingEquivalence(t *testing.T) { }, {`first_over_time({a=~".+"} | logfmt | unwrap value [1s])`, false, []string{ShardFirstOverTime}}, {`first_over_time({a=~".+"} | logfmt | unwrap value [1s]) by (a)`, false, []string{ShardFirstOverTime}}, + {`first_over_time({a=~".+"} | logfmt | unwrap value [1s] offset 2s) by (a)`, false, []string{ShardFirstOverTime}}, + {`first_over_time({a=~".+"} | logfmt | unwrap value [1s] offset -2s) by (a)`, false, []string{ShardFirstOverTime}}, {`last_over_time({a=~".+"} | logfmt | unwrap value [1s])`, false, []string{ShardLastOverTime}}, {`last_over_time({a=~".+"} | logfmt | unwrap value [1s]) by (a)`, false, []string{ShardLastOverTime}}, + {`last_over_time({a=~".+"} | logfmt | unwrap value [1s] offset 2s) by (a)`, false, []string{ShardLastOverTime}}, + {`last_over_time({a=~".+"} | logfmt | unwrap value [1s] offset -2s) by (a)`, false, []string{ShardLastOverTime}}, // topk prefers already-seen values in tiebreakers. Since the test data generates // the same log lines for each series & the resulting promql.Vectors aren't deterministically // sorted by labels, we don't expect this to pass. @@ -190,6 +195,7 @@ func TestMappingEquivalenceSketches(t *testing.T) { }{ {`quantile_over_time(0.70, {a=~".+"} | logfmt | unwrap value [1s]) by (a)`, 0.05}, {`quantile_over_time(0.99, {a=~".+"} | logfmt | unwrap value [1s]) by (a)`, 0.02}, + {`quantile_over_time(0.99, {a=~".+"} | logfmt | unwrap value [1s] offset 2s) by (a)`, 0.02}, } { q := NewMockQuerier( shards, @@ -241,8 +247,8 @@ func TestMappingEquivalenceSketches(t *testing.T) { // plus set step and interval to 0 params, err := NewLiteralParams( tc.query, - time.Unix(1, 0), - time.Unix(1, 0), + time.Unix(10, 0), + time.Unix(10, 0), 0, 0, logproto.FORWARD, @@ -294,7 +300,7 @@ func TestApproxTopkSketches(t *testing.T) { shardedQuery string regularQuery string realtiveError float64 - //cardinalityEstimate int + // cardinalityEstimate int }{ // Note:our data generation results in less spread between topk things for 10k streams than for 100k streams // if we have 1k streams, we can get much more accurate results for topk 10 than topk 100 @@ -304,7 +310,7 @@ func TestApproxTopkSketches(t *testing.T) { shardedQuery: `approx_topk(3, sum by (a) (sum_over_time ({a=~".+"} | logfmt | unwrap value [1s])))`, regularQuery: `topk(3, sum by (a) (sum_over_time ({a=~".+"} | logfmt | unwrap value [1s])))`, realtiveError: 0.0012, - //cardinalityEstimate: 3, + // cardinalityEstimate: 3, }, { labelShards: 10, diff --git a/pkg/logql/first_last_over_time.go b/pkg/logql/first_last_over_time.go index 4b6bbde55173c..f379401d47ac6 100644 --- a/pkg/logql/first_last_over_time.go +++ b/pkg/logql/first_last_over_time.go @@ -16,6 +16,15 @@ func newFirstWithTimestampIterator( it iter.PeekingSampleIterator, selRange, step, start, end, offset int64, ) RangeVectorIterator { + // forces at least one step. + if step == 0 { + step = 1 + } + if offset != 0 { + start = start - offset + end = end - offset + } + inner := &batchRangeVectorIterator{ iter: it, step: step, @@ -70,6 +79,15 @@ func newLastWithTimestampIterator( it iter.PeekingSampleIterator, selRange, step, start, end, offset int64, ) RangeVectorIterator { + // forces at least one step. + if step == 0 { + step = 1 + } + if offset != 0 { + start = start - offset + end = end - offset + } + inner := &batchRangeVectorIterator{ iter: it, step: step, @@ -127,6 +145,7 @@ type mergeOverTimeStepEvaluator struct { step time.Duration matrices []promql.Matrix merge func(promql.Vector, int, int, promql.Series) promql.Vector + offset time.Duration } // Next returns the first or last element within one step of each matrix. @@ -170,6 +189,10 @@ func (e *mergeOverTimeStepEvaluator) pop(r, s int) { // inRange returns true if t is in step range of ts. func (e *mergeOverTimeStepEvaluator) inRange(t, ts int64) bool { + // The time stamp needs to be adjusted because the original datapoint at t is + // from a shifted query. + ts -= e.offset.Milliseconds() + // special case instant queries if e.step.Milliseconds() == 0 { return true @@ -181,7 +204,7 @@ func (*mergeOverTimeStepEvaluator) Close() error { return nil } func (*mergeOverTimeStepEvaluator) Error() error { return nil } -func NewMergeFirstOverTimeStepEvaluator(params Params, m []promql.Matrix) StepEvaluator { +func NewMergeFirstOverTimeStepEvaluator(params Params, m []promql.Matrix, offset time.Duration) StepEvaluator { if len(m) == 0 { return EmptyEvaluator[SampleVector]{} } @@ -199,6 +222,7 @@ func NewMergeFirstOverTimeStepEvaluator(params Params, m []promql.Matrix) StepEv step: step, matrices: m, merge: mergeFirstOverTime, + offset: offset, } } @@ -218,7 +242,7 @@ func mergeFirstOverTime(vec promql.Vector, pos int, nSeries int, series promql.S return vec } -func NewMergeLastOverTimeStepEvaluator(params Params, m []promql.Matrix) StepEvaluator { +func NewMergeLastOverTimeStepEvaluator(params Params, m []promql.Matrix, offset time.Duration) StepEvaluator { if len(m) == 0 { return EmptyEvaluator[SampleVector]{} } @@ -236,6 +260,7 @@ func NewMergeLastOverTimeStepEvaluator(params Params, m []promql.Matrix) StepEva step: step, matrices: m, merge: mergeLastOverTime, + offset: offset, } } diff --git a/pkg/logql/quantile_over_time_sketch.go b/pkg/logql/quantile_over_time_sketch.go index 49eca3453e081..538013e7c6e66 100644 --- a/pkg/logql/quantile_over_time_sketch.go +++ b/pkg/logql/quantile_over_time_sketch.go @@ -185,6 +185,15 @@ func newQuantileSketchIterator( it iter.PeekingSampleIterator, selRange, step, start, end, offset int64, ) RangeVectorIterator { + // forces at least one step. + if step == 0 { + step = 1 + } + if offset != 0 { + start = start - offset + end = end - offset + } + inner := &batchRangeVectorIterator{ iter: it, step: step, @@ -302,23 +311,20 @@ func JoinQuantileSketchVector(next bool, r StepResult, stepEvaluator StepEvaluat // QuantileSketchMatrixStepEvaluator steps through a matrix of quantile sketch // vectors, ie t-digest or DDSketch structures per time step. type QuantileSketchMatrixStepEvaluator struct { - start, end, ts time.Time - step time.Duration - m ProbabilisticQuantileMatrix + end, ts time.Time + step time.Duration + m ProbabilisticQuantileMatrix } func NewQuantileSketchMatrixStepEvaluator(m ProbabilisticQuantileMatrix, params Params) *QuantileSketchMatrixStepEvaluator { var ( - start = params.Start() - end = params.End() - step = params.Step() + step = params.Step() ) return &QuantileSketchMatrixStepEvaluator{ - start: start, - end: end, - ts: start.Add(-step), // will be corrected on first Next() call - step: step, - m: m, + end: params.End(), + ts: params.Start().Add(-step), // will be corrected on first Next() call + step: step, + m: m, } } diff --git a/pkg/logql/range_vector_test.go b/pkg/logql/range_vector_test.go index 0fe81e7e2a193..f0ee5454b6334 100644 --- a/pkg/logql/range_vector_test.go +++ b/pkg/logql/range_vector_test.go @@ -67,7 +67,6 @@ func newPoint(t time.Time, v float64) promql.FPoint { } func Benchmark_RangeVectorIteratorCompare(b *testing.B) { - // no overlap test case. buildStreamingIt := func() (RangeVectorIterator, error) { tt := struct { @@ -183,7 +182,6 @@ func Benchmark_RangeVectorIteratorCompare(b *testing.B) { } } }) - } func Benchmark_RangeVectorIterator(b *testing.B) { @@ -214,7 +212,6 @@ func Benchmark_RangeVectorIterator(b *testing.B) { i++ } } - } func Test_RangeVectorIterator_InstantQuery(t *testing.T) { @@ -445,6 +442,7 @@ func Test_RangeVectorIterator(t *testing.T) { time.Unix(110, 0), time.Unix(120, 0), }, { + // TODO: use this test case (5 * time.Second).Nanoseconds(), // no overlap (30 * time.Second).Nanoseconds(), (10 * time.Second).Nanoseconds(), diff --git a/pkg/logql/shardmapper.go b/pkg/logql/shardmapper.go index fd07ec0a73ba3..3ffa3cc030c1c 100644 --- a/pkg/logql/shardmapper.go +++ b/pkg/logql/shardmapper.go @@ -593,6 +593,7 @@ func (m ShardMapper) mapRangeAggregationExpr(expr *syntax.RangeAggregationExpr, return &MergeFirstOverTimeExpr{ downstreams: downstreams, + offset: expr.Left.Offset, }, bytesPerShard, nil case syntax.OpRangeTypeLast: if !m.lastOverTimeSharding { @@ -623,6 +624,7 @@ func (m ShardMapper) mapRangeAggregationExpr(expr *syntax.RangeAggregationExpr, return &MergeLastOverTimeExpr{ downstreams: downstreams, + offset: expr.Left.Offset, }, bytesPerShard, nil default: // don't shard if there's not an appropriate optimization
fix
Adjust with offset in last, first and quantile over time queries. (#15915)
7eceea082bf1247872f2e3cc81860ce6ce51ef20
2021-07-07 05:29:01
Karen Miller
docs: Make identification of experimental items consistent and more obvious. (#3911)
false
diff --git a/docs/sources/api/_index.md b/docs/sources/api/_index.md index b6c27b3572e9a..97b8ac69638e5 100644 --- a/docs/sources/api/_index.md +++ b/docs/sources/api/_index.md @@ -242,18 +242,18 @@ accepts the following query parameters in the URL: - `start`: The start time for the query as a nanosecond Unix epoch. Defaults to one hour ago. - `end`: The end time for the query as a nanosecond Unix epoch. Defaults to now. - `step`: Query resolution step width in `duration` format or float number of seconds. `duration` refers to Prometheus duration strings of the form `[0-9]+[smhdwy]`. For example, 5m refers to a duration of 5 minutes. Defaults to a dynamic value based on `start` and `end`. Only applies to query types which produce a matrix response. -- `interval`: **Experimental, See Below** Only return entries at (or greater than) the specified interval, can be a `duration` format or float number of seconds. Only applies to queries which produce a stream response. +- `interval`: <span style="background-color:#f3f973;">This parameter is experimental; see the explanation under Step versus Interval.</span> Only return entries at (or greater than) the specified interval, can be a `duration` format or float number of seconds. Only applies to queries which produce a stream response. - `direction`: Determines the sort order of logs. Supported values are `forward` or `backward`. Defaults to `backward.` In microservices mode, `/loki/api/v1/query_range` is exposed by the querier and the frontend. -##### Step vs Interval +##### Step versus Interval Use the `step` parameter when making metric queries to Loki, or queries which return a matrix response. It is evaluated in exactly the same way Prometheus evaluates `step`. First the query will be evaluated at `start` and then evaluated again at `start + step` and again at `start + step + step` until `end` is reached. The result will be a matrix of the query result evaluated at each step. Use the `interval` parameter when making log queries to Loki, or queries which return a stream response. It is evaluated by returning a log entry at `start`, then the next entry will be returned an entry with timestampe >= `start + interval`, and again at `start + interval + interval` and so on until `end` is reached. It does not fill missing entries. -**Note about the experimental nature of interval** This flag may be removed in the future, if so it will likely be in favor of a LogQL expression to perform similar behavior, however that is uncertain at this time. [Issue 1779](https://github.com/grafana/loki/issues/1779) was created to track the discussion, if you are using `interval` please go add your use case and thoughts to that issue. +<span style="background-color:#f3f973;">Note about the experimental nature of the interval parameter:</span> This flag may be removed in the future, if so it will likely be in favor of a LogQL expression to perform similar behavior, however that is uncertain at this time. [Issue 1779](https://github.com/grafana/loki/issues/1779) was created to track the discussion, if you are using `interval` please go add your use case and thoughts to that issue. @@ -955,14 +955,14 @@ Displays a web page with the ruler hash ring status, including the state, health ### List rule groups +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` GET /loki/api/v1/rules ``` List all rules configured for the authenticated tenant. This endpoint returns a YAML dictionary with all the rule groups for each namespace and `200` status code on success. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - #### Example response ```yaml @@ -1003,14 +1003,14 @@ _This experimental endpoint is disabled by default and can be enabled via the `- ### Get rule groups by namespace +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` GET /loki/api/v1/rules/{namespace} ``` Returns the rule groups defined for a given namespace. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - #### Example response ```yaml @@ -1028,24 +1028,24 @@ rules: ### Get rule group +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` GET /loki/api/v1/rules/{namespace}/{groupName} ``` Returns the rule group matching the request namespace and group name. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - ### Set rule group +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` POST /loki/api/v1/rules/{namespace} ``` Creates or updates a rule group. This endpoint expects a request with `Content-Type: application/yaml` header and the rules **YAML** definition in the request body, and returns `202` on success. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - #### Example request Request headers: @@ -1077,16 +1077,18 @@ Deletes a rule group by namespace and group name. This endpoints returns `202` o ### Delete namespace +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` DELETE /loki/api/v1/rules/{namespace} ``` Deletes all the rule groups in a namespace (including the namespace itself). This endpoint returns `202` on success. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - ### List rules +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` GET /prometheus/api/v1/rules ``` @@ -1095,16 +1097,14 @@ Prometheus-compatible rules endpoint to list alerting and recording rules that a For more information, refer to the [Prometheus rules](https://prometheus.io/docs/prometheus/latest/querying/api/#rules) documentation. -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ - ### List alerts +<span style="background-color:#f3f973;">This experimental endpoint is disabled by default and can be enabled via the -experimental.ruler.enable-api CLI flag or the YAML config option.</span> + ``` GET /prometheus/api/v1/alerts ``` Prometheus-compatible rules endpoint to list all active alerts. -_For more information, please check out the Prometheus [alerts](https://prometheus.io/docs/prometheus/latest/querying/api/#alerts) documentation._ - -_This experimental endpoint is disabled by default and can be enabled via the `-experimental.ruler.enable-api` CLI flag (or its respective YAML config option)._ +For more information, please check out the Prometheus [alerts](https://prometheus.io/docs/prometheus/latest/querying/api/#alerts) documentation. diff --git a/docs/sources/configuration/_index.md b/docs/sources/configuration/_index.md index 2e3dde3799835..d6312c4fe582e 100644 --- a/docs/sources/configuration/_index.md +++ b/docs/sources/configuration/_index.md @@ -352,6 +352,8 @@ results_cache: The `ruler_config` configures the Loki ruler. +<span style="background-color:#f3f973;">The Ruler API is experimental.</span> + ```yaml # URL of alerts return path. # CLI flag: -ruler.external.url @@ -1462,6 +1464,8 @@ to wait before saving them to the backing store. The `cache_config` block configures how Loki will cache requests, chunks, and the index to a backing cache store. +<span style="background-color:#f3f973;">The memcached configuration variable addresses is experimental.</span> + ```yaml # Enable in-memory cache. # CLI flag: -<prefix>.cache.enable-fifocache @@ -1507,7 +1511,7 @@ memcached_client: # CLI flag: -<prefix>.memcached.service [service: <string> | default = "memcached"] - # EXPERIMENTAL: Comma separated addresses list in DNS Service Discovery format: + # (Experimental) Comma-separated addresses list in DNS Service Discovery format: # https://cortexmetrics.io/docs/configuration/arguments/#dns-service-discovery # CLI flag: -<prefix>.memcached.addresses [addresses: <string> | default = ""] @@ -1653,6 +1657,8 @@ chunks: The `compactor_config` block configures the compactor component. This component periodically compacts index shards to more performant forms. +<span style="background-color:#f3f973;">Retention through the Compactor is experimental.</span> + ```yaml # Directory where files can be downloaded for compaction. [working_directory: <string>] diff --git a/docs/sources/logql/_index.md b/docs/sources/logql/_index.md index 792c8088d456c..fd29dd9ad11e1 100644 --- a/docs/sources/logql/_index.md +++ b/docs/sources/logql/_index.md @@ -280,6 +280,8 @@ will get those labels extracted: ##### Pattern +<span style="background-color:#f3f973;">The pattern parser is a beta feature.</span> + The pattern parser allows the explicit extraction of fields from log lines by defining a pattern expression (`| pattern "<pattern-expression>"`). The expression matches the structure of a log line. Consider this NGINX log line. diff --git a/docs/sources/operations/storage/logs-deletion.md b/docs/sources/operations/storage/logs-deletion.md index 7a6b6253e3fda..bd4f8a6a14b0b 100644 --- a/docs/sources/operations/storage/logs-deletion.md +++ b/docs/sources/operations/storage/logs-deletion.md @@ -4,7 +4,7 @@ weight: 60 --- # Log Entry Deletion -_This feature is experimental. It is only supported for the BoltDB Shipper index store._ +<span style="background-color:#f3f973;">Log entry deletion is experimental. It is only supported for the BoltDB Shipper index store.</span> Loki supports the deletion of log entries from specified streams. Log entries that fall within a specified time window are those that will be deleted. @@ -88,4 +88,4 @@ Sample form of a cURL command: curl -X POST \ '<compactor_addr>/loki/api/admin/cancel_delete_request?request_id=<request_id>' \ -H 'x-scope-orgid: <tenant-id>' -``` \ No newline at end of file +``` diff --git a/docs/sources/operations/storage/retention.md b/docs/sources/operations/storage/retention.md index e5d5c178cc478..be525df40bf47 100644 --- a/docs/sources/operations/storage/retention.md +++ b/docs/sources/operations/storage/retention.md @@ -8,7 +8,8 @@ Retention in Loki is achieved either through the [Table Manager](#table-manager) Retention through the [Table Manager](../table-manager/) is achieved by relying on the object store TTL feature, and will work for both [boltdb-shipper](../boltdb-shipper) store and chunk/index store. However retention through the [Compactor](../boltdb-shipper#compactor) is supported only with the [boltdb-shipper](../boltdb-shipper) store. -The [Compactor](#Compactor) retention will become the default and have long term support. While this retention is still **experimental**, it supports more granular retention policies on per tenant and per stream use cases. +<span style="background-color:#f3f973;">Retention through the [Compactor](#Compactor) is experimental.</span> +The Compactor retention will become the default and have long term support. It supports more granular retention policies on per tenant and per stream use cases. ## Compactor diff --git a/docs/sources/storage/_index.md b/docs/sources/storage/_index.md index 4f291c964f1b5..9edaf2a8c21a8 100644 --- a/docs/sources/storage/_index.md +++ b/docs/sources/storage/_index.md @@ -50,7 +50,7 @@ As of 2.0, this is the recommended index storage type, performance is comparable ### Cassandra -Cassandra can also be utilized for the index store and aside from the experimental [boltdb-shipper](../operations/storage/boltdb-shipper/), it's the only non-cloud offering that can be used for the index that's horizontally scalable and has configurable replication. It's a good candidate when you already run Cassandra, are running on-prem, or do not wish to use a managed cloud offering. +Cassandra can also be utilized for the index store and aside from the [boltdb-shipper](../operations/storage/boltdb-shipper/), it's the only non-cloud offering that can be used for the index that's horizontally scalable and has configurable replication. It's a good candidate when you already run Cassandra, are running on-prem, or do not wish to use a managed cloud offering. ### BigTable @@ -66,7 +66,7 @@ DynamoDB is susceptible to rate limiting, particularly due to overconsuming what ### BoltDB -BoltDB is an embedded database on disk. It is not replicated and thus cannot be used for high availability or clustered Loki deployments, but is commonly paired with a `filesystem` chunk store for proof of concept deployments, trying out Loki, and development. There is also an experimental mode, the [boltdb-shipper](../operations/storage/boltdb-shipper/), which aims to support clustered deployments using `boltdb` as an index. +BoltDB is an embedded database on disk. It is not replicated and thus cannot be used for high availability or clustered Loki deployments, but is commonly paired with a `filesystem` chunk store for proof of concept deployments, trying out Loki, and development. The [boltdb-shipper](../operations/storage/boltdb-shipper/) aims to support clustered deployments using `boltdb` as an index. ## Schema Configs
docs
Make identification of experimental items consistent and more obvious. (#3911)
dbf2befc1d888905bb7a69a96c8ba660153808eb
2025-02-14 18:40:40
Cyril Tovena
feat: Distributed Operational UI (#16097)
false
diff --git a/.cursor/rules/frontend.mdc b/.cursor/rules/frontend.mdc new file mode 100644 index 0000000000000..81b63d90af3b3 --- /dev/null +++ b/.cursor/rules/frontend.mdc @@ -0,0 +1,104 @@ +--- +description: building frontend code in react and typescript +globs: *.tsx,*.ts,*.css +--- +You are an expert in TypeScript, Node.js, react-dom router, React, Shadcn UI, Radix UI and Tailwind. + +# Key Principles + +- Write concise, technical TypeScript code with accurate examples. +- Use functional and declarative programming patterns; avoid classes. +- Prefer iteration and modularization over code duplication. +- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError). +- Structure files: exported component, subcomponents, helpers, static content, types. + +# Component Composition + +Break down complex UIs into smaller, more manageable parts, which can be easily reused across different parts of the application. + +- Reusability: Components can be easily reused across different parts of the application, making it easier to maintain and update the UI. +- Modularity: Breaking the UI down into smaller, more manageable components makes it easier to understand and work with, particularly for larger and more complex applications. +- Separation of Concerns: By separating the UI into smaller components, each component can focus on its own specific functionality, making it easier to test and debug. +- Code Maintainability: Using smaller components that are easy to understand and maintain makes it easier to make changes and update the application over time. + +Avoid large components with nested rendering functions + + +# State + +- useState - for simpler states that are independent +- useReducer - for more complex states where on a single action you want to update several pieces of state +- context + hooks = good state management don't use other library +- prefix -context and -provider for context and respective provider. + +# Naming Conventions + +- Use lowercase with dashes for directories (e.g., components/auth-wizard). +- Favor named exports for components. + +# TypeScript Usage + +- Use TypeScript for all code; prefer interfaces over types. +- Avoid enums; use maps instead. +- Use functional components with TypeScript interfaces. + +# Syntax and Formatting + +- Use the "function" keyword for pure functions. +- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements. +- Use declarative JSX. +- Use arrow functions for improving code readability and reducing verbosity, especially for smaller functions like event handlers or callback functions. +- Avoid using inline styles + +## Project Structure + +Colocate things as close as possible to where it's being used + +``` +src/ +├── components/ # React components +│ ├── ui/ # Shadcn UI components +│ │ ├── errors/ # Error handling components +│ │ └── breadcrumbs/ # Navigation breadcrumbs +│ ├── shared/ # Shared components used across pages +│ │ └── {pagename}/ # Page-specific components +│ ├── common/ # Truly reusable components +│ └── features/ # Complex feature modules +│ └── theme/ # Theme-related components and logic +├── pages/ # Page components and routes +├── layout/ # Layout components +├── hooks/ # Custom React hooks +├── contexts/ # React context providers +├── lib/ # Utility functions and constants +└── types/ # TypeScript type definitions +``` + +DON'T modify shadcn component directly they are stored in src/components/ui/* + + +# UI and Styling + +- Use Shadcn UI, Radix, and Tailwind for components and styling. +- Implement responsive design with Tailwind CSS. + +# Performance Optimization + +- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC). +- Wrap client components in Suspense with fallback. +- Use dynamic loading for non-critical components. +- Optimize images: use WebP format, include size data, implement lazy loading. + +# Key Conventions + +- Use 'nuqs' for URL search parameter state management. +- Optimize Web Vitals (LCP, CLS, FID). +- Limit 'use client': + +# Unit Tests + +Unit testing is done to test individual components of the React application involving testing the functionality of each component in isolation to ensure that it works as intended. + +- Use Jest for unit testing. +- Write unit tests for each component. +- Use React Testing Library for testing components. +- Use React Testing Library for testing components. diff --git a/.gitignore b/.gitignore index 47a961cca44be..955575c74c874 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ dlv rootfs/ dist !pkg/dataobj/explorer/dist +!pkg/ui/frontend/dist *coverage.txt *test_results.txt .DS_Store @@ -37,8 +38,8 @@ dist pkg/loki/wal tools/lambda-promtail/main tools/dev/kafka/data/ -pkg/dataobj/explorer/ui/node_modules/* -pkg/dataobj/explorer/ui/.vite/* +pkg/ui/frontend/node_modules/* +pkg/ui/frontend/.vite/* # Submodule added by `act` CLI _shared-workflows-dockerhub-login diff --git a/Makefile b/Makefile index ce1fd1fa61a3e..5c1e037220134 100644 --- a/Makefile +++ b/Makefile @@ -199,7 +199,7 @@ cmd/loki/loki-debug: CGO_ENABLED=0 go build $(DEBUG_GO_FLAGS) -o $@ ./$(@D) ui-assets: - make -C pkg/dataobj/explorer/ui build + make -C pkg/ui/frontend build ############### # Loki-Canary # ############### diff --git a/cmd/loki/Dockerfile b/cmd/loki/Dockerfile index 700fa1710dcde..4fcb773f34dd6 100644 --- a/cmd/loki/Dockerfile +++ b/cmd/loki/Dockerfile @@ -5,13 +5,13 @@ FROM node:22-alpine AS ui-builder RUN apk add --no-cache make COPY . /src/loki WORKDIR /src/loki -RUN make -C pkg/dataobj/explorer/ui build +RUN make -C pkg/ui/frontend build # Go build stage FROM golang:${GO_VERSION} AS build ARG IMAGE_TAG COPY . /src/loki -COPY --from=ui-builder /src/loki/pkg/dataobj/explorer/dist /src/loki/pkg/dataobj/explorer/dist +COPY --from=ui-builder /src/loki/pkg/ui/frontend/dist /src/loki/pkg/ui/frontend/dist WORKDIR /src/loki RUN make clean && make BUILD_IN_CONTAINER=false IMAGE_TAG=${IMAGE_TAG} loki diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index a55cfff40ef1b..e065282ea722c 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -109,6 +109,42 @@ Pass the `-config.expand-env` flag at the command line to enable this way of set # Configures the server of the launched module(s). [server: <server>] +ui: + # Name to use for this node in the cluster. + # CLI flag: -ui.node-name + [node_name: <string> | default = "<hostname>"] + + # IP address to advertise in the cluster. + # CLI flag: -ui.advertise-addr + [advertise_addr: <string> | default = ""] + + # Name of network interface to read address from. + # CLI flag: -ui.interface + [interface_names: <list of strings> | default = [<private network interfaces>]] + + # How frequently to rejoin the cluster to address split brain issues. + # CLI flag: -ui.rejoin-interval + [rejoin_interval: <duration> | default = 15s] + + # Number of initial peers to join from the discovered set. + # CLI flag: -ui.cluster-max-join-peers + [cluster_max_join_peers: <int> | default = 3] + + # Name to prevent nodes without this identifier from joining the cluster. + # CLI flag: -ui.cluster-name + [cluster_name: <string> | default = ""] + + # Enable using a IPv6 instance address. + # CLI flag: -ui.enable-ipv6 + [enable_ipv6: <boolean> | default = false] + + discovery: + # List of peers to join the cluster. Supports multiple values separated by + # commas. Each value can be a hostname, an IP address, or a DNS name (A/AAAA + # and SRV records). + # CLI flag: -ui.discovery.join-peers + [join_peers: <list of strings> | default = []] + # Configures the distributor. [distributor: <distributor>] diff --git a/go.mod b/go.mod index 258f6c4920dbf..5699b391dce39 100644 --- a/go.mod +++ b/go.mod @@ -50,6 +50,7 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 + github.com/grafana/ckit v0.0.0-20250109002736-4ca45886e452 github.com/grafana/cloudflare-go v0.0.0-20230110200409-c627cf6792f2 github.com/grafana/dskit v0.0.0-20241007172036-53283a0f6b41 github.com/grafana/go-gelf/v2 v2.0.1 @@ -299,13 +300,13 @@ require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v1.6.3 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-msgpack v1.1.5 // indirect + github.com/hashicorp/go-msgpack v0.5.5 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-retryablehttp v0.7.7 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect github.com/hashicorp/go-sockaddr v1.0.7 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect - github.com/hashicorp/memberlist v0.5.1 // indirect + github.com/hashicorp/memberlist v0.5.2 // indirect github.com/hashicorp/serf v0.10.1 // indirect github.com/huandu/xstrings v1.5.0 // indirect github.com/jcmturner/aescts/v2 v2.0.0 // indirect diff --git a/go.sum b/go.sum index 9c7b1f72fdb59..315e82422d120 100644 --- a/go.sum +++ b/go.sum @@ -614,6 +614,8 @@ github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/z github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grafana/ckit v0.0.0-20250109002736-4ca45886e452 h1:d/pdVKdLSNUfHUlWsN39OqUI94XgWKOGJdi568yOXmc= +github.com/grafana/ckit v0.0.0-20250109002736-4ca45886e452/go.mod h1:x6HpYv0+NXPJRBbDYA40IcxWHvrrKwgrMe1Mue172wE= github.com/grafana/cloudflare-go v0.0.0-20230110200409-c627cf6792f2 h1:qhugDMdQ4Vp68H0tp/0iN17DM2ehRo1rLEdOFe/gB8I= github.com/grafana/cloudflare-go v0.0.0-20230110200409-c627cf6792f2/go.mod h1:w/aiO1POVIeXUQyl0VQSZjl5OAGDTL5aX+4v0RA1tcw= github.com/grafana/dskit v0.0.0-20241007172036-53283a0f6b41 h1:a4O59OU3FJZ+EJUVnlvvNTvdAc4uRN1P6EaGwqL9CnA= @@ -670,8 +672,8 @@ github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjh github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-msgpack v1.1.5 h1:9byZdVjKTe5mce63pRVNP1L7UAmdHOTEMGehn6KvJWs= -github.com/hashicorp/go-msgpack v1.1.5/go.mod h1:gWVc3sv/wbDmR3rQsj1CAktEZzoz1YNK9NfGLXJ69/4= +github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= +github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= @@ -1497,7 +1499,6 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190424220101-1e8e1cfdf96b/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= diff --git a/pkg/analytics/handler.go b/pkg/analytics/handler.go new file mode 100644 index 0000000000000..8d7e4821061a0 --- /dev/null +++ b/pkg/analytics/handler.go @@ -0,0 +1,32 @@ +package analytics + +import ( + "encoding/json" + "net/http" + "sync" + "time" +) + +var ( + seed = &ClusterSeed{} + rw sync.RWMutex +) + +func setSeed(s *ClusterSeed) { + rw.Lock() + defer rw.Unlock() + seed = s +} + +func Handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + rw.RLock() + defer rw.RUnlock() + report := buildReport(seed, time.Now()) + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(report); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + }) +} diff --git a/pkg/analytics/reporter.go b/pkg/analytics/reporter.go index e6a279e4022ab..af0b8ae37132d 100644 --- a/pkg/analytics/reporter.go +++ b/pkg/analytics/reporter.go @@ -295,6 +295,7 @@ func (rep *Reporter) running(ctx context.Context) error { } return nil } + setSeed(rep.cluster) rep.startCPUPercentCollection(ctx, time.Minute) // check every minute if we should report. ticker := time.NewTicker(reportCheckInterval) @@ -352,9 +353,7 @@ func (rep *Reporter) reportUsage(ctx context.Context, interval time.Time) error const cpuUsageKey = "cpu_usage" -var ( - cpuUsage = NewFloat(cpuUsageKey) -) +var cpuUsage = NewFloat(cpuUsageKey) func (rep *Reporter) startCPUPercentCollection(ctx context.Context, cpuCollectionInterval time.Duration) { proc, err := process.NewProcess(int32(os.Getpid())) diff --git a/pkg/compactor/compactor.go b/pkg/compactor/compactor.go index e19bfec2457a9..8230cd4e3efb8 100644 --- a/pkg/compactor/compactor.go +++ b/pkg/compactor/compactor.go @@ -4,7 +4,6 @@ import ( "context" "flag" "fmt" - "net/http" "os" "path/filepath" "sort" @@ -178,6 +177,7 @@ type Compactor struct { indexCompactors map[string]IndexCompactor schemaConfig config.SchemaConfig tableLocker *tableLocker + limits Limits // Ring used for running a single compactor ringLifecycler *ring.BasicLifecycler @@ -219,6 +219,7 @@ func NewCompactor(cfg Config, objectStoreClients map[config.DayTime]client.Objec indexCompactors: map[string]IndexCompactor{}, schemaConfig: schemaConfig, tableLocker: newTableLocker(), + limits: limits, } ringStore, err := kv.NewClient( @@ -882,10 +883,6 @@ func (c *Compactor) OnRingInstanceStopping(_ *ring.BasicLifecycler) func (c *Compactor) OnRingInstanceHeartbeat(_ *ring.BasicLifecycler, _ *ring.Desc, _ *ring.InstanceDesc) { } -func (c *Compactor) ServeHTTP(w http.ResponseWriter, req *http.Request) { - c.ring.ServeHTTP(w, req) -} - func SortTablesByRange(tables []string) { tableRanges := make(map[string]model.Interval) for _, table := range tables { diff --git a/pkg/compactor/deletion/delete_request.go b/pkg/compactor/deletion/delete_request.go index 592ae810b2a98..5dea77bb32a71 100644 --- a/pkg/compactor/deletion/delete_request.go +++ b/pkg/compactor/deletion/delete_request.go @@ -1,6 +1,7 @@ package deletion import ( + "strings" "time" "github.com/go-kit/log/level" @@ -195,3 +196,15 @@ func intervalsOverlap(interval1, interval2 model.Interval) bool { return true } + +// GetMatchers returns the string representation of the matchers +func (d *DeleteRequest) GetMatchers() string { + if len(d.matchers) == 0 { + return "" + } + var result []string + for _, m := range d.matchers { + result = append(result, m.String()) + } + return strings.Join(result, ",") +} diff --git a/pkg/compactor/deletion/request_handler.go b/pkg/compactor/deletion/request_handler.go index 5d5d166f0406a..a606b773e6f19 100644 --- a/pkg/compactor/deletion/request_handler.go +++ b/pkg/compactor/deletion/request_handler.go @@ -45,6 +45,10 @@ func NewDeleteRequestHandler(deleteStore DeleteRequestsStore, maxInterval, delet // AddDeleteRequestHandler handles addition of a new delete request func (dm *DeleteRequestHandler) AddDeleteRequestHandler(w http.ResponseWriter, r *http.Request) { + if dm == nil { + http.Error(w, "Retention is not enabled", http.StatusBadRequest) + return + } ctx := r.Context() userID, err := tenant.TenantID(ctx) if err != nil { @@ -125,6 +129,10 @@ func (dm *DeleteRequestHandler) interval(params url.Values, startTime, endTime m // GetAllDeleteRequestsHandler handles get all delete requests func (dm *DeleteRequestHandler) GetAllDeleteRequestsHandler(w http.ResponseWriter, r *http.Request) { + if dm == nil { + http.Error(w, "Retention is not enabled", http.StatusBadRequest) + return + } ctx := r.Context() userID, err := tenant.TenantID(ctx) if err != nil { @@ -219,6 +227,10 @@ func deleteRequestStatus(processed, total int) DeleteRequestStatus { // CancelDeleteRequestHandler handles delete request cancellation func (dm *DeleteRequestHandler) CancelDeleteRequestHandler(w http.ResponseWriter, r *http.Request) { + if dm == nil { + http.Error(w, "Retention is not enabled", http.StatusBadRequest) + return + } ctx := r.Context() userID, err := tenant.TenantID(ctx) if err != nil { @@ -271,6 +283,10 @@ func filterProcessed(reqs []DeleteRequest) []DeleteRequest { // GetCacheGenerationNumberHandler handles requests for a user's cache generation number func (dm *DeleteRequestHandler) GetCacheGenerationNumberHandler(w http.ResponseWriter, r *http.Request) { + if dm == nil { + http.Error(w, "Retention is not enabled", http.StatusBadRequest) + return + } ctx := r.Context() userID, err := tenant.TenantID(ctx) if err != nil { diff --git a/pkg/compactor/deletion/tenant_request_handler.go b/pkg/compactor/deletion/tenant_request_handler.go index 0af62baa13b1f..fc2ee5bba457d 100644 --- a/pkg/compactor/deletion/tenant_request_handler.go +++ b/pkg/compactor/deletion/tenant_request_handler.go @@ -3,29 +3,32 @@ package deletion import ( "net/http" + "github.com/grafana/dskit/middleware" "github.com/grafana/dskit/tenant" ) -func TenantMiddleware(limits Limits, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - userID, err := tenant.TenantID(ctx) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } +func TenantMiddleware(limits Limits) middleware.Interface { + return middleware.Func(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + userID, err := tenant.TenantID(ctx) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } - hasDelete, err := validDeletionLimit(limits, userID) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } + hasDelete, err := validDeletionLimit(limits, userID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } - if !hasDelete { - http.Error(w, deletionNotAvailableMsg, http.StatusForbidden) - return - } + if !hasDelete { + http.Error(w, deletionNotAvailableMsg, http.StatusForbidden) + return + } - next.ServeHTTP(w, r) + next.ServeHTTP(w, r) + }) }) } diff --git a/pkg/compactor/deletion/tenant_request_handler_test.go b/pkg/compactor/deletion/tenant_request_handler_test.go index 7178a31bcc0f0..dcd7d2017f4ca 100644 --- a/pkg/compactor/deletion/tenant_request_handler_test.go +++ b/pkg/compactor/deletion/tenant_request_handler_test.go @@ -23,8 +23,7 @@ func TestDeleteRequestHandlerDeletionMiddleware(t *testing.T) { } // Setup handler - middle := TenantMiddleware(fl, http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) - + middle := TenantMiddleware(fl).Wrap(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) // User that has deletion enabled req := httptest.NewRequest(http.MethodGet, "http://www.your-domain.com", nil) req = req.WithContext(user.InjectOrgID(req.Context(), "1")) diff --git a/pkg/compactor/ui.go b/pkg/compactor/ui.go new file mode 100644 index 0000000000000..acb51d06c33ac --- /dev/null +++ b/pkg/compactor/ui.go @@ -0,0 +1,114 @@ +package compactor + +import ( + "encoding/json" + "net/http" + "sort" + + "github.com/grafana/dskit/middleware" + + "github.com/grafana/loki/v3/pkg/compactor/deletion" +) + +func (c *Compactor) Handler() (string, http.Handler) { + mux := http.NewServeMux() + + mw := middleware.Merge( + middleware.AuthenticateUser, + deletion.TenantMiddleware(c.limits), + // Automatically parse form data + middleware.Func(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + next.ServeHTTP(w, r) + }) + }), + ) + + // API endpoints + mux.Handle("/compactor/ring", c.ring) + // Custom UI endpoints for the compactor + mux.HandleFunc("/compactor/ui/api/v1/deletes", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + c.handleListDeleteRequests(w, r) + case http.MethodPost: + mw.Wrap(http.HandlerFunc(c.DeleteRequestsHandler.AddDeleteRequestHandler)).ServeHTTP(w, r) + default: + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } + }) + + return "/compactor", mux +} + +type DeleteRequestResponse struct { + RequestID string `json:"request_id"` + StartTime int64 `json:"start_time"` + EndTime int64 `json:"end_time"` + Query string `json:"query"` + Status string `json:"status"` + CreatedAt int64 `json:"created_at"` + UserID string `json:"user_id"` + DeletedLines int32 `json:"deleted_lines"` +} + +func (c *Compactor) handleListDeleteRequests(w http.ResponseWriter, r *http.Request) { + status := r.URL.Query().Get("status") + if status == "" { + status = string(deletion.StatusReceived) + } + + ctx := r.Context() + if c.deleteRequestsStore == nil { + http.Error(w, "Retention is not enabled", http.StatusBadRequest) + return + } + requests, err := c.deleteRequestsStore.GetAllRequests(ctx) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Filter requests by status + filtered := requests[:0] + for _, req := range requests { + if req.Status == deletion.DeleteRequestStatus(status) { + filtered = append(filtered, req) + } + } + requests = filtered + + // Sort by creation time descending + sort.Slice(requests, func(i, j int) bool { + return requests[i].CreatedAt > requests[j].CreatedAt + }) + + // Take only last 100 + if len(requests) > 100 { + requests = requests[:100] + } + + response := make([]DeleteRequestResponse, 0, len(requests)) + for _, req := range requests { + response = append(response, DeleteRequestResponse{ + RequestID: req.RequestID, + StartTime: int64(req.StartTime), + EndTime: int64(req.EndTime), + Query: req.Query, + Status: string(req.Status), + CreatedAt: int64(req.CreatedAt), + UserID: req.UserID, + DeletedLines: req.DeletedLines, + }) + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(response); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } +} diff --git a/pkg/dataobj/explorer/dist/assets/index-CWzBrpZu.js b/pkg/dataobj/explorer/dist/assets/index-CWzBrpZu.js deleted file mode 100644 index 656b7207beb77..0000000000000 --- a/pkg/dataobj/explorer/dist/assets/index-CWzBrpZu.js +++ /dev/null @@ -1,68 +0,0 @@ -function bc(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const l in r)if(l!=="default"&&!(l in e)){const a=Object.getOwnPropertyDescriptor(r,l);a&&Object.defineProperty(e,l,a.get?a:{enumerable:!0,get:()=>r[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const a of l)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(l){const a={};return l.integrity&&(a.integrity=l.integrity),l.referrerPolicy&&(a.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?a.credentials="include":l.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(l){if(l.ep)return;l.ep=!0;const a=n(l);fetch(l.href,a)}})();function Xc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Kc={exports:{}},ba={},Gc={exports:{}},Q={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Cl=Symbol.for("react.element"),tp=Symbol.for("react.portal"),np=Symbol.for("react.fragment"),rp=Symbol.for("react.strict_mode"),lp=Symbol.for("react.profiler"),ap=Symbol.for("react.provider"),ip=Symbol.for("react.context"),op=Symbol.for("react.forward_ref"),up=Symbol.for("react.suspense"),sp=Symbol.for("react.memo"),cp=Symbol.for("react.lazy"),os=Symbol.iterator;function dp(e){return e===null||typeof e!="object"?null:(e=os&&e[os]||e["@@iterator"],typeof e=="function"?e:null)}var Jc={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Zc=Object.assign,qc={};function Sr(e,t,n){this.props=e,this.context=t,this.refs=qc,this.updater=n||Jc}Sr.prototype.isReactComponent={};Sr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Sr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ed(){}ed.prototype=Sr.prototype;function Go(e,t,n){this.props=e,this.context=t,this.refs=qc,this.updater=n||Jc}var Jo=Go.prototype=new ed;Jo.constructor=Go;Zc(Jo,Sr.prototype);Jo.isPureReactComponent=!0;var us=Array.isArray,td=Object.prototype.hasOwnProperty,Zo={current:null},nd={key:!0,ref:!0,__self:!0,__source:!0};function rd(e,t,n){var r,l={},a=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(a=""+t.key),t)td.call(t,r)&&!nd.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1<o){for(var u=Array(o),s=0;s<o;s++)u[s]=arguments[s+2];l.children=u}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)l[r]===void 0&&(l[r]=o[r]);return{$$typeof:Cl,type:e,key:a,ref:i,props:l,_owner:Zo.current}}function fp(e,t){return{$$typeof:Cl,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function qo(e){return typeof e=="object"&&e!==null&&e.$$typeof===Cl}function hp(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var ss=/\/+/g;function wi(e,t){return typeof e=="object"&&e!==null&&e.key!=null?hp(""+e.key):t.toString(36)}function la(e,t,n,r,l){var a=typeof e;(a==="undefined"||a==="boolean")&&(e=null);var i=!1;if(e===null)i=!0;else switch(a){case"string":case"number":i=!0;break;case"object":switch(e.$$typeof){case Cl:case tp:i=!0}}if(i)return i=e,l=l(i),e=r===""?"."+wi(i,0):r,us(l)?(n="",e!=null&&(n=e.replace(ss,"$&/")+"/"),la(l,t,n,"",function(s){return s})):l!=null&&(qo(l)&&(l=fp(l,n+(!l.key||i&&i.key===l.key?"":(""+l.key).replace(ss,"$&/")+"/")+e)),t.push(l)),1;if(i=0,r=r===""?".":r+":",us(e))for(var o=0;o<e.length;o++){a=e[o];var u=r+wi(a,o);i+=la(a,t,n,u,l)}else if(u=dp(e),typeof u=="function")for(e=u.call(e),o=0;!(a=e.next()).done;)a=a.value,u=r+wi(a,o++),i+=la(a,t,n,u,l);else if(a==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return i}function Ul(e,t,n){if(e==null)return e;var r=[],l=0;return la(e,r,"","",function(a){return t.call(n,a,l++)}),r}function pp(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var He={current:null},aa={transition:null},mp={ReactCurrentDispatcher:He,ReactCurrentBatchConfig:aa,ReactCurrentOwner:Zo};function ld(){throw Error("act(...) is not supported in production builds of React.")}Q.Children={map:Ul,forEach:function(e,t,n){Ul(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return Ul(e,function(){t++}),t},toArray:function(e){return Ul(e,function(t){return t})||[]},only:function(e){if(!qo(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};Q.Component=Sr;Q.Fragment=np;Q.Profiler=lp;Q.PureComponent=Go;Q.StrictMode=rp;Q.Suspense=up;Q.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=mp;Q.act=ld;Q.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Zc({},e.props),l=e.key,a=e.ref,i=e._owner;if(t!=null){if(t.ref!==void 0&&(a=t.ref,i=Zo.current),t.key!==void 0&&(l=""+t.key),e.type&&e.type.defaultProps)var o=e.type.defaultProps;for(u in t)td.call(t,u)&&!nd.hasOwnProperty(u)&&(r[u]=t[u]===void 0&&o!==void 0?o[u]:t[u])}var u=arguments.length-2;if(u===1)r.children=n;else if(1<u){o=Array(u);for(var s=0;s<u;s++)o[s]=arguments[s+2];r.children=o}return{$$typeof:Cl,type:e.type,key:l,ref:a,props:r,_owner:i}};Q.createContext=function(e){return e={$$typeof:ip,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:ap,_context:e},e.Consumer=e};Q.createElement=rd;Q.createFactory=function(e){var t=rd.bind(null,e);return t.type=e,t};Q.createRef=function(){return{current:null}};Q.forwardRef=function(e){return{$$typeof:op,render:e}};Q.isValidElement=qo;Q.lazy=function(e){return{$$typeof:cp,_payload:{_status:-1,_result:e},_init:pp}};Q.memo=function(e,t){return{$$typeof:sp,type:e,compare:t===void 0?null:t}};Q.startTransition=function(e){var t=aa.transition;aa.transition={};try{e()}finally{aa.transition=t}};Q.unstable_act=ld;Q.useCallback=function(e,t){return He.current.useCallback(e,t)};Q.useContext=function(e){return He.current.useContext(e)};Q.useDebugValue=function(){};Q.useDeferredValue=function(e){return He.current.useDeferredValue(e)};Q.useEffect=function(e,t){return He.current.useEffect(e,t)};Q.useId=function(){return He.current.useId()};Q.useImperativeHandle=function(e,t,n){return He.current.useImperativeHandle(e,t,n)};Q.useInsertionEffect=function(e,t){return He.current.useInsertionEffect(e,t)};Q.useLayoutEffect=function(e,t){return He.current.useLayoutEffect(e,t)};Q.useMemo=function(e,t){return He.current.useMemo(e,t)};Q.useReducer=function(e,t,n){return He.current.useReducer(e,t,n)};Q.useRef=function(e){return He.current.useRef(e)};Q.useState=function(e){return He.current.useState(e)};Q.useSyncExternalStore=function(e,t,n){return He.current.useSyncExternalStore(e,t,n)};Q.useTransition=function(){return He.current.useTransition()};Q.version="18.3.1";Gc.exports=Q;var N=Gc.exports;const Ne=Xc(N),gp=bc({__proto__:null,default:Ne},[N]);/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var yp=N,vp=Symbol.for("react.element"),wp=Symbol.for("react.fragment"),xp=Object.prototype.hasOwnProperty,kp=yp.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Sp={key:!0,ref:!0,__self:!0,__source:!0};function ad(e,t,n){var r,l={},a=null,i=null;n!==void 0&&(a=""+n),t.key!==void 0&&(a=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)xp.call(t,r)&&!Sp.hasOwnProperty(r)&&(l[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)l[r]===void 0&&(l[r]=t[r]);return{$$typeof:vp,type:e,key:a,ref:i,props:l,_owner:kp.current}}ba.Fragment=wp;ba.jsx=ad;ba.jsxs=ad;Kc.exports=ba;var g=Kc.exports,Gi={},id={exports:{}},nt={},od={exports:{}},ud={};/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(e){function t(D,A){var H=D.length;D.push(A);e:for(;0<H;){var J=H-1>>>1,ae=D[J];if(0<l(ae,A))D[J]=A,D[H]=ae,H=J;else break e}}function n(D){return D.length===0?null:D[0]}function r(D){if(D.length===0)return null;var A=D[0],H=D.pop();if(H!==A){D[0]=H;e:for(var J=0,ae=D.length,wt=ae>>>1;J<wt;){var Ce=2*(J+1)-1,ct=D[Ce],Be=Ce+1,Nt=D[Be];if(0>l(ct,H))Be<ae&&0>l(Nt,ct)?(D[J]=Nt,D[Be]=H,J=Be):(D[J]=ct,D[Ce]=H,J=Ce);else if(Be<ae&&0>l(Nt,H))D[J]=Nt,D[Be]=H,J=Be;else break e}}return A}function l(D,A){var H=D.sortIndex-A.sortIndex;return H!==0?H:D.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,o=i.now();e.unstable_now=function(){return i.now()-o}}var u=[],s=[],c=1,f=null,h=3,k=!1,S=!1,v=!1,P=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(D){for(var A=n(s);A!==null;){if(A.callback===null)r(s);else if(A.startTime<=D)r(s),A.sortIndex=A.expirationTime,t(u,A);else break;A=n(s)}}function C(D){if(v=!1,y(D),!S)if(n(u)!==null)S=!0,Vt(R);else{var A=n(s);A!==null&&pe(C,A.startTime-D)}}function R(D,A){S=!1,v&&(v=!1,p(j),j=-1),k=!0;var H=h;try{for(y(A),f=n(u);f!==null&&(!(f.expirationTime>A)||D&&!te());){var J=f.callback;if(typeof J=="function"){f.callback=null,h=f.priorityLevel;var ae=J(f.expirationTime<=A);A=e.unstable_now(),typeof ae=="function"?f.callback=ae:f===n(u)&&r(u),y(A)}else r(u);f=n(u)}if(f!==null)var wt=!0;else{var Ce=n(s);Ce!==null&&pe(C,Ce.startTime-A),wt=!1}return wt}finally{f=null,h=H,k=!1}}var w=!1,T=null,j=-1,B=5,U=-1;function te(){return!(e.unstable_now()-U<B)}function ce(){if(T!==null){var D=e.unstable_now();U=D;var A=!0;try{A=T(!0,D)}finally{A?xe():(w=!1,T=null)}}else w=!1}var xe;if(typeof d=="function")xe=function(){d(ce)};else if(typeof MessageChannel<"u"){var ke=new MessageChannel,Ht=ke.port2;ke.port1.onmessage=ce,xe=function(){Ht.postMessage(null)}}else xe=function(){P(ce,0)};function Vt(D){T=D,w||(w=!0,xe())}function pe(D,A){j=P(function(){D(e.unstable_now())},A)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(D){D.callback=null},e.unstable_continueExecution=function(){S||k||(S=!0,Vt(R))},e.unstable_forceFrameRate=function(D){0>D||125<D?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):B=0<D?Math.floor(1e3/D):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_getFirstCallbackNode=function(){return n(u)},e.unstable_next=function(D){switch(h){case 1:case 2:case 3:var A=3;break;default:A=h}var H=h;h=A;try{return D()}finally{h=H}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(D,A){switch(D){case 1:case 2:case 3:case 4:case 5:break;default:D=3}var H=h;h=D;try{return A()}finally{h=H}},e.unstable_scheduleCallback=function(D,A,H){var J=e.unstable_now();switch(typeof H=="object"&&H!==null?(H=H.delay,H=typeof H=="number"&&0<H?J+H:J):H=J,D){case 1:var ae=-1;break;case 2:ae=250;break;case 5:ae=1073741823;break;case 4:ae=1e4;break;default:ae=5e3}return ae=H+ae,D={id:c++,callback:A,priorityLevel:D,startTime:H,expirationTime:ae,sortIndex:-1},H>J?(D.sortIndex=H,t(s,D),n(u)===null&&D===n(s)&&(v?(p(j),j=-1):v=!0,pe(C,H-J))):(D.sortIndex=ae,t(u,D),S||k||(S=!0,Vt(R))),D},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(D){var A=h;return function(){var H=h;h=A;try{return D.apply(this,arguments)}finally{h=H}}}})(ud);od.exports=ud;var Ep=od.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Cp=N,tt=Ep;function _(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var sd=new Set,rl={};function Bn(e,t){pr(e,t),pr(e+"Capture",t)}function pr(e,t){for(rl[e]=t,e=0;e<t.length;e++)sd.add(t[e])}var Ft=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ji=Object.prototype.hasOwnProperty,Pp=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,cs={},ds={};function Np(e){return Ji.call(ds,e)?!0:Ji.call(cs,e)?!1:Pp.test(e)?ds[e]=!0:(cs[e]=!0,!1)}function Mp(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function _p(e,t,n,r){if(t===null||typeof t>"u"||Mp(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Ve(e,t,n,r,l,a,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=i}var Oe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Oe[e]=new Ve(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Oe[t]=new Ve(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Oe[e]=new Ve(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Oe[e]=new Ve(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Oe[e]=new Ve(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Oe[e]=new Ve(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Oe[e]=new Ve(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Oe[e]=new Ve(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Oe[e]=new Ve(e,5,!1,e.toLowerCase(),null,!1,!1)});var eu=/[\-:]([a-z])/g;function tu(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(eu,tu);Oe[t]=new Ve(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(eu,tu);Oe[t]=new Ve(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(eu,tu);Oe[t]=new Ve(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Oe[e]=new Ve(e,1,!1,e.toLowerCase(),null,!1,!1)});Oe.xlinkHref=new Ve("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Oe[e]=new Ve(e,1,!1,e.toLowerCase(),null,!0,!0)});function nu(e,t,n,r){var l=Oe.hasOwnProperty(t)?Oe[t]:null;(l!==null?l.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(_p(t,n,l,r)&&(n=null),r||l===null?Np(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,""+n)):l.mustUseProperty?e[l.propertyName]=n===null?l.type===3?!1:"":n:(t=l.attributeName,r=l.attributeNamespace,n===null?e.removeAttribute(t):(l=l.type,n=l===3||l===4&&n===!0?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}var $t=Cp.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Bl=Symbol.for("react.element"),Gn=Symbol.for("react.portal"),Jn=Symbol.for("react.fragment"),ru=Symbol.for("react.strict_mode"),Zi=Symbol.for("react.profiler"),cd=Symbol.for("react.provider"),dd=Symbol.for("react.context"),lu=Symbol.for("react.forward_ref"),qi=Symbol.for("react.suspense"),eo=Symbol.for("react.suspense_list"),au=Symbol.for("react.memo"),Gt=Symbol.for("react.lazy"),fd=Symbol.for("react.offscreen"),fs=Symbol.iterator;function Rr(e){return e===null||typeof e!="object"?null:(e=fs&&e[fs]||e["@@iterator"],typeof e=="function"?e:null)}var he=Object.assign,xi;function Hr(e){if(xi===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);xi=t&&t[1]||""}return` -`+xi+e}var ki=!1;function Si(e,t){if(!e||ki)return"";ki=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(s){var r=s}Reflect.construct(e,[],t)}else{try{t.call()}catch(s){r=s}e.call(t.prototype)}else{try{throw Error()}catch(s){r=s}e()}}catch(s){if(s&&r&&typeof s.stack=="string"){for(var l=s.stack.split(` -`),a=r.stack.split(` -`),i=l.length-1,o=a.length-1;1<=i&&0<=o&&l[i]!==a[o];)o--;for(;1<=i&&0<=o;i--,o--)if(l[i]!==a[o]){if(i!==1||o!==1)do if(i--,o--,0>o||l[i]!==a[o]){var u=` -`+l[i].replace(" at new "," at ");return e.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",e.displayName)),u}while(1<=i&&0<=o);break}}}finally{ki=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Hr(e):""}function jp(e){switch(e.tag){case 5:return Hr(e.type);case 16:return Hr("Lazy");case 13:return Hr("Suspense");case 19:return Hr("SuspenseList");case 0:case 2:case 15:return e=Si(e.type,!1),e;case 11:return e=Si(e.type.render,!1),e;case 1:return e=Si(e.type,!0),e;default:return""}}function to(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Jn:return"Fragment";case Gn:return"Portal";case Zi:return"Profiler";case ru:return"StrictMode";case qi:return"Suspense";case eo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case dd:return(e.displayName||"Context")+".Consumer";case cd:return(e._context.displayName||"Context")+".Provider";case lu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case au:return t=e.displayName||null,t!==null?t:to(e.type)||"Memo";case Gt:t=e._payload,e=e._init;try{return to(e(t))}catch{}}return null}function Rp(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return to(t);case 8:return t===ru?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function hn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function hd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Tp(e){var t=hd(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,a.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Wl(e){e._valueTracker||(e._valueTracker=Tp(e))}function pd(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=hd(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function va(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function no(e,t){var n=t.checked;return he({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function hs(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=hn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function md(e,t){t=t.checked,t!=null&&nu(e,"checked",t,!1)}function ro(e,t){md(e,t);var n=hn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?lo(e,t.type,n):t.hasOwnProperty("defaultValue")&&lo(e,t.type,hn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ps(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function lo(e,t,n){(t!=="number"||va(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Vr=Array.isArray;function ur(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(n=""+hn(n),t=null,l=0;l<e.length;l++){if(e[l].value===n){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}t!==null||e[l].disabled||(t=e[l])}t!==null&&(t.selected=!0)}}function ao(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(_(91));return he({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function ms(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(_(92));if(Vr(n)){if(1<n.length)throw Error(_(93));n=n[0]}t=n}t==null&&(t=""),n=t}e._wrapperState={initialValue:hn(n)}}function gd(e,t){var n=hn(t.value),r=hn(t.defaultValue);n!=null&&(n=""+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),r!=null&&(e.defaultValue=""+r)}function gs(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function yd(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function io(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?yd(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var $l,vd=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,n,r,l){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,l)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for($l=$l||document.createElement("div"),$l.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=$l.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ll(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Xr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Lp=["Webkit","ms","Moz","O"];Object.keys(Xr).forEach(function(e){Lp.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Xr[t]=Xr[e]})});function wd(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Xr.hasOwnProperty(e)&&Xr[e]?(""+t).trim():t+"px"}function xd(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=wd(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Dp=he({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function oo(e,t){if(t){if(Dp[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(_(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(_(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(_(61))}if(t.style!=null&&typeof t.style!="object")throw Error(_(62))}}function uo(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var so=null;function iu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var co=null,sr=null,cr=null;function ys(e){if(e=Ml(e)){if(typeof co!="function")throw Error(_(280));var t=e.stateNode;t&&(t=Za(t),co(e.stateNode,e.type,t))}}function kd(e){sr?cr?cr.push(e):cr=[e]:sr=e}function Sd(){if(sr){var e=sr,t=cr;if(cr=sr=null,ys(e),t)for(e=0;e<t.length;e++)ys(t[e])}}function Ed(e,t){return e(t)}function Cd(){}var Ei=!1;function Pd(e,t,n){if(Ei)return e(t,n);Ei=!0;try{return Ed(e,t,n)}finally{Ei=!1,(sr!==null||cr!==null)&&(Cd(),Sd())}}function al(e,t){var n=e.stateNode;if(n===null)return null;var r=Za(n);if(r===null)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(_(231,t,typeof n));return n}var fo=!1;if(Ft)try{var Tr={};Object.defineProperty(Tr,"passive",{get:function(){fo=!0}}),window.addEventListener("test",Tr,Tr),window.removeEventListener("test",Tr,Tr)}catch{fo=!1}function Op(e,t,n,r,l,a,i,o,u){var s=Array.prototype.slice.call(arguments,3);try{t.apply(n,s)}catch(c){this.onError(c)}}var Kr=!1,wa=null,xa=!1,ho=null,zp={onError:function(e){Kr=!0,wa=e}};function Fp(e,t,n,r,l,a,i,o,u){Kr=!1,wa=null,Op.apply(zp,arguments)}function Ip(e,t,n,r,l,a,i,o,u){if(Fp.apply(this,arguments),Kr){if(Kr){var s=wa;Kr=!1,wa=null}else throw Error(_(198));xa||(xa=!0,ho=s)}}function Wn(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function Nd(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function vs(e){if(Wn(e)!==e)throw Error(_(188))}function Up(e){var t=e.alternate;if(!t){if(t=Wn(e),t===null)throw Error(_(188));return t!==e?null:e}for(var n=e,r=t;;){var l=n.return;if(l===null)break;var a=l.alternate;if(a===null){if(r=l.return,r!==null){n=r;continue}break}if(l.child===a.child){for(a=l.child;a;){if(a===n)return vs(l),e;if(a===r)return vs(l),t;a=a.sibling}throw Error(_(188))}if(n.return!==r.return)n=l,r=a;else{for(var i=!1,o=l.child;o;){if(o===n){i=!0,n=l,r=a;break}if(o===r){i=!0,r=l,n=a;break}o=o.sibling}if(!i){for(o=a.child;o;){if(o===n){i=!0,n=a,r=l;break}if(o===r){i=!0,r=a,n=l;break}o=o.sibling}if(!i)throw Error(_(189))}}if(n.alternate!==r)throw Error(_(190))}if(n.tag!==3)throw Error(_(188));return n.stateNode.current===n?e:t}function Md(e){return e=Up(e),e!==null?_d(e):null}function _d(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=_d(e);if(t!==null)return t;e=e.sibling}return null}var jd=tt.unstable_scheduleCallback,ws=tt.unstable_cancelCallback,Bp=tt.unstable_shouldYield,Wp=tt.unstable_requestPaint,we=tt.unstable_now,$p=tt.unstable_getCurrentPriorityLevel,ou=tt.unstable_ImmediatePriority,Rd=tt.unstable_UserBlockingPriority,ka=tt.unstable_NormalPriority,Ap=tt.unstable_LowPriority,Td=tt.unstable_IdlePriority,Xa=null,Ct=null;function Hp(e){if(Ct&&typeof Ct.onCommitFiberRoot=="function")try{Ct.onCommitFiberRoot(Xa,e,void 0,(e.current.flags&128)===128)}catch{}}var gt=Math.clz32?Math.clz32:Qp,Vp=Math.log,Yp=Math.LN2;function Qp(e){return e>>>=0,e===0?32:31-(Vp(e)/Yp|0)|0}var Al=64,Hl=4194304;function Yr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Sa(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,i=n&268435455;if(i!==0){var o=i&~l;o!==0?r=Yr(o):(a&=i,a!==0&&(r=Yr(a)))}else i=n&~l,i!==0?r=Yr(i):a!==0&&(r=Yr(a));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,a=t&-t,l>=a||l===16&&(a&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)n=31-gt(t),l=1<<n,r|=e[n],t&=~l;return r}function bp(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Xp(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=e.pendingLanes;0<a;){var i=31-gt(a),o=1<<i,u=l[i];u===-1?(!(o&n)||o&r)&&(l[i]=bp(o,t)):u<=t&&(e.expiredLanes|=o),a&=~o}}function po(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function Ld(){var e=Al;return Al<<=1,!(Al&4194240)&&(Al=64),e}function Ci(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Pl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-gt(t),e[t]=n}function Kp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var l=31-gt(n),a=1<<l;t[l]=0,r[l]=-1,e[l]=-1,n&=~a}}function uu(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-gt(n),l=1<<r;l&t|e[r]&t&&(e[r]|=t),n&=~l}}var ee=0;function Dd(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var Od,su,zd,Fd,Id,mo=!1,Vl=[],ln=null,an=null,on=null,il=new Map,ol=new Map,Zt=[],Gp="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function xs(e,t){switch(e){case"focusin":case"focusout":ln=null;break;case"dragenter":case"dragleave":an=null;break;case"mouseover":case"mouseout":on=null;break;case"pointerover":case"pointerout":il.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":ol.delete(t.pointerId)}}function Lr(e,t,n,r,l,a){return e===null||e.nativeEvent!==a?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:a,targetContainers:[l]},t!==null&&(t=Ml(t),t!==null&&su(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,l!==null&&t.indexOf(l)===-1&&t.push(l),e)}function Jp(e,t,n,r,l){switch(t){case"focusin":return ln=Lr(ln,e,t,n,r,l),!0;case"dragenter":return an=Lr(an,e,t,n,r,l),!0;case"mouseover":return on=Lr(on,e,t,n,r,l),!0;case"pointerover":var a=l.pointerId;return il.set(a,Lr(il.get(a)||null,e,t,n,r,l)),!0;case"gotpointercapture":return a=l.pointerId,ol.set(a,Lr(ol.get(a)||null,e,t,n,r,l)),!0}return!1}function Ud(e){var t=Mn(e.target);if(t!==null){var n=Wn(t);if(n!==null){if(t=n.tag,t===13){if(t=Nd(n),t!==null){e.blockedOn=t,Id(e.priority,function(){zd(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function ia(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=go(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);so=r,n.target.dispatchEvent(r),so=null}else return t=Ml(n),t!==null&&su(t),e.blockedOn=n,!1;t.shift()}return!0}function ks(e,t,n){ia(e)&&n.delete(t)}function Zp(){mo=!1,ln!==null&&ia(ln)&&(ln=null),an!==null&&ia(an)&&(an=null),on!==null&&ia(on)&&(on=null),il.forEach(ks),ol.forEach(ks)}function Dr(e,t){e.blockedOn===t&&(e.blockedOn=null,mo||(mo=!0,tt.unstable_scheduleCallback(tt.unstable_NormalPriority,Zp)))}function ul(e){function t(l){return Dr(l,e)}if(0<Vl.length){Dr(Vl[0],e);for(var n=1;n<Vl.length;n++){var r=Vl[n];r.blockedOn===e&&(r.blockedOn=null)}}for(ln!==null&&Dr(ln,e),an!==null&&Dr(an,e),on!==null&&Dr(on,e),il.forEach(t),ol.forEach(t),n=0;n<Zt.length;n++)r=Zt[n],r.blockedOn===e&&(r.blockedOn=null);for(;0<Zt.length&&(n=Zt[0],n.blockedOn===null);)Ud(n),n.blockedOn===null&&Zt.shift()}var dr=$t.ReactCurrentBatchConfig,Ea=!0;function qp(e,t,n,r){var l=ee,a=dr.transition;dr.transition=null;try{ee=1,cu(e,t,n,r)}finally{ee=l,dr.transition=a}}function em(e,t,n,r){var l=ee,a=dr.transition;dr.transition=null;try{ee=4,cu(e,t,n,r)}finally{ee=l,dr.transition=a}}function cu(e,t,n,r){if(Ea){var l=go(e,t,n,r);if(l===null)Oi(e,t,r,Ca,n),xs(e,r);else if(Jp(l,e,t,n,r))r.stopPropagation();else if(xs(e,r),t&4&&-1<Gp.indexOf(e)){for(;l!==null;){var a=Ml(l);if(a!==null&&Od(a),a=go(e,t,n,r),a===null&&Oi(e,t,r,Ca,n),a===l)break;l=a}l!==null&&r.stopPropagation()}else Oi(e,t,r,null,n)}}var Ca=null;function go(e,t,n,r){if(Ca=null,e=iu(r),e=Mn(e),e!==null)if(t=Wn(e),t===null)e=null;else if(n=t.tag,n===13){if(e=Nd(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Ca=e,null}function Bd(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch($p()){case ou:return 1;case Rd:return 4;case ka:case Ap:return 16;case Td:return 536870912;default:return 16}default:return 16}}var en=null,du=null,oa=null;function Wd(){if(oa)return oa;var e,t=du,n=t.length,r,l="value"in en?en.value:en.textContent,a=l.length;for(e=0;e<n&&t[e]===l[e];e++);var i=n-e;for(r=1;r<=i&&t[n-r]===l[a-r];r++);return oa=l.slice(e,1<r?1-r:void 0)}function ua(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Yl(){return!0}function Ss(){return!1}function rt(e){function t(n,r,l,a,i){this._reactName=n,this._targetInst=l,this.type=r,this.nativeEvent=a,this.target=i,this.currentTarget=null;for(var o in e)e.hasOwnProperty(o)&&(n=e[o],this[o]=n?n(a):a[o]);return this.isDefaultPrevented=(a.defaultPrevented!=null?a.defaultPrevented:a.returnValue===!1)?Yl:Ss,this.isPropagationStopped=Ss,this}return he(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=Yl)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=Yl)},persist:function(){},isPersistent:Yl}),t}var Er={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},fu=rt(Er),Nl=he({},Er,{view:0,detail:0}),tm=rt(Nl),Pi,Ni,Or,Ka=he({},Nl,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hu,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Or&&(Or&&e.type==="mousemove"?(Pi=e.screenX-Or.screenX,Ni=e.screenY-Or.screenY):Ni=Pi=0,Or=e),Pi)},movementY:function(e){return"movementY"in e?e.movementY:Ni}}),Es=rt(Ka),nm=he({},Ka,{dataTransfer:0}),rm=rt(nm),lm=he({},Nl,{relatedTarget:0}),Mi=rt(lm),am=he({},Er,{animationName:0,elapsedTime:0,pseudoElement:0}),im=rt(am),om=he({},Er,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),um=rt(om),sm=he({},Er,{data:0}),Cs=rt(sm),cm={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},dm={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fm={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function hm(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=fm[e])?!!t[e]:!1}function hu(){return hm}var pm=he({},Nl,{key:function(e){if(e.key){var t=cm[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=ua(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?dm[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hu,charCode:function(e){return e.type==="keypress"?ua(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?ua(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),mm=rt(pm),gm=he({},Ka,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Ps=rt(gm),ym=he({},Nl,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hu}),vm=rt(ym),wm=he({},Er,{propertyName:0,elapsedTime:0,pseudoElement:0}),xm=rt(wm),km=he({},Ka,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Sm=rt(km),Em=[9,13,27,32],pu=Ft&&"CompositionEvent"in window,Gr=null;Ft&&"documentMode"in document&&(Gr=document.documentMode);var Cm=Ft&&"TextEvent"in window&&!Gr,$d=Ft&&(!pu||Gr&&8<Gr&&11>=Gr),Ns=" ",Ms=!1;function Ad(e,t){switch(e){case"keyup":return Em.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hd(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Zn=!1;function Pm(e,t){switch(e){case"compositionend":return Hd(t);case"keypress":return t.which!==32?null:(Ms=!0,Ns);case"textInput":return e=t.data,e===Ns&&Ms?null:e;default:return null}}function Nm(e,t){if(Zn)return e==="compositionend"||!pu&&Ad(e,t)?(e=Wd(),oa=du=en=null,Zn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return $d&&t.locale!=="ko"?null:t.data;default:return null}}var Mm={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function _s(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Mm[e.type]:t==="textarea"}function Vd(e,t,n,r){kd(r),t=Pa(t,"onChange"),0<t.length&&(n=new fu("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Jr=null,sl=null;function _m(e){tf(e,0)}function Ga(e){var t=tr(e);if(pd(t))return e}function jm(e,t){if(e==="change")return t}var Yd=!1;if(Ft){var _i;if(Ft){var ji="oninput"in document;if(!ji){var js=document.createElement("div");js.setAttribute("oninput","return;"),ji=typeof js.oninput=="function"}_i=ji}else _i=!1;Yd=_i&&(!document.documentMode||9<document.documentMode)}function Rs(){Jr&&(Jr.detachEvent("onpropertychange",Qd),sl=Jr=null)}function Qd(e){if(e.propertyName==="value"&&Ga(sl)){var t=[];Vd(t,sl,e,iu(e)),Pd(_m,t)}}function Rm(e,t,n){e==="focusin"?(Rs(),Jr=t,sl=n,Jr.attachEvent("onpropertychange",Qd)):e==="focusout"&&Rs()}function Tm(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Ga(sl)}function Lm(e,t){if(e==="click")return Ga(t)}function Dm(e,t){if(e==="input"||e==="change")return Ga(t)}function Om(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var vt=typeof Object.is=="function"?Object.is:Om;function cl(e,t){if(vt(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var l=n[r];if(!Ji.call(t,l)||!vt(e[l],t[l]))return!1}return!0}function Ts(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ls(e,t){var n=Ts(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ts(n)}}function bd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?bd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Xd(){for(var e=window,t=va();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=va(e.document)}return t}function mu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function zm(e){var t=Xd(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&bd(n.ownerDocument.documentElement,n)){if(r!==null&&mu(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,a=Math.min(r.start,l);r=r.end===void 0?a:Math.min(r.end,l),!e.extend&&a>r&&(l=r,r=a,a=l),l=Ls(n,a);var i=Ls(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Fm=Ft&&"documentMode"in document&&11>=document.documentMode,qn=null,yo=null,Zr=null,vo=!1;function Ds(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;vo||qn==null||qn!==va(r)||(r=qn,"selectionStart"in r&&mu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Zr&&cl(Zr,r)||(Zr=r,r=Pa(yo,"onSelect"),0<r.length&&(t=new fu("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=qn)))}function Ql(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var er={animationend:Ql("Animation","AnimationEnd"),animationiteration:Ql("Animation","AnimationIteration"),animationstart:Ql("Animation","AnimationStart"),transitionend:Ql("Transition","TransitionEnd")},Ri={},Kd={};Ft&&(Kd=document.createElement("div").style,"AnimationEvent"in window||(delete er.animationend.animation,delete er.animationiteration.animation,delete er.animationstart.animation),"TransitionEvent"in window||delete er.transitionend.transition);function Ja(e){if(Ri[e])return Ri[e];if(!er[e])return e;var t=er[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Kd)return Ri[e]=t[n];return e}var Gd=Ja("animationend"),Jd=Ja("animationiteration"),Zd=Ja("animationstart"),qd=Ja("transitionend"),ef=new Map,Os="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function mn(e,t){ef.set(e,t),Bn(t,[e])}for(var Ti=0;Ti<Os.length;Ti++){var Li=Os[Ti],Im=Li.toLowerCase(),Um=Li[0].toUpperCase()+Li.slice(1);mn(Im,"on"+Um)}mn(Gd,"onAnimationEnd");mn(Jd,"onAnimationIteration");mn(Zd,"onAnimationStart");mn("dblclick","onDoubleClick");mn("focusin","onFocus");mn("focusout","onBlur");mn(qd,"onTransitionEnd");pr("onMouseEnter",["mouseout","mouseover"]);pr("onMouseLeave",["mouseout","mouseover"]);pr("onPointerEnter",["pointerout","pointerover"]);pr("onPointerLeave",["pointerout","pointerover"]);Bn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Bn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Bn("onBeforeInput",["compositionend","keypress","textInput","paste"]);Bn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Bn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Bn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Qr="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Bm=new Set("cancel close invalid load scroll toggle".split(" ").concat(Qr));function zs(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,Ip(r,t,void 0,e),e.currentTarget=null}function tf(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var r=e[n],l=r.event;r=r.listeners;e:{var a=void 0;if(t)for(var i=r.length-1;0<=i;i--){var o=r[i],u=o.instance,s=o.currentTarget;if(o=o.listener,u!==a&&l.isPropagationStopped())break e;zs(l,o,s),a=u}else for(i=0;i<r.length;i++){if(o=r[i],u=o.instance,s=o.currentTarget,o=o.listener,u!==a&&l.isPropagationStopped())break e;zs(l,o,s),a=u}}}if(xa)throw e=ho,xa=!1,ho=null,e}function ie(e,t){var n=t[Eo];n===void 0&&(n=t[Eo]=new Set);var r=e+"__bubble";n.has(r)||(nf(t,e,2,!1),n.add(r))}function Di(e,t,n){var r=0;t&&(r|=4),nf(n,e,r,t)}var bl="_reactListening"+Math.random().toString(36).slice(2);function dl(e){if(!e[bl]){e[bl]=!0,sd.forEach(function(n){n!=="selectionchange"&&(Bm.has(n)||Di(n,!1,e),Di(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[bl]||(t[bl]=!0,Di("selectionchange",!1,t))}}function nf(e,t,n,r){switch(Bd(t)){case 1:var l=qp;break;case 4:l=em;break;default:l=cu}n=l.bind(null,t,n,e),l=void 0,!fo||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(l=!0),r?l!==void 0?e.addEventListener(t,n,{capture:!0,passive:l}):e.addEventListener(t,n,!0):l!==void 0?e.addEventListener(t,n,{passive:l}):e.addEventListener(t,n,!1)}function Oi(e,t,n,r,l){var a=r;if(!(t&1)&&!(t&2)&&r!==null)e:for(;;){if(r===null)return;var i=r.tag;if(i===3||i===4){var o=r.stateNode.containerInfo;if(o===l||o.nodeType===8&&o.parentNode===l)break;if(i===4)for(i=r.return;i!==null;){var u=i.tag;if((u===3||u===4)&&(u=i.stateNode.containerInfo,u===l||u.nodeType===8&&u.parentNode===l))return;i=i.return}for(;o!==null;){if(i=Mn(o),i===null)return;if(u=i.tag,u===5||u===6){r=a=i;continue e}o=o.parentNode}}r=r.return}Pd(function(){var s=a,c=iu(n),f=[];e:{var h=ef.get(e);if(h!==void 0){var k=fu,S=e;switch(e){case"keypress":if(ua(n)===0)break e;case"keydown":case"keyup":k=mm;break;case"focusin":S="focus",k=Mi;break;case"focusout":S="blur",k=Mi;break;case"beforeblur":case"afterblur":k=Mi;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":k=Es;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":k=rm;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":k=vm;break;case Gd:case Jd:case Zd:k=im;break;case qd:k=xm;break;case"scroll":k=tm;break;case"wheel":k=Sm;break;case"copy":case"cut":case"paste":k=um;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":k=Ps}var v=(t&4)!==0,P=!v&&e==="scroll",p=v?h!==null?h+"Capture":null:h;v=[];for(var d=s,y;d!==null;){y=d;var C=y.stateNode;if(y.tag===5&&C!==null&&(y=C,p!==null&&(C=al(d,p),C!=null&&v.push(fl(d,C,y)))),P)break;d=d.return}0<v.length&&(h=new k(h,S,null,n,c),f.push({event:h,listeners:v}))}}if(!(t&7)){e:{if(h=e==="mouseover"||e==="pointerover",k=e==="mouseout"||e==="pointerout",h&&n!==so&&(S=n.relatedTarget||n.fromElement)&&(Mn(S)||S[It]))break e;if((k||h)&&(h=c.window===c?c:(h=c.ownerDocument)?h.defaultView||h.parentWindow:window,k?(S=n.relatedTarget||n.toElement,k=s,S=S?Mn(S):null,S!==null&&(P=Wn(S),S!==P||S.tag!==5&&S.tag!==6)&&(S=null)):(k=null,S=s),k!==S)){if(v=Es,C="onMouseLeave",p="onMouseEnter",d="mouse",(e==="pointerout"||e==="pointerover")&&(v=Ps,C="onPointerLeave",p="onPointerEnter",d="pointer"),P=k==null?h:tr(k),y=S==null?h:tr(S),h=new v(C,d+"leave",k,n,c),h.target=P,h.relatedTarget=y,C=null,Mn(c)===s&&(v=new v(p,d+"enter",S,n,c),v.target=y,v.relatedTarget=P,C=v),P=C,k&&S)t:{for(v=k,p=S,d=0,y=v;y;y=Qn(y))d++;for(y=0,C=p;C;C=Qn(C))y++;for(;0<d-y;)v=Qn(v),d--;for(;0<y-d;)p=Qn(p),y--;for(;d--;){if(v===p||p!==null&&v===p.alternate)break t;v=Qn(v),p=Qn(p)}v=null}else v=null;k!==null&&Fs(f,h,k,v,!1),S!==null&&P!==null&&Fs(f,P,S,v,!0)}}e:{if(h=s?tr(s):window,k=h.nodeName&&h.nodeName.toLowerCase(),k==="select"||k==="input"&&h.type==="file")var R=jm;else if(_s(h))if(Yd)R=Dm;else{R=Tm;var w=Rm}else(k=h.nodeName)&&k.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(R=Lm);if(R&&(R=R(e,s))){Vd(f,R,n,c);break e}w&&w(e,h,s),e==="focusout"&&(w=h._wrapperState)&&w.controlled&&h.type==="number"&&lo(h,"number",h.value)}switch(w=s?tr(s):window,e){case"focusin":(_s(w)||w.contentEditable==="true")&&(qn=w,yo=s,Zr=null);break;case"focusout":Zr=yo=qn=null;break;case"mousedown":vo=!0;break;case"contextmenu":case"mouseup":case"dragend":vo=!1,Ds(f,n,c);break;case"selectionchange":if(Fm)break;case"keydown":case"keyup":Ds(f,n,c)}var T;if(pu)e:{switch(e){case"compositionstart":var j="onCompositionStart";break e;case"compositionend":j="onCompositionEnd";break e;case"compositionupdate":j="onCompositionUpdate";break e}j=void 0}else Zn?Ad(e,n)&&(j="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(j="onCompositionStart");j&&($d&&n.locale!=="ko"&&(Zn||j!=="onCompositionStart"?j==="onCompositionEnd"&&Zn&&(T=Wd()):(en=c,du="value"in en?en.value:en.textContent,Zn=!0)),w=Pa(s,j),0<w.length&&(j=new Cs(j,e,null,n,c),f.push({event:j,listeners:w}),T?j.data=T:(T=Hd(n),T!==null&&(j.data=T)))),(T=Cm?Pm(e,n):Nm(e,n))&&(s=Pa(s,"onBeforeInput"),0<s.length&&(c=new Cs("onBeforeInput","beforeinput",null,n,c),f.push({event:c,listeners:s}),c.data=T))}tf(f,t)})}function fl(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Pa(e,t){for(var n=t+"Capture",r=[];e!==null;){var l=e,a=l.stateNode;l.tag===5&&a!==null&&(l=a,a=al(e,n),a!=null&&r.unshift(fl(e,a,l)),a=al(e,t),a!=null&&r.push(fl(e,a,l))),e=e.return}return r}function Qn(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Fs(e,t,n,r,l){for(var a=t._reactName,i=[];n!==null&&n!==r;){var o=n,u=o.alternate,s=o.stateNode;if(u!==null&&u===r)break;o.tag===5&&s!==null&&(o=s,l?(u=al(n,a),u!=null&&i.unshift(fl(n,u,o))):l||(u=al(n,a),u!=null&&i.push(fl(n,u,o)))),n=n.return}i.length!==0&&e.push({event:t,listeners:i})}var Wm=/\r\n?/g,$m=/\u0000|\uFFFD/g;function Is(e){return(typeof e=="string"?e:""+e).replace(Wm,` -`).replace($m,"")}function Xl(e,t,n){if(t=Is(t),Is(e)!==t&&n)throw Error(_(425))}function Na(){}var wo=null,xo=null;function ko(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var So=typeof setTimeout=="function"?setTimeout:void 0,Am=typeof clearTimeout=="function"?clearTimeout:void 0,Us=typeof Promise=="function"?Promise:void 0,Hm=typeof queueMicrotask=="function"?queueMicrotask:typeof Us<"u"?function(e){return Us.resolve(null).then(e).catch(Vm)}:So;function Vm(e){setTimeout(function(){throw e})}function zi(e,t){var n=t,r=0;do{var l=n.nextSibling;if(e.removeChild(n),l&&l.nodeType===8)if(n=l.data,n==="/$"){if(r===0){e.removeChild(l),ul(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=l}while(n);ul(t)}function un(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Bs(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var Cr=Math.random().toString(36).slice(2),Et="__reactFiber$"+Cr,hl="__reactProps$"+Cr,It="__reactContainer$"+Cr,Eo="__reactEvents$"+Cr,Ym="__reactListeners$"+Cr,Qm="__reactHandles$"+Cr;function Mn(e){var t=e[Et];if(t)return t;for(var n=e.parentNode;n;){if(t=n[It]||n[Et]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Bs(e);e!==null;){if(n=e[Et])return n;e=Bs(e)}return t}e=n,n=e.parentNode}return null}function Ml(e){return e=e[Et]||e[It],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function tr(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(_(33))}function Za(e){return e[hl]||null}var Co=[],nr=-1;function gn(e){return{current:e}}function oe(e){0>nr||(e.current=Co[nr],Co[nr]=null,nr--)}function le(e,t){nr++,Co[nr]=e.current,e.current=t}var pn={},Ue=gn(pn),Xe=gn(!1),Dn=pn;function mr(e,t){var n=e.type.contextTypes;if(!n)return pn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},a;for(a in n)l[a]=t[a];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function Ke(e){return e=e.childContextTypes,e!=null}function Ma(){oe(Xe),oe(Ue)}function Ws(e,t,n){if(Ue.current!==pn)throw Error(_(168));le(Ue,t),le(Xe,n)}function rf(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(_(108,Rp(e)||"Unknown",l));return he({},n,r)}function _a(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pn,Dn=Ue.current,le(Ue,e),le(Xe,Xe.current),!0}function $s(e,t,n){var r=e.stateNode;if(!r)throw Error(_(169));n?(e=rf(e,t,Dn),r.__reactInternalMemoizedMergedChildContext=e,oe(Xe),oe(Ue),le(Ue,e)):oe(Xe),le(Xe,n)}var Tt=null,qa=!1,Fi=!1;function lf(e){Tt===null?Tt=[e]:Tt.push(e)}function bm(e){qa=!0,lf(e)}function yn(){if(!Fi&&Tt!==null){Fi=!0;var e=0,t=ee;try{var n=Tt;for(ee=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Tt=null,qa=!1}catch(l){throw Tt!==null&&(Tt=Tt.slice(e+1)),jd(ou,yn),l}finally{ee=t,Fi=!1}}return null}var rr=[],lr=0,ja=null,Ra=0,lt=[],at=0,On=null,Lt=1,Dt="";function Sn(e,t){rr[lr++]=Ra,rr[lr++]=ja,ja=e,Ra=t}function af(e,t,n){lt[at++]=Lt,lt[at++]=Dt,lt[at++]=On,On=e;var r=Lt;e=Dt;var l=32-gt(r)-1;r&=~(1<<l),n+=1;var a=32-gt(t)+l;if(30<a){var i=l-l%5;a=(r&(1<<i)-1).toString(32),r>>=i,l-=i,Lt=1<<32-gt(t)+l|n<<l|r,Dt=a+e}else Lt=1<<a|n<<l|r,Dt=e}function gu(e){e.return!==null&&(Sn(e,1),af(e,1,0))}function yu(e){for(;e===ja;)ja=rr[--lr],rr[lr]=null,Ra=rr[--lr],rr[lr]=null;for(;e===On;)On=lt[--at],lt[at]=null,Dt=lt[--at],lt[at]=null,Lt=lt[--at],lt[at]=null}var et=null,qe=null,se=!1,mt=null;function of(e,t){var n=it(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function As(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,et=e,qe=un(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,et=e,qe=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=On!==null?{id:Lt,overflow:Dt}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=it(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,et=e,qe=null,!0):!1;default:return!1}}function Po(e){return(e.mode&1)!==0&&(e.flags&128)===0}function No(e){if(se){var t=qe;if(t){var n=t;if(!As(e,t)){if(Po(e))throw Error(_(418));t=un(n.nextSibling);var r=et;t&&As(e,t)?of(r,n):(e.flags=e.flags&-4097|2,se=!1,et=e)}}else{if(Po(e))throw Error(_(418));e.flags=e.flags&-4097|2,se=!1,et=e}}}function Hs(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;et=e}function Kl(e){if(e!==et)return!1;if(!se)return Hs(e),se=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!ko(e.type,e.memoizedProps)),t&&(t=qe)){if(Po(e))throw uf(),Error(_(418));for(;t;)of(e,t),t=un(t.nextSibling)}if(Hs(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(_(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"){if(t===0){qe=un(e.nextSibling);break e}t--}else n!=="$"&&n!=="$!"&&n!=="$?"||t++}e=e.nextSibling}qe=null}}else qe=et?un(e.stateNode.nextSibling):null;return!0}function uf(){for(var e=qe;e;)e=un(e.nextSibling)}function gr(){qe=et=null,se=!1}function vu(e){mt===null?mt=[e]:mt.push(e)}var Xm=$t.ReactCurrentBatchConfig;function zr(e,t,n){if(e=n.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(_(309));var r=n.stateNode}if(!r)throw Error(_(147,e));var l=r,a=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===a?t.ref:(t=function(i){var o=l.refs;i===null?delete o[a]:o[a]=i},t._stringRef=a,t)}if(typeof e!="string")throw Error(_(284));if(!n._owner)throw Error(_(290,e))}return e}function Gl(e,t){throw e=Object.prototype.toString.call(t),Error(_(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Vs(e){var t=e._init;return t(e._payload)}function sf(e){function t(p,d){if(e){var y=p.deletions;y===null?(p.deletions=[d],p.flags|=16):y.push(d)}}function n(p,d){if(!e)return null;for(;d!==null;)t(p,d),d=d.sibling;return null}function r(p,d){for(p=new Map;d!==null;)d.key!==null?p.set(d.key,d):p.set(d.index,d),d=d.sibling;return p}function l(p,d){return p=fn(p,d),p.index=0,p.sibling=null,p}function a(p,d,y){return p.index=y,e?(y=p.alternate,y!==null?(y=y.index,y<d?(p.flags|=2,d):y):(p.flags|=2,d)):(p.flags|=1048576,d)}function i(p){return e&&p.alternate===null&&(p.flags|=2),p}function o(p,d,y,C){return d===null||d.tag!==6?(d=Hi(y,p.mode,C),d.return=p,d):(d=l(d,y),d.return=p,d)}function u(p,d,y,C){var R=y.type;return R===Jn?c(p,d,y.props.children,C,y.key):d!==null&&(d.elementType===R||typeof R=="object"&&R!==null&&R.$$typeof===Gt&&Vs(R)===d.type)?(C=l(d,y.props),C.ref=zr(p,d,y),C.return=p,C):(C=ma(y.type,y.key,y.props,null,p.mode,C),C.ref=zr(p,d,y),C.return=p,C)}function s(p,d,y,C){return d===null||d.tag!==4||d.stateNode.containerInfo!==y.containerInfo||d.stateNode.implementation!==y.implementation?(d=Vi(y,p.mode,C),d.return=p,d):(d=l(d,y.children||[]),d.return=p,d)}function c(p,d,y,C,R){return d===null||d.tag!==7?(d=Ln(y,p.mode,C,R),d.return=p,d):(d=l(d,y),d.return=p,d)}function f(p,d,y){if(typeof d=="string"&&d!==""||typeof d=="number")return d=Hi(""+d,p.mode,y),d.return=p,d;if(typeof d=="object"&&d!==null){switch(d.$$typeof){case Bl:return y=ma(d.type,d.key,d.props,null,p.mode,y),y.ref=zr(p,null,d),y.return=p,y;case Gn:return d=Vi(d,p.mode,y),d.return=p,d;case Gt:var C=d._init;return f(p,C(d._payload),y)}if(Vr(d)||Rr(d))return d=Ln(d,p.mode,y,null),d.return=p,d;Gl(p,d)}return null}function h(p,d,y,C){var R=d!==null?d.key:null;if(typeof y=="string"&&y!==""||typeof y=="number")return R!==null?null:o(p,d,""+y,C);if(typeof y=="object"&&y!==null){switch(y.$$typeof){case Bl:return y.key===R?u(p,d,y,C):null;case Gn:return y.key===R?s(p,d,y,C):null;case Gt:return R=y._init,h(p,d,R(y._payload),C)}if(Vr(y)||Rr(y))return R!==null?null:c(p,d,y,C,null);Gl(p,y)}return null}function k(p,d,y,C,R){if(typeof C=="string"&&C!==""||typeof C=="number")return p=p.get(y)||null,o(d,p,""+C,R);if(typeof C=="object"&&C!==null){switch(C.$$typeof){case Bl:return p=p.get(C.key===null?y:C.key)||null,u(d,p,C,R);case Gn:return p=p.get(C.key===null?y:C.key)||null,s(d,p,C,R);case Gt:var w=C._init;return k(p,d,y,w(C._payload),R)}if(Vr(C)||Rr(C))return p=p.get(y)||null,c(d,p,C,R,null);Gl(d,C)}return null}function S(p,d,y,C){for(var R=null,w=null,T=d,j=d=0,B=null;T!==null&&j<y.length;j++){T.index>j?(B=T,T=null):B=T.sibling;var U=h(p,T,y[j],C);if(U===null){T===null&&(T=B);break}e&&T&&U.alternate===null&&t(p,T),d=a(U,d,j),w===null?R=U:w.sibling=U,w=U,T=B}if(j===y.length)return n(p,T),se&&Sn(p,j),R;if(T===null){for(;j<y.length;j++)T=f(p,y[j],C),T!==null&&(d=a(T,d,j),w===null?R=T:w.sibling=T,w=T);return se&&Sn(p,j),R}for(T=r(p,T);j<y.length;j++)B=k(T,p,j,y[j],C),B!==null&&(e&&B.alternate!==null&&T.delete(B.key===null?j:B.key),d=a(B,d,j),w===null?R=B:w.sibling=B,w=B);return e&&T.forEach(function(te){return t(p,te)}),se&&Sn(p,j),R}function v(p,d,y,C){var R=Rr(y);if(typeof R!="function")throw Error(_(150));if(y=R.call(y),y==null)throw Error(_(151));for(var w=R=null,T=d,j=d=0,B=null,U=y.next();T!==null&&!U.done;j++,U=y.next()){T.index>j?(B=T,T=null):B=T.sibling;var te=h(p,T,U.value,C);if(te===null){T===null&&(T=B);break}e&&T&&te.alternate===null&&t(p,T),d=a(te,d,j),w===null?R=te:w.sibling=te,w=te,T=B}if(U.done)return n(p,T),se&&Sn(p,j),R;if(T===null){for(;!U.done;j++,U=y.next())U=f(p,U.value,C),U!==null&&(d=a(U,d,j),w===null?R=U:w.sibling=U,w=U);return se&&Sn(p,j),R}for(T=r(p,T);!U.done;j++,U=y.next())U=k(T,p,j,U.value,C),U!==null&&(e&&U.alternate!==null&&T.delete(U.key===null?j:U.key),d=a(U,d,j),w===null?R=U:w.sibling=U,w=U);return e&&T.forEach(function(ce){return t(p,ce)}),se&&Sn(p,j),R}function P(p,d,y,C){if(typeof y=="object"&&y!==null&&y.type===Jn&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case Bl:e:{for(var R=y.key,w=d;w!==null;){if(w.key===R){if(R=y.type,R===Jn){if(w.tag===7){n(p,w.sibling),d=l(w,y.props.children),d.return=p,p=d;break e}}else if(w.elementType===R||typeof R=="object"&&R!==null&&R.$$typeof===Gt&&Vs(R)===w.type){n(p,w.sibling),d=l(w,y.props),d.ref=zr(p,w,y),d.return=p,p=d;break e}n(p,w);break}else t(p,w);w=w.sibling}y.type===Jn?(d=Ln(y.props.children,p.mode,C,y.key),d.return=p,p=d):(C=ma(y.type,y.key,y.props,null,p.mode,C),C.ref=zr(p,d,y),C.return=p,p=C)}return i(p);case Gn:e:{for(w=y.key;d!==null;){if(d.key===w)if(d.tag===4&&d.stateNode.containerInfo===y.containerInfo&&d.stateNode.implementation===y.implementation){n(p,d.sibling),d=l(d,y.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=Vi(y,p.mode,C),d.return=p,p=d}return i(p);case Gt:return w=y._init,P(p,d,w(y._payload),C)}if(Vr(y))return S(p,d,y,C);if(Rr(y))return v(p,d,y,C);Gl(p,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,y),d.return=p,p=d):(n(p,d),d=Hi(y,p.mode,C),d.return=p,p=d),i(p)):n(p,d)}return P}var yr=sf(!0),cf=sf(!1),Ta=gn(null),La=null,ar=null,wu=null;function xu(){wu=ar=La=null}function ku(e){var t=Ta.current;oe(Ta),e._currentValue=t}function Mo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function fr(e,t){La=e,wu=ar=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(be=!0),e.firstContext=null)}function ut(e){var t=e._currentValue;if(wu!==e)if(e={context:e,memoizedValue:t,next:null},ar===null){if(La===null)throw Error(_(308));ar=e,La.dependencies={lanes:0,firstContext:e}}else ar=ar.next=e;return t}var _n=null;function Su(e){_n===null?_n=[e]:_n.push(e)}function df(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Su(t)):(n.next=l.next,l.next=n),t.interleaved=n,Ut(e,r)}function Ut(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Jt=!1;function Eu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ff(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ot(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function sn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,K&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Ut(e,n)}return l=r.interleaved,l===null?(t.next=t,Su(r)):(t.next=l.next,l.next=t),r.interleaved=t,Ut(e,n)}function sa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,uu(e,n)}}function Ys(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?l=a=i:a=a.next=i,n=n.next}while(n!==null);a===null?l=a=t:a=a.next=t}else l=a=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Da(e,t,n,r){var l=e.updateQueue;Jt=!1;var a=l.firstBaseUpdate,i=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,s=u.next;u.next=null,i===null?a=s:i.next=s,i=u;var c=e.alternate;c!==null&&(c=c.updateQueue,o=c.lastBaseUpdate,o!==i&&(o===null?c.firstBaseUpdate=s:o.next=s,c.lastBaseUpdate=u))}if(a!==null){var f=l.baseState;i=0,c=s=u=null,o=a;do{var h=o.lane,k=o.eventTime;if((r&h)===h){c!==null&&(c=c.next={eventTime:k,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var S=e,v=o;switch(h=t,k=n,v.tag){case 1:if(S=v.payload,typeof S=="function"){f=S.call(k,f,h);break e}f=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=v.payload,h=typeof S=="function"?S.call(k,f,h):S,h==null)break e;f=he({},f,h);break e;case 2:Jt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else k={eventTime:k,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},c===null?(s=c=k,u=f):c=c.next=k,i|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(c===null&&(u=f),l.baseState=u,l.firstBaseUpdate=s,l.lastBaseUpdate=c,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else a===null&&(l.shared.lanes=0);Fn|=i,e.lanes=i,e.memoizedState=f}}function Qs(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var r=e[t],l=r.callback;if(l!==null){if(r.callback=null,r=n,typeof l!="function")throw Error(_(191,l));l.call(r)}}}var _l={},Pt=gn(_l),pl=gn(_l),ml=gn(_l);function jn(e){if(e===_l)throw Error(_(174));return e}function Cu(e,t){switch(le(ml,t),le(pl,e),le(Pt,_l),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:io(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=io(t,e)}oe(Pt),le(Pt,t)}function vr(){oe(Pt),oe(pl),oe(ml)}function hf(e){jn(ml.current);var t=jn(Pt.current),n=io(t,e.type);t!==n&&(le(pl,e),le(Pt,n))}function Pu(e){pl.current===e&&(oe(Pt),oe(pl))}var de=gn(0);function Oa(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Ii=[];function Nu(){for(var e=0;e<Ii.length;e++)Ii[e]._workInProgressVersionPrimary=null;Ii.length=0}var ca=$t.ReactCurrentDispatcher,Ui=$t.ReactCurrentBatchConfig,zn=0,fe=null,Pe=null,_e=null,za=!1,qr=!1,gl=0,Km=0;function ze(){throw Error(_(321))}function Mu(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!vt(e[n],t[n]))return!1;return!0}function _u(e,t,n,r,l,a){if(zn=a,fe=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,ca.current=e===null||e.memoizedState===null?qm:eg,e=n(r,l),qr){a=0;do{if(qr=!1,gl=0,25<=a)throw Error(_(301));a+=1,_e=Pe=null,t.updateQueue=null,ca.current=tg,e=n(r,l)}while(qr)}if(ca.current=Fa,t=Pe!==null&&Pe.next!==null,zn=0,_e=Pe=fe=null,za=!1,t)throw Error(_(300));return e}function ju(){var e=gl!==0;return gl=0,e}function St(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return _e===null?fe.memoizedState=_e=e:_e=_e.next=e,_e}function st(){if(Pe===null){var e=fe.alternate;e=e!==null?e.memoizedState:null}else e=Pe.next;var t=_e===null?fe.memoizedState:_e.next;if(t!==null)_e=t,Pe=e;else{if(e===null)throw Error(_(310));Pe=e,e={memoizedState:Pe.memoizedState,baseState:Pe.baseState,baseQueue:Pe.baseQueue,queue:Pe.queue,next:null},_e===null?fe.memoizedState=_e=e:_e=_e.next=e}return _e}function yl(e,t){return typeof t=="function"?t(e):t}function Bi(e){var t=st(),n=t.queue;if(n===null)throw Error(_(311));n.lastRenderedReducer=e;var r=Pe,l=r.baseQueue,a=n.pending;if(a!==null){if(l!==null){var i=l.next;l.next=a.next,a.next=i}r.baseQueue=l=a,n.pending=null}if(l!==null){a=l.next,r=r.baseState;var o=i=null,u=null,s=a;do{var c=s.lane;if((zn&c)===c)u!==null&&(u=u.next={lane:0,action:s.action,hasEagerState:s.hasEagerState,eagerState:s.eagerState,next:null}),r=s.hasEagerState?s.eagerState:e(r,s.action);else{var f={lane:c,action:s.action,hasEagerState:s.hasEagerState,eagerState:s.eagerState,next:null};u===null?(o=u=f,i=r):u=u.next=f,fe.lanes|=c,Fn|=c}s=s.next}while(s!==null&&s!==a);u===null?i=r:u.next=o,vt(r,t.memoizedState)||(be=!0),t.memoizedState=r,t.baseState=i,t.baseQueue=u,n.lastRenderedState=r}if(e=n.interleaved,e!==null){l=e;do a=l.lane,fe.lanes|=a,Fn|=a,l=l.next;while(l!==e)}else l===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function Wi(e){var t=st(),n=t.queue;if(n===null)throw Error(_(311));n.lastRenderedReducer=e;var r=n.dispatch,l=n.pending,a=t.memoizedState;if(l!==null){n.pending=null;var i=l=l.next;do a=e(a,i.action),i=i.next;while(i!==l);vt(a,t.memoizedState)||(be=!0),t.memoizedState=a,t.baseQueue===null&&(t.baseState=a),n.lastRenderedState=a}return[a,r]}function pf(){}function mf(e,t){var n=fe,r=st(),l=t(),a=!vt(r.memoizedState,l);if(a&&(r.memoizedState=l,be=!0),r=r.queue,Ru(vf.bind(null,n,r,e),[e]),r.getSnapshot!==t||a||_e!==null&&_e.memoizedState.tag&1){if(n.flags|=2048,vl(9,yf.bind(null,n,r,l,t),void 0,null),je===null)throw Error(_(349));zn&30||gf(n,t,l)}return l}function gf(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=fe.updateQueue,t===null?(t={lastEffect:null,stores:null},fe.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function yf(e,t,n,r){t.value=n,t.getSnapshot=r,wf(t)&&xf(e)}function vf(e,t,n){return n(function(){wf(t)&&xf(e)})}function wf(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!vt(e,n)}catch{return!0}}function xf(e){var t=Ut(e,1);t!==null&&yt(t,e,1,-1)}function bs(e){var t=St();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:yl,lastRenderedState:e},t.queue=e,e=e.dispatch=Zm.bind(null,fe,e),[t.memoizedState,e]}function vl(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},t=fe.updateQueue,t===null?(t={lastEffect:null,stores:null},fe.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e)),e}function kf(){return st().memoizedState}function da(e,t,n,r){var l=St();fe.flags|=e,l.memoizedState=vl(1|t,n,void 0,r===void 0?null:r)}function ei(e,t,n,r){var l=st();r=r===void 0?null:r;var a=void 0;if(Pe!==null){var i=Pe.memoizedState;if(a=i.destroy,r!==null&&Mu(r,i.deps)){l.memoizedState=vl(t,n,a,r);return}}fe.flags|=e,l.memoizedState=vl(1|t,n,a,r)}function Xs(e,t){return da(8390656,8,e,t)}function Ru(e,t){return ei(2048,8,e,t)}function Sf(e,t){return ei(4,2,e,t)}function Ef(e,t){return ei(4,4,e,t)}function Cf(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Pf(e,t,n){return n=n!=null?n.concat([e]):null,ei(4,4,Cf.bind(null,t,e),n)}function Tu(){}function Nf(e,t){var n=st();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Mu(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function Mf(e,t){var n=st();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Mu(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function _f(e,t,n){return zn&21?(vt(n,t)||(n=Ld(),fe.lanes|=n,Fn|=n,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,be=!0),e.memoizedState=n)}function Gm(e,t){var n=ee;ee=n!==0&&4>n?n:4,e(!0);var r=Ui.transition;Ui.transition={};try{e(!1),t()}finally{ee=n,Ui.transition=r}}function jf(){return st().memoizedState}function Jm(e,t,n){var r=dn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Rf(e))Tf(t,n);else if(n=df(e,t,n,r),n!==null){var l=Ae();yt(n,e,r,l),Lf(n,t,r)}}function Zm(e,t,n){var r=dn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Rf(e))Tf(t,l);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var i=t.lastRenderedState,o=a(i,n);if(l.hasEagerState=!0,l.eagerState=o,vt(o,i)){var u=t.interleaved;u===null?(l.next=l,Su(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=df(e,t,l,r),n!==null&&(l=Ae(),yt(n,e,r,l),Lf(n,t,r))}}function Rf(e){var t=e.alternate;return e===fe||t!==null&&t===fe}function Tf(e,t){qr=za=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Lf(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,uu(e,n)}}var Fa={readContext:ut,useCallback:ze,useContext:ze,useEffect:ze,useImperativeHandle:ze,useInsertionEffect:ze,useLayoutEffect:ze,useMemo:ze,useReducer:ze,useRef:ze,useState:ze,useDebugValue:ze,useDeferredValue:ze,useTransition:ze,useMutableSource:ze,useSyncExternalStore:ze,useId:ze,unstable_isNewReconciler:!1},qm={readContext:ut,useCallback:function(e,t){return St().memoizedState=[e,t===void 0?null:t],e},useContext:ut,useEffect:Xs,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,da(4194308,4,Cf.bind(null,t,e),n)},useLayoutEffect:function(e,t){return da(4194308,4,e,t)},useInsertionEffect:function(e,t){return da(4,2,e,t)},useMemo:function(e,t){var n=St();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=St();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Jm.bind(null,fe,e),[r.memoizedState,e]},useRef:function(e){var t=St();return e={current:e},t.memoizedState=e},useState:bs,useDebugValue:Tu,useDeferredValue:function(e){return St().memoizedState=e},useTransition:function(){var e=bs(!1),t=e[0];return e=Gm.bind(null,e[1]),St().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=fe,l=St();if(se){if(n===void 0)throw Error(_(407));n=n()}else{if(n=t(),je===null)throw Error(_(349));zn&30||gf(r,t,n)}l.memoizedState=n;var a={value:n,getSnapshot:t};return l.queue=a,Xs(vf.bind(null,r,a,e),[e]),r.flags|=2048,vl(9,yf.bind(null,r,a,n,t),void 0,null),n},useId:function(){var e=St(),t=je.identifierPrefix;if(se){var n=Dt,r=Lt;n=(r&~(1<<32-gt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=gl++,0<n&&(t+="H"+n.toString(32)),t+=":"}else n=Km++,t=":"+t+"r"+n.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},eg={readContext:ut,useCallback:Nf,useContext:ut,useEffect:Ru,useImperativeHandle:Pf,useInsertionEffect:Sf,useLayoutEffect:Ef,useMemo:Mf,useReducer:Bi,useRef:kf,useState:function(){return Bi(yl)},useDebugValue:Tu,useDeferredValue:function(e){var t=st();return _f(t,Pe.memoizedState,e)},useTransition:function(){var e=Bi(yl)[0],t=st().memoizedState;return[e,t]},useMutableSource:pf,useSyncExternalStore:mf,useId:jf,unstable_isNewReconciler:!1},tg={readContext:ut,useCallback:Nf,useContext:ut,useEffect:Ru,useImperativeHandle:Pf,useInsertionEffect:Sf,useLayoutEffect:Ef,useMemo:Mf,useReducer:Wi,useRef:kf,useState:function(){return Wi(yl)},useDebugValue:Tu,useDeferredValue:function(e){var t=st();return Pe===null?t.memoizedState=e:_f(t,Pe.memoizedState,e)},useTransition:function(){var e=Wi(yl)[0],t=st().memoizedState;return[e,t]},useMutableSource:pf,useSyncExternalStore:mf,useId:jf,unstable_isNewReconciler:!1};function ft(e,t){if(e&&e.defaultProps){t=he({},t),e=e.defaultProps;for(var n in e)t[n]===void 0&&(t[n]=e[n]);return t}return t}function _o(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:he({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var ti={isMounted:function(e){return(e=e._reactInternals)?Wn(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=Ae(),l=dn(e),a=Ot(r,l);a.payload=t,n!=null&&(a.callback=n),t=sn(e,a,l),t!==null&&(yt(t,e,l,r),sa(t,e,l))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=Ae(),l=dn(e),a=Ot(r,l);a.tag=1,a.payload=t,n!=null&&(a.callback=n),t=sn(e,a,l),t!==null&&(yt(t,e,l,r),sa(t,e,l))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=Ae(),r=dn(e),l=Ot(n,r);l.tag=2,t!=null&&(l.callback=t),t=sn(e,l,r),t!==null&&(yt(t,e,r,n),sa(t,e,r))}};function Ks(e,t,n,r,l,a,i){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,a,i):t.prototype&&t.prototype.isPureReactComponent?!cl(n,r)||!cl(l,a):!0}function Df(e,t,n){var r=!1,l=pn,a=t.contextType;return typeof a=="object"&&a!==null?a=ut(a):(l=Ke(t)?Dn:Ue.current,r=t.contextTypes,a=(r=r!=null)?mr(e,l):pn),t=new t(n,a),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=ti,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),t}function Gs(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&ti.enqueueReplaceState(t,t.state,null)}function jo(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs={},Eu(e);var a=t.contextType;typeof a=="object"&&a!==null?l.context=ut(a):(a=Ke(t)?Dn:Ue.current,l.context=mr(e,a)),l.state=e.memoizedState,a=t.getDerivedStateFromProps,typeof a=="function"&&(_o(e,t,a,n),l.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof l.getSnapshotBeforeUpdate=="function"||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(t=l.state,typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount(),t!==l.state&&ti.enqueueReplaceState(l,l.state,null),Da(e,n,l,r),l.state=e.memoizedState),typeof l.componentDidMount=="function"&&(e.flags|=4194308)}function wr(e,t){try{var n="",r=t;do n+=jp(r),r=r.return;while(r);var l=n}catch(a){l=` -Error generating stack: `+a.message+` -`+a.stack}return{value:e,source:t,stack:l,digest:null}}function $i(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Ro(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var ng=typeof WeakMap=="function"?WeakMap:Map;function Of(e,t,n){n=Ot(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ua||(Ua=!0,Wo=r),Ro(e,t)},n}function zf(e,t,n){n=Ot(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){Ro(e,t)}}var a=e.stateNode;return a!==null&&typeof a.componentDidCatch=="function"&&(n.callback=function(){Ro(e,t),typeof r!="function"&&(cn===null?cn=new Set([this]):cn.add(this));var i=t.stack;this.componentDidCatch(t.value,{componentStack:i!==null?i:""})}),n}function Js(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new ng;var l=new Set;r.set(t,l)}else l=r.get(t),l===void 0&&(l=new Set,r.set(t,l));l.has(n)||(l.add(n),e=gg.bind(null,e,t,n),t.then(e,e))}function Zs(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function qs(e,t,n,r,l){return e.mode&1?(e.flags|=65536,e.lanes=l,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Ot(-1,1),t.tag=2,sn(n,t,1))),n.lanes|=1),e)}var rg=$t.ReactCurrentOwner,be=!1;function $e(e,t,n,r){t.child=e===null?cf(t,null,n,r):yr(t,e.child,n,r)}function ec(e,t,n,r,l){n=n.render;var a=t.ref;return fr(t,l),r=_u(e,t,n,r,a,l),n=ju(),e!==null&&!be?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Bt(e,t,l)):(se&&n&&gu(t),t.flags|=1,$e(e,t,r,l),t.child)}function tc(e,t,n,r,l){if(e===null){var a=n.type;return typeof a=="function"&&!Bu(a)&&a.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=a,Ff(e,t,a,r,l)):(e=ma(n.type,null,r,t,t.mode,l),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,!(e.lanes&l)){var i=a.memoizedProps;if(n=n.compare,n=n!==null?n:cl,n(i,r)&&e.ref===t.ref)return Bt(e,t,l)}return t.flags|=1,e=fn(a,r),e.ref=t.ref,e.return=t,t.child=e}function Ff(e,t,n,r,l){if(e!==null){var a=e.memoizedProps;if(cl(a,r)&&e.ref===t.ref)if(be=!1,t.pendingProps=r=a,(e.lanes&l)!==0)e.flags&131072&&(be=!0);else return t.lanes=e.lanes,Bt(e,t,l)}return To(e,t,n,r,l)}function If(e,t,n){var r=t.pendingProps,l=r.children,a=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},le(or,Je),Je|=n;else{if(!(n&1073741824))return e=a!==null?a.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,le(or,Je),Je|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=a!==null?a.baseLanes:n,le(or,Je),Je|=r}else a!==null?(r=a.baseLanes|n,t.memoizedState=null):r=n,le(or,Je),Je|=r;return $e(e,t,l,n),t.child}function Uf(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function To(e,t,n,r,l){var a=Ke(n)?Dn:Ue.current;return a=mr(t,a),fr(t,l),n=_u(e,t,n,r,a,l),r=ju(),e!==null&&!be?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Bt(e,t,l)):(se&&r&&gu(t),t.flags|=1,$e(e,t,n,l),t.child)}function nc(e,t,n,r,l){if(Ke(n)){var a=!0;_a(t)}else a=!1;if(fr(t,l),t.stateNode===null)fa(e,t),Df(t,n,r),jo(t,n,r,l),r=!0;else if(e===null){var i=t.stateNode,o=t.memoizedProps;i.props=o;var u=i.context,s=n.contextType;typeof s=="object"&&s!==null?s=ut(s):(s=Ke(n)?Dn:Ue.current,s=mr(t,s));var c=n.getDerivedStateFromProps,f=typeof c=="function"||typeof i.getSnapshotBeforeUpdate=="function";f||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(o!==r||u!==s)&&Gs(t,i,r,s),Jt=!1;var h=t.memoizedState;i.state=h,Da(t,r,i,l),u=t.memoizedState,o!==r||h!==u||Xe.current||Jt?(typeof c=="function"&&(_o(t,n,c,r),u=t.memoizedState),(o=Jt||Ks(t,n,o,r,h,u,s))?(f||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(t.flags|=4194308)):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=u),i.props=r,i.state=u,i.context=s,r=o):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{i=t.stateNode,ff(e,t),o=t.memoizedProps,s=t.type===t.elementType?o:ft(t.type,o),i.props=s,f=t.pendingProps,h=i.context,u=n.contextType,typeof u=="object"&&u!==null?u=ut(u):(u=Ke(n)?Dn:Ue.current,u=mr(t,u));var k=n.getDerivedStateFromProps;(c=typeof k=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(o!==f||h!==u)&&Gs(t,i,r,u),Jt=!1,h=t.memoizedState,i.state=h,Da(t,r,i,l);var S=t.memoizedState;o!==f||h!==S||Xe.current||Jt?(typeof k=="function"&&(_o(t,n,k,r),S=t.memoizedState),(s=Jt||Ks(t,n,s,r,h,S,u)||!1)?(c||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,S,u),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,S,u)),typeof i.componentDidUpdate=="function"&&(t.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof i.componentDidUpdate!="function"||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=S),i.props=r,i.state=S,i.context=u,r=s):(typeof i.componentDidUpdate!="function"||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),r=!1)}return Lo(e,t,n,r,a,l)}function Lo(e,t,n,r,l,a){Uf(e,t);var i=(t.flags&128)!==0;if(!r&&!i)return l&&$s(t,n,!1),Bt(e,t,a);r=t.stateNode,rg.current=t;var o=i&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&i?(t.child=yr(t,e.child,null,a),t.child=yr(t,null,o,a)):$e(e,t,o,a),t.memoizedState=r.state,l&&$s(t,n,!0),t.child}function Bf(e){var t=e.stateNode;t.pendingContext?Ws(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Ws(e,t.context,!1),Cu(e,t.containerInfo)}function rc(e,t,n,r,l){return gr(),vu(l),t.flags|=256,$e(e,t,n,r),t.child}var Do={dehydrated:null,treeContext:null,retryLane:0};function Oo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Wf(e,t,n){var r=t.pendingProps,l=de.current,a=!1,i=(t.flags&128)!==0,o;if((o=i)||(o=e!==null&&e.memoizedState===null?!1:(l&2)!==0),o?(a=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),le(de,l&1),e===null)return No(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(i=r.children,e=r.fallback,a?(r=t.mode,a=t.child,i={mode:"hidden",children:i},!(r&1)&&a!==null?(a.childLanes=0,a.pendingProps=i):a=li(i,r,0,null),e=Ln(e,r,n,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=Oo(n),t.memoizedState=Do,e):Lu(t,i));if(l=e.memoizedState,l!==null&&(o=l.dehydrated,o!==null))return lg(e,t,i,r,o,l,n);if(a){a=r.fallback,i=t.mode,l=e.child,o=l.sibling;var u={mode:"hidden",children:r.children};return!(i&1)&&t.child!==l?(r=t.child,r.childLanes=0,r.pendingProps=u,t.deletions=null):(r=fn(l,u),r.subtreeFlags=l.subtreeFlags&14680064),o!==null?a=fn(o,a):(a=Ln(a,i,n,null),a.flags|=2),a.return=t,r.return=t,r.sibling=a,t.child=r,r=a,a=t.child,i=e.child.memoizedState,i=i===null?Oo(n):{baseLanes:i.baseLanes|n,cachePool:null,transitions:i.transitions},a.memoizedState=i,a.childLanes=e.childLanes&~n,t.memoizedState=Do,r}return a=e.child,e=a.sibling,r=fn(a,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function Lu(e,t){return t=li({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Jl(e,t,n,r){return r!==null&&vu(r),yr(t,e.child,null,n),e=Lu(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function lg(e,t,n,r,l,a,i){if(n)return t.flags&256?(t.flags&=-257,r=$i(Error(_(422))),Jl(e,t,i,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(a=r.fallback,l=t.mode,r=li({mode:"visible",children:r.children},l,0,null),a=Ln(a,l,i,null),a.flags|=2,r.return=t,a.return=t,r.sibling=a,t.child=r,t.mode&1&&yr(t,e.child,null,i),t.child.memoizedState=Oo(i),t.memoizedState=Do,a);if(!(t.mode&1))return Jl(e,t,i,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var o=r.dgst;return r=o,a=Error(_(419)),r=$i(a,r,void 0),Jl(e,t,i,r)}if(o=(i&e.childLanes)!==0,be||o){if(r=je,r!==null){switch(i&-i){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=l&(r.suspendedLanes|i)?0:l,l!==0&&l!==a.retryLane&&(a.retryLane=l,Ut(e,l),yt(r,e,l,-1))}return Uu(),r=$i(Error(_(421))),Jl(e,t,i,r)}return l.data==="$?"?(t.flags|=128,t.child=e.child,t=yg.bind(null,e),l._reactRetry=t,null):(e=a.treeContext,qe=un(l.nextSibling),et=t,se=!0,mt=null,e!==null&&(lt[at++]=Lt,lt[at++]=Dt,lt[at++]=On,Lt=e.id,Dt=e.overflow,On=t),t=Lu(t,r.children),t.flags|=4096,t)}function lc(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Mo(e.return,t,n)}function Ai(e,t,n,r,l){var a=e.memoizedState;a===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=n,a.tailMode=l)}function $f(e,t,n){var r=t.pendingProps,l=r.revealOrder,a=r.tail;if($e(e,t,r.children,n),r=de.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&lc(e,n,t);else if(e.tag===19)lc(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(le(de,r),!(t.mode&1))t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;n!==null;)e=n.alternate,e!==null&&Oa(e)===null&&(l=n),n=n.sibling;n=l,n===null?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),Ai(t,!1,l,n,a);break;case"backwards":for(n=null,l=t.child,t.child=null;l!==null;){if(e=l.alternate,e!==null&&Oa(e)===null){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}Ai(t,!0,n,null,a);break;case"together":Ai(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function fa(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Bt(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Fn|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(_(153));if(t.child!==null){for(e=t.child,n=fn(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=fn(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function ag(e,t,n){switch(t.tag){case 3:Bf(t),gr();break;case 5:hf(t);break;case 1:Ke(t.type)&&_a(t);break;case 4:Cu(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,l=t.memoizedProps.value;le(Ta,r._currentValue),r._currentValue=l;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(le(de,de.current&1),t.flags|=128,null):n&t.child.childLanes?Wf(e,t,n):(le(de,de.current&1),e=Bt(e,t,n),e!==null?e.sibling:null);le(de,de.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return $f(e,t,n);t.flags|=128}if(l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),le(de,de.current),r)break;return null;case 22:case 23:return t.lanes=0,If(e,t,n)}return Bt(e,t,n)}var Af,zo,Hf,Vf;Af=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};zo=function(){};Hf=function(e,t,n,r){var l=e.memoizedProps;if(l!==r){e=t.stateNode,jn(Pt.current);var a=null;switch(n){case"input":l=no(e,l),r=no(e,r),a=[];break;case"select":l=he({},l,{value:void 0}),r=he({},r,{value:void 0}),a=[];break;case"textarea":l=ao(e,l),r=ao(e,r),a=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Na)}oo(n,r);var i;n=null;for(s in l)if(!r.hasOwnProperty(s)&&l.hasOwnProperty(s)&&l[s]!=null)if(s==="style"){var o=l[s];for(i in o)o.hasOwnProperty(i)&&(n||(n={}),n[i]="")}else s!=="dangerouslySetInnerHTML"&&s!=="children"&&s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(rl.hasOwnProperty(s)?a||(a=[]):(a=a||[]).push(s,null));for(s in r){var u=r[s];if(o=l!=null?l[s]:void 0,r.hasOwnProperty(s)&&u!==o&&(u!=null||o!=null))if(s==="style")if(o){for(i in o)!o.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(n||(n={}),n[i]="");for(i in u)u.hasOwnProperty(i)&&o[i]!==u[i]&&(n||(n={}),n[i]=u[i])}else n||(a||(a=[]),a.push(s,n)),n=u;else s==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,o=o?o.__html:void 0,u!=null&&o!==u&&(a=a||[]).push(s,u)):s==="children"?typeof u!="string"&&typeof u!="number"||(a=a||[]).push(s,""+u):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&(rl.hasOwnProperty(s)?(u!=null&&s==="onScroll"&&ie("scroll",e),a||o===u||(a=[])):(a=a||[]).push(s,u))}n&&(a=a||[]).push("style",n);var s=a;(t.updateQueue=s)&&(t.flags|=4)}};Vf=function(e,t,n,r){n!==r&&(t.flags|=4)};function Fr(e,t){if(!se)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Fe(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function ig(e,t,n){var r=t.pendingProps;switch(yu(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Fe(t),null;case 1:return Ke(t.type)&&Ma(),Fe(t),null;case 3:return r=t.stateNode,vr(),oe(Xe),oe(Ue),Nu(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(Kl(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,mt!==null&&(Ho(mt),mt=null))),zo(e,t),Fe(t),null;case 5:Pu(t);var l=jn(ml.current);if(n=t.type,e!==null&&t.stateNode!=null)Hf(e,t,n,r,l),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(_(166));return Fe(t),null}if(e=jn(Pt.current),Kl(t)){r=t.stateNode,n=t.type;var a=t.memoizedProps;switch(r[Et]=t,r[hl]=a,e=(t.mode&1)!==0,n){case"dialog":ie("cancel",r),ie("close",r);break;case"iframe":case"object":case"embed":ie("load",r);break;case"video":case"audio":for(l=0;l<Qr.length;l++)ie(Qr[l],r);break;case"source":ie("error",r);break;case"img":case"image":case"link":ie("error",r),ie("load",r);break;case"details":ie("toggle",r);break;case"input":hs(r,a),ie("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!a.multiple},ie("invalid",r);break;case"textarea":ms(r,a),ie("invalid",r)}oo(n,a),l=null;for(var i in a)if(a.hasOwnProperty(i)){var o=a[i];i==="children"?typeof o=="string"?r.textContent!==o&&(a.suppressHydrationWarning!==!0&&Xl(r.textContent,o,e),l=["children",o]):typeof o=="number"&&r.textContent!==""+o&&(a.suppressHydrationWarning!==!0&&Xl(r.textContent,o,e),l=["children",""+o]):rl.hasOwnProperty(i)&&o!=null&&i==="onScroll"&&ie("scroll",r)}switch(n){case"input":Wl(r),ps(r,a,!0);break;case"textarea":Wl(r),gs(r);break;case"select":case"option":break;default:typeof a.onClick=="function"&&(r.onclick=Na)}r=l,t.updateQueue=r,r!==null&&(t.flags|=4)}else{i=l.nodeType===9?l:l.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=yd(n)),e==="http://www.w3.org/1999/xhtml"?n==="script"?(e=i.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Et]=t,e[hl]=r,Af(e,t,!1,!1),t.stateNode=e;e:{switch(i=uo(n,r),n){case"dialog":ie("cancel",e),ie("close",e),l=r;break;case"iframe":case"object":case"embed":ie("load",e),l=r;break;case"video":case"audio":for(l=0;l<Qr.length;l++)ie(Qr[l],e);l=r;break;case"source":ie("error",e),l=r;break;case"img":case"image":case"link":ie("error",e),ie("load",e),l=r;break;case"details":ie("toggle",e),l=r;break;case"input":hs(e,r),l=no(e,r),ie("invalid",e);break;case"option":l=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},l=he({},r,{value:void 0}),ie("invalid",e);break;case"textarea":ms(e,r),l=ao(e,r),ie("invalid",e);break;default:l=r}oo(n,l),o=l;for(a in o)if(o.hasOwnProperty(a)){var u=o[a];a==="style"?xd(e,u):a==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,u!=null&&vd(e,u)):a==="children"?typeof u=="string"?(n!=="textarea"||u!=="")&&ll(e,u):typeof u=="number"&&ll(e,""+u):a!=="suppressContentEditableWarning"&&a!=="suppressHydrationWarning"&&a!=="autoFocus"&&(rl.hasOwnProperty(a)?u!=null&&a==="onScroll"&&ie("scroll",e):u!=null&&nu(e,a,u,i))}switch(n){case"input":Wl(e),ps(e,r,!1);break;case"textarea":Wl(e),gs(e);break;case"option":r.value!=null&&e.setAttribute("value",""+hn(r.value));break;case"select":e.multiple=!!r.multiple,a=r.value,a!=null?ur(e,!!r.multiple,a,!1):r.defaultValue!=null&&ur(e,!!r.multiple,r.defaultValue,!0);break;default:typeof l.onClick=="function"&&(e.onclick=Na)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return Fe(t),null;case 6:if(e&&t.stateNode!=null)Vf(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(_(166));if(n=jn(ml.current),jn(Pt.current),Kl(t)){if(r=t.stateNode,n=t.memoizedProps,r[Et]=t,(a=r.nodeValue!==n)&&(e=et,e!==null))switch(e.tag){case 3:Xl(r.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Xl(r.nodeValue,n,(e.mode&1)!==0)}a&&(t.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[Et]=t,t.stateNode=r}return Fe(t),null;case 13:if(oe(de),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(se&&qe!==null&&t.mode&1&&!(t.flags&128))uf(),gr(),t.flags|=98560,a=!1;else if(a=Kl(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(_(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(_(317));a[Et]=t}else gr(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fe(t),a=!1}else mt!==null&&(Ho(mt),mt=null),a=!0;if(!a)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,t.mode&1&&(e===null||de.current&1?Me===0&&(Me=3):Uu())),t.updateQueue!==null&&(t.flags|=4),Fe(t),null);case 4:return vr(),zo(e,t),e===null&&dl(t.stateNode.containerInfo),Fe(t),null;case 10:return ku(t.type._context),Fe(t),null;case 17:return Ke(t.type)&&Ma(),Fe(t),null;case 19:if(oe(de),a=t.memoizedState,a===null)return Fe(t),null;if(r=(t.flags&128)!==0,i=a.rendering,i===null)if(r)Fr(a,!1);else{if(Me!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(i=Oa(e),i!==null){for(t.flags|=128,Fr(a,!1),r=i.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;n!==null;)a=n,e=r,a.flags&=14680066,i=a.alternate,i===null?(a.childLanes=0,a.lanes=e,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=i.childLanes,a.lanes=i.lanes,a.child=i.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=i.memoizedProps,a.memoizedState=i.memoizedState,a.updateQueue=i.updateQueue,a.type=i.type,e=i.dependencies,a.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return le(de,de.current&1|2),t.child}e=e.sibling}a.tail!==null&&we()>xr&&(t.flags|=128,r=!0,Fr(a,!1),t.lanes=4194304)}else{if(!r)if(e=Oa(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Fr(a,!0),a.tail===null&&a.tailMode==="hidden"&&!i.alternate&&!se)return Fe(t),null}else 2*we()-a.renderingStartTime>xr&&n!==1073741824&&(t.flags|=128,r=!0,Fr(a,!1),t.lanes=4194304);a.isBackwards?(i.sibling=t.child,t.child=i):(n=a.last,n!==null?n.sibling=i:t.child=i,a.last=i)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=we(),t.sibling=null,n=de.current,le(de,r?n&1|2:n&1),t):(Fe(t),null);case 22:case 23:return Iu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Je&1073741824&&(Fe(t),t.subtreeFlags&6&&(t.flags|=8192)):Fe(t),null;case 24:return null;case 25:return null}throw Error(_(156,t.tag))}function og(e,t){switch(yu(t),t.tag){case 1:return Ke(t.type)&&Ma(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return vr(),oe(Xe),oe(Ue),Nu(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Pu(t),null;case 13:if(oe(de),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(_(340));gr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return oe(de),null;case 4:return vr(),null;case 10:return ku(t.type._context),null;case 22:case 23:return Iu(),null;case 24:return null;default:return null}}var Zl=!1,Ie=!1,ug=typeof WeakSet=="function"?WeakSet:Set,O=null;function ir(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(e,t,r)}else n.current=null}function Fo(e,t,n){try{n()}catch(r){ye(e,t,r)}}var ac=!1;function sg(e,t){if(wo=Ea,e=Xd(),mu(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,a=r.focusNode;r=r.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break e}var i=0,o=-1,u=-1,s=0,c=0,f=e,h=null;t:for(;;){for(var k;f!==n||l!==0&&f.nodeType!==3||(o=i+l),f!==a||r!==0&&f.nodeType!==3||(u=i+r),f.nodeType===3&&(i+=f.nodeValue.length),(k=f.firstChild)!==null;)h=f,f=k;for(;;){if(f===e)break t;if(h===n&&++s===l&&(o=i),h===a&&++c===r&&(u=i),(k=f.nextSibling)!==null)break;f=h,h=f.parentNode}f=k}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(xo={focusedElem:e,selectionRange:n},Ea=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var S=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var v=S.memoizedProps,P=S.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?v:ft(t.type,v),P);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(_(163))}}catch(C){ye(t,t.return,C)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return S=ac,ac=!1,S}function el(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var a=l.destroy;l.destroy=void 0,a!==void 0&&Fo(t,n,a)}l=l.next}while(l!==r)}}function ni(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Io(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Yf(e){var t=e.alternate;t!==null&&(e.alternate=null,Yf(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Et],delete t[hl],delete t[Eo],delete t[Ym],delete t[Qm])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Qf(e){return e.tag===5||e.tag===3||e.tag===4}function ic(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Qf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Uo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Na));else if(r!==4&&(e=e.child,e!==null))for(Uo(e,t,n),e=e.sibling;e!==null;)Uo(e,t,n),e=e.sibling}function Bo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Bo(e,t,n),e=e.sibling;e!==null;)Bo(e,t,n),e=e.sibling}var Le=null,ht=!1;function bt(e,t,n){for(n=n.child;n!==null;)bf(e,t,n),n=n.sibling}function bf(e,t,n){if(Ct&&typeof Ct.onCommitFiberUnmount=="function")try{Ct.onCommitFiberUnmount(Xa,n)}catch{}switch(n.tag){case 5:Ie||ir(n,t);case 6:var r=Le,l=ht;Le=null,bt(e,t,n),Le=r,ht=l,Le!==null&&(ht?(e=Le,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Le.removeChild(n.stateNode));break;case 18:Le!==null&&(ht?(e=Le,n=n.stateNode,e.nodeType===8?zi(e.parentNode,n):e.nodeType===1&&zi(e,n),ul(e)):zi(Le,n.stateNode));break;case 4:r=Le,l=ht,Le=n.stateNode.containerInfo,ht=!0,bt(e,t,n),Le=r,ht=l;break;case 0:case 11:case 14:case 15:if(!Ie&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var a=l,i=a.destroy;a=a.tag,i!==void 0&&(a&2||a&4)&&Fo(n,t,i),l=l.next}while(l!==r)}bt(e,t,n);break;case 1:if(!Ie&&(ir(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ye(n,t,o)}bt(e,t,n);break;case 21:bt(e,t,n);break;case 22:n.mode&1?(Ie=(r=Ie)||n.memoizedState!==null,bt(e,t,n),Ie=r):bt(e,t,n);break;default:bt(e,t,n)}}function oc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new ug),t.forEach(function(r){var l=vg.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;r<n.length;r++){var l=n[r];try{var a=e,i=t,o=i;e:for(;o!==null;){switch(o.tag){case 5:Le=o.stateNode,ht=!1;break e;case 3:Le=o.stateNode.containerInfo,ht=!0;break e;case 4:Le=o.stateNode.containerInfo,ht=!0;break e}o=o.return}if(Le===null)throw Error(_(160));bf(a,i,l),Le=null,ht=!1;var u=l.alternate;u!==null&&(u.return=null),l.return=null}catch(s){ye(l,t,s)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)Xf(t,e),t=t.sibling}function Xf(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(dt(t,e),kt(e),r&4){try{el(3,e,e.return),ni(3,e)}catch(v){ye(e,e.return,v)}try{el(5,e,e.return)}catch(v){ye(e,e.return,v)}}break;case 1:dt(t,e),kt(e),r&512&&n!==null&&ir(n,n.return);break;case 5:if(dt(t,e),kt(e),r&512&&n!==null&&ir(n,n.return),e.flags&32){var l=e.stateNode;try{ll(l,"")}catch(v){ye(e,e.return,v)}}if(r&4&&(l=e.stateNode,l!=null)){var a=e.memoizedProps,i=n!==null?n.memoizedProps:a,o=e.type,u=e.updateQueue;if(e.updateQueue=null,u!==null)try{o==="input"&&a.type==="radio"&&a.name!=null&&md(l,a),uo(o,i);var s=uo(o,a);for(i=0;i<u.length;i+=2){var c=u[i],f=u[i+1];c==="style"?xd(l,f):c==="dangerouslySetInnerHTML"?vd(l,f):c==="children"?ll(l,f):nu(l,c,f,s)}switch(o){case"input":ro(l,a);break;case"textarea":gd(l,a);break;case"select":var h=l._wrapperState.wasMultiple;l._wrapperState.wasMultiple=!!a.multiple;var k=a.value;k!=null?ur(l,!!a.multiple,k,!1):h!==!!a.multiple&&(a.defaultValue!=null?ur(l,!!a.multiple,a.defaultValue,!0):ur(l,!!a.multiple,a.multiple?[]:"",!1))}l[hl]=a}catch(v){ye(e,e.return,v)}}break;case 6:if(dt(t,e),kt(e),r&4){if(e.stateNode===null)throw Error(_(162));l=e.stateNode,a=e.memoizedProps;try{l.nodeValue=a}catch(v){ye(e,e.return,v)}}break;case 3:if(dt(t,e),kt(e),r&4&&n!==null&&n.memoizedState.isDehydrated)try{ul(t.containerInfo)}catch(v){ye(e,e.return,v)}break;case 4:dt(t,e),kt(e);break;case 13:dt(t,e),kt(e),l=e.child,l.flags&8192&&(a=l.memoizedState!==null,l.stateNode.isHidden=a,!a||l.alternate!==null&&l.alternate.memoizedState!==null||(zu=we())),r&4&&oc(e);break;case 22:if(c=n!==null&&n.memoizedState!==null,e.mode&1?(Ie=(s=Ie)||c,dt(t,e),Ie=s):dt(t,e),kt(e),r&8192){if(s=e.memoizedState!==null,(e.stateNode.isHidden=s)&&!c&&e.mode&1)for(O=e,c=e.child;c!==null;){for(f=O=c;O!==null;){switch(h=O,k=h.child,h.tag){case 0:case 11:case 14:case 15:el(4,h,h.return);break;case 1:ir(h,h.return);var S=h.stateNode;if(typeof S.componentWillUnmount=="function"){r=h,n=h.return;try{t=r,S.props=t.memoizedProps,S.state=t.memoizedState,S.componentWillUnmount()}catch(v){ye(r,n,v)}}break;case 5:ir(h,h.return);break;case 22:if(h.memoizedState!==null){sc(f);continue}}k!==null?(k.return=h,O=k):sc(f)}c=c.sibling}e:for(c=null,f=e;;){if(f.tag===5){if(c===null){c=f;try{l=f.stateNode,s?(a=l.style,typeof a.setProperty=="function"?a.setProperty("display","none","important"):a.display="none"):(o=f.stateNode,u=f.memoizedProps.style,i=u!=null&&u.hasOwnProperty("display")?u.display:null,o.style.display=wd("display",i))}catch(v){ye(e,e.return,v)}}}else if(f.tag===6){if(c===null)try{f.stateNode.nodeValue=s?"":f.memoizedProps}catch(v){ye(e,e.return,v)}}else if((f.tag!==22&&f.tag!==23||f.memoizedState===null||f===e)&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===e)break e;for(;f.sibling===null;){if(f.return===null||f.return===e)break e;c===f&&(c=null),f=f.return}c===f&&(c=null),f.sibling.return=f.return,f=f.sibling}}break;case 19:dt(t,e),kt(e),r&4&&oc(e);break;case 21:break;default:dt(t,e),kt(e)}}function kt(e){var t=e.flags;if(t&2){try{e:{for(var n=e.return;n!==null;){if(Qf(n)){var r=n;break e}n=n.return}throw Error(_(160))}switch(r.tag){case 5:var l=r.stateNode;r.flags&32&&(ll(l,""),r.flags&=-33);var a=ic(e);Bo(e,a,l);break;case 3:case 4:var i=r.stateNode.containerInfo,o=ic(e);Uo(e,o,i);break;default:throw Error(_(161))}}catch(u){ye(e,e.return,u)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function cg(e,t,n){O=e,Kf(e)}function Kf(e,t,n){for(var r=(e.mode&1)!==0;O!==null;){var l=O,a=l.child;if(l.tag===22&&r){var i=l.memoizedState!==null||Zl;if(!i){var o=l.alternate,u=o!==null&&o.memoizedState!==null||Ie;o=Zl;var s=Ie;if(Zl=i,(Ie=u)&&!s)for(O=l;O!==null;)i=O,u=i.child,i.tag===22&&i.memoizedState!==null?cc(l):u!==null?(u.return=i,O=u):cc(l);for(;a!==null;)O=a,Kf(a),a=a.sibling;O=l,Zl=o,Ie=s}uc(e)}else l.subtreeFlags&8772&&a!==null?(a.return=l,O=a):uc(e)}}function uc(e){for(;O!==null;){var t=O;if(t.flags&8772){var n=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:Ie||ni(5,t);break;case 1:var r=t.stateNode;if(t.flags&4&&!Ie)if(n===null)r.componentDidMount();else{var l=t.elementType===t.type?n.memoizedProps:ft(t.type,n.memoizedProps);r.componentDidUpdate(l,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var a=t.updateQueue;a!==null&&Qs(t,a,r);break;case 3:var i=t.updateQueue;if(i!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}Qs(t,i,n)}break;case 5:var o=t.stateNode;if(n===null&&t.flags&4){n=o;var u=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":u.autoFocus&&n.focus();break;case"img":u.src&&(n.src=u.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var s=t.alternate;if(s!==null){var c=s.memoizedState;if(c!==null){var f=c.dehydrated;f!==null&&ul(f)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(_(163))}Ie||t.flags&512&&Io(t)}catch(h){ye(t,t.return,h)}}if(t===e){O=null;break}if(n=t.sibling,n!==null){n.return=t.return,O=n;break}O=t.return}}function sc(e){for(;O!==null;){var t=O;if(t===e){O=null;break}var n=t.sibling;if(n!==null){n.return=t.return,O=n;break}O=t.return}}function cc(e){for(;O!==null;){var t=O;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{ni(4,t)}catch(u){ye(t,n,u)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount=="function"){var l=t.return;try{r.componentDidMount()}catch(u){ye(t,l,u)}}var a=t.return;try{Io(t)}catch(u){ye(t,a,u)}break;case 5:var i=t.return;try{Io(t)}catch(u){ye(t,i,u)}}}catch(u){ye(t,t.return,u)}if(t===e){O=null;break}var o=t.sibling;if(o!==null){o.return=t.return,O=o;break}O=t.return}}var dg=Math.ceil,Ia=$t.ReactCurrentDispatcher,Du=$t.ReactCurrentOwner,ot=$t.ReactCurrentBatchConfig,K=0,je=null,Ee=null,De=0,Je=0,or=gn(0),Me=0,wl=null,Fn=0,ri=0,Ou=0,tl=null,Qe=null,zu=0,xr=1/0,Rt=null,Ua=!1,Wo=null,cn=null,ql=!1,tn=null,Ba=0,nl=0,$o=null,ha=-1,pa=0;function Ae(){return K&6?we():ha!==-1?ha:ha=we()}function dn(e){return e.mode&1?K&2&&De!==0?De&-De:Xm.transition!==null?(pa===0&&(pa=Ld()),pa):(e=ee,e!==0||(e=window.event,e=e===void 0?16:Bd(e.type)),e):1}function yt(e,t,n,r){if(50<nl)throw nl=0,$o=null,Error(_(185));Pl(e,n,r),(!(K&2)||e!==je)&&(e===je&&(!(K&2)&&(ri|=n),Me===4&&qt(e,De)),Ge(e,r),n===1&&K===0&&!(t.mode&1)&&(xr=we()+500,qa&&yn()))}function Ge(e,t){var n=e.callbackNode;Xp(e,t);var r=Sa(e,e===je?De:0);if(r===0)n!==null&&ws(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(n!=null&&ws(n),t===1)e.tag===0?bm(dc.bind(null,e)):lf(dc.bind(null,e)),Hm(function(){!(K&6)&&yn()}),n=null;else{switch(Dd(r)){case 1:n=ou;break;case 4:n=Rd;break;case 16:n=ka;break;case 536870912:n=Td;break;default:n=ka}n=rh(n,Gf.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function Gf(e,t){if(ha=-1,pa=0,K&6)throw Error(_(327));var n=e.callbackNode;if(hr()&&e.callbackNode!==n)return null;var r=Sa(e,e===je?De:0);if(r===0)return null;if(r&30||r&e.expiredLanes||t)t=Wa(e,r);else{t=r;var l=K;K|=2;var a=Zf();(je!==e||De!==t)&&(Rt=null,xr=we()+500,Tn(e,t));do try{pg();break}catch(o){Jf(e,o)}while(!0);xu(),Ia.current=a,K=l,Ee!==null?t=0:(je=null,De=0,t=Me)}if(t!==0){if(t===2&&(l=po(e),l!==0&&(r=l,t=Ao(e,l))),t===1)throw n=wl,Tn(e,0),qt(e,r),Ge(e,we()),n;if(t===6)qt(e,r);else{if(l=e.current.alternate,!(r&30)&&!fg(l)&&(t=Wa(e,r),t===2&&(a=po(e),a!==0&&(r=a,t=Ao(e,a))),t===1))throw n=wl,Tn(e,0),qt(e,r),Ge(e,we()),n;switch(e.finishedWork=l,e.finishedLanes=r,t){case 0:case 1:throw Error(_(345));case 2:En(e,Qe,Rt);break;case 3:if(qt(e,r),(r&130023424)===r&&(t=zu+500-we(),10<t)){if(Sa(e,0)!==0)break;if(l=e.suspendedLanes,(l&r)!==r){Ae(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=So(En.bind(null,e,Qe,Rt),t);break}En(e,Qe,Rt);break;case 4:if(qt(e,r),(r&4194240)===r)break;for(t=e.eventTimes,l=-1;0<r;){var i=31-gt(r);a=1<<i,i=t[i],i>l&&(l=i),r&=~a}if(r=l,r=we()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*dg(r/1960))-r,10<r){e.timeoutHandle=So(En.bind(null,e,Qe,Rt),r);break}En(e,Qe,Rt);break;case 5:En(e,Qe,Rt);break;default:throw Error(_(329))}}}return Ge(e,we()),e.callbackNode===n?Gf.bind(null,e):null}function Ao(e,t){var n=tl;return e.current.memoizedState.isDehydrated&&(Tn(e,t).flags|=256),e=Wa(e,t),e!==2&&(t=Qe,Qe=n,t!==null&&Ho(t)),e}function Ho(e){Qe===null?Qe=e:Qe.push.apply(Qe,e)}function fg(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var l=n[r],a=l.getSnapshot;l=l.value;try{if(!vt(a(),l))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function qt(e,t){for(t&=~Ou,t&=~ri,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-gt(t),r=1<<n;e[n]=-1,t&=~r}}function dc(e){if(K&6)throw Error(_(327));hr();var t=Sa(e,0);if(!(t&1))return Ge(e,we()),null;var n=Wa(e,t);if(e.tag!==0&&n===2){var r=po(e);r!==0&&(t=r,n=Ao(e,r))}if(n===1)throw n=wl,Tn(e,0),qt(e,t),Ge(e,we()),n;if(n===6)throw Error(_(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,En(e,Qe,Rt),Ge(e,we()),null}function Fu(e,t){var n=K;K|=1;try{return e(t)}finally{K=n,K===0&&(xr=we()+500,qa&&yn())}}function In(e){tn!==null&&tn.tag===0&&!(K&6)&&hr();var t=K;K|=1;var n=ot.transition,r=ee;try{if(ot.transition=null,ee=1,e)return e()}finally{ee=r,ot.transition=n,K=t,!(K&6)&&yn()}}function Iu(){Je=or.current,oe(or)}function Tn(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,Am(n)),Ee!==null)for(n=Ee.return;n!==null;){var r=n;switch(yu(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&Ma();break;case 3:vr(),oe(Xe),oe(Ue),Nu();break;case 5:Pu(r);break;case 4:vr();break;case 13:oe(de);break;case 19:oe(de);break;case 10:ku(r.type._context);break;case 22:case 23:Iu()}n=n.return}if(je=e,Ee=e=fn(e.current,null),De=Je=t,Me=0,wl=null,Ou=ri=Fn=0,Qe=tl=null,_n!==null){for(t=0;t<_n.length;t++)if(n=_n[t],r=n.interleaved,r!==null){n.interleaved=null;var l=r.next,a=n.pending;if(a!==null){var i=a.next;a.next=l,r.next=i}n.pending=r}_n=null}return e}function Jf(e,t){do{var n=Ee;try{if(xu(),ca.current=Fa,za){for(var r=fe.memoizedState;r!==null;){var l=r.queue;l!==null&&(l.pending=null),r=r.next}za=!1}if(zn=0,_e=Pe=fe=null,qr=!1,gl=0,Du.current=null,n===null||n.return===null){Me=1,wl=t,Ee=null;break}e:{var a=e,i=n.return,o=n,u=t;if(t=De,o.flags|=32768,u!==null&&typeof u=="object"&&typeof u.then=="function"){var s=u,c=o,f=c.tag;if(!(c.mode&1)&&(f===0||f===11||f===15)){var h=c.alternate;h?(c.updateQueue=h.updateQueue,c.memoizedState=h.memoizedState,c.lanes=h.lanes):(c.updateQueue=null,c.memoizedState=null)}var k=Zs(i);if(k!==null){k.flags&=-257,qs(k,i,o,a,t),k.mode&1&&Js(a,s,t),t=k,u=s;var S=t.updateQueue;if(S===null){var v=new Set;v.add(u),t.updateQueue=v}else S.add(u);break e}else{if(!(t&1)){Js(a,s,t),Uu();break e}u=Error(_(426))}}else if(se&&o.mode&1){var P=Zs(i);if(P!==null){!(P.flags&65536)&&(P.flags|=256),qs(P,i,o,a,t),vu(wr(u,o));break e}}a=u=wr(u,o),Me!==4&&(Me=2),tl===null?tl=[a]:tl.push(a),a=i;do{switch(a.tag){case 3:a.flags|=65536,t&=-t,a.lanes|=t;var p=Of(a,u,t);Ys(a,p);break e;case 1:o=u;var d=a.type,y=a.stateNode;if(!(a.flags&128)&&(typeof d.getDerivedStateFromError=="function"||y!==null&&typeof y.componentDidCatch=="function"&&(cn===null||!cn.has(y)))){a.flags|=65536,t&=-t,a.lanes|=t;var C=zf(a,o,t);Ys(a,C);break e}}a=a.return}while(a!==null)}eh(n)}catch(R){t=R,Ee===n&&n!==null&&(Ee=n=n.return);continue}break}while(!0)}function Zf(){var e=Ia.current;return Ia.current=Fa,e===null?Fa:e}function Uu(){(Me===0||Me===3||Me===2)&&(Me=4),je===null||!(Fn&268435455)&&!(ri&268435455)||qt(je,De)}function Wa(e,t){var n=K;K|=2;var r=Zf();(je!==e||De!==t)&&(Rt=null,Tn(e,t));do try{hg();break}catch(l){Jf(e,l)}while(!0);if(xu(),K=n,Ia.current=r,Ee!==null)throw Error(_(261));return je=null,De=0,Me}function hg(){for(;Ee!==null;)qf(Ee)}function pg(){for(;Ee!==null&&!Bp();)qf(Ee)}function qf(e){var t=nh(e.alternate,e,Je);e.memoizedProps=e.pendingProps,t===null?eh(e):Ee=t,Du.current=null}function eh(e){var t=e;do{var n=t.alternate;if(e=t.return,t.flags&32768){if(n=og(n,t),n!==null){n.flags&=32767,Ee=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Me=6,Ee=null;return}}else if(n=ig(n,t,Je),n!==null){Ee=n;return}if(t=t.sibling,t!==null){Ee=t;return}Ee=t=e}while(t!==null);Me===0&&(Me=5)}function En(e,t,n){var r=ee,l=ot.transition;try{ot.transition=null,ee=1,mg(e,t,n,r)}finally{ot.transition=l,ee=r}return null}function mg(e,t,n,r){do hr();while(tn!==null);if(K&6)throw Error(_(327));n=e.finishedWork;var l=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(_(177));e.callbackNode=null,e.callbackPriority=0;var a=n.lanes|n.childLanes;if(Kp(e,a),e===je&&(Ee=je=null,De=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||ql||(ql=!0,rh(ka,function(){return hr(),null})),a=(n.flags&15990)!==0,n.subtreeFlags&15990||a){a=ot.transition,ot.transition=null;var i=ee;ee=1;var o=K;K|=4,Du.current=null,sg(e,n),Xf(n,e),zm(xo),Ea=!!wo,xo=wo=null,e.current=n,cg(n),Wp(),K=o,ee=i,ot.transition=a}else e.current=n;if(ql&&(ql=!1,tn=e,Ba=l),a=e.pendingLanes,a===0&&(cn=null),Hp(n.stateNode),Ge(e,we()),t!==null)for(r=e.onRecoverableError,n=0;n<t.length;n++)l=t[n],r(l.value,{componentStack:l.stack,digest:l.digest});if(Ua)throw Ua=!1,e=Wo,Wo=null,e;return Ba&1&&e.tag!==0&&hr(),a=e.pendingLanes,a&1?e===$o?nl++:(nl=0,$o=e):nl=0,yn(),null}function hr(){if(tn!==null){var e=Dd(Ba),t=ot.transition,n=ee;try{if(ot.transition=null,ee=16>e?16:e,tn===null)var r=!1;else{if(e=tn,tn=null,Ba=0,K&6)throw Error(_(331));var l=K;for(K|=4,O=e.current;O!==null;){var a=O,i=a.child;if(O.flags&16){var o=a.deletions;if(o!==null){for(var u=0;u<o.length;u++){var s=o[u];for(O=s;O!==null;){var c=O;switch(c.tag){case 0:case 11:case 15:el(8,c,a)}var f=c.child;if(f!==null)f.return=c,O=f;else for(;O!==null;){c=O;var h=c.sibling,k=c.return;if(Yf(c),c===s){O=null;break}if(h!==null){h.return=k,O=h;break}O=k}}}var S=a.alternate;if(S!==null){var v=S.child;if(v!==null){S.child=null;do{var P=v.sibling;v.sibling=null,v=P}while(v!==null)}}O=a}}if(a.subtreeFlags&2064&&i!==null)i.return=a,O=i;else e:for(;O!==null;){if(a=O,a.flags&2048)switch(a.tag){case 0:case 11:case 15:el(9,a,a.return)}var p=a.sibling;if(p!==null){p.return=a.return,O=p;break e}O=a.return}}var d=e.current;for(O=d;O!==null;){i=O;var y=i.child;if(i.subtreeFlags&2064&&y!==null)y.return=i,O=y;else e:for(i=d;O!==null;){if(o=O,o.flags&2048)try{switch(o.tag){case 0:case 11:case 15:ni(9,o)}}catch(R){ye(o,o.return,R)}if(o===i){O=null;break e}var C=o.sibling;if(C!==null){C.return=o.return,O=C;break e}O=o.return}}if(K=l,yn(),Ct&&typeof Ct.onPostCommitFiberRoot=="function")try{Ct.onPostCommitFiberRoot(Xa,e)}catch{}r=!0}return r}finally{ee=n,ot.transition=t}}return!1}function fc(e,t,n){t=wr(n,t),t=Of(e,t,1),e=sn(e,t,1),t=Ae(),e!==null&&(Pl(e,1,t),Ge(e,t))}function ye(e,t,n){if(e.tag===3)fc(e,e,n);else for(;t!==null;){if(t.tag===3){fc(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(cn===null||!cn.has(r))){e=wr(n,e),e=zf(t,e,1),t=sn(t,e,1),e=Ae(),t!==null&&(Pl(t,1,e),Ge(t,e));break}}t=t.return}}function gg(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),t=Ae(),e.pingedLanes|=e.suspendedLanes&n,je===e&&(De&n)===n&&(Me===4||Me===3&&(De&130023424)===De&&500>we()-zu?Tn(e,0):Ou|=n),Ge(e,t)}function th(e,t){t===0&&(e.mode&1?(t=Hl,Hl<<=1,!(Hl&130023424)&&(Hl=4194304)):t=1);var n=Ae();e=Ut(e,t),e!==null&&(Pl(e,t,n),Ge(e,n))}function yg(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),th(e,n)}function vg(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(_(314))}r!==null&&r.delete(t),th(e,n)}var nh;nh=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Xe.current)be=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return be=!1,ag(e,t,n);be=!!(e.flags&131072)}else be=!1,se&&t.flags&1048576&&af(t,Ra,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;fa(e,t),e=t.pendingProps;var l=mr(t,Ue.current);fr(t,n),l=_u(null,t,r,e,l,n);var a=ju();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ke(r)?(a=!0,_a(t)):a=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Eu(t),l.updater=ti,t.stateNode=l,l._reactInternals=t,jo(t,r,e,n),t=Lo(null,t,r,!0,a,n)):(t.tag=0,se&&a&&gu(t),$e(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(fa(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=xg(r),e=ft(r,e),l){case 0:t=To(null,t,r,e,n);break e;case 1:t=nc(null,t,r,e,n);break e;case 11:t=ec(null,t,r,e,n);break e;case 14:t=tc(null,t,r,ft(r.type,e),n);break e}throw Error(_(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ft(r,l),To(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ft(r,l),nc(e,t,r,l,n);case 3:e:{if(Bf(t),e===null)throw Error(_(387));r=t.pendingProps,a=t.memoizedState,l=a.element,ff(e,t),Da(t,r,null,n);var i=t.memoizedState;if(r=i.element,a.isDehydrated)if(a={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){l=wr(Error(_(423)),t),t=rc(e,t,r,n,l);break e}else if(r!==l){l=wr(Error(_(424)),t),t=rc(e,t,r,n,l);break e}else for(qe=un(t.stateNode.containerInfo.firstChild),et=t,se=!0,mt=null,n=cf(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(gr(),r===l){t=Bt(e,t,n);break e}$e(e,t,r,n)}t=t.child}return t;case 5:return hf(t),e===null&&No(t),r=t.type,l=t.pendingProps,a=e!==null?e.memoizedProps:null,i=l.children,ko(r,l)?i=null:a!==null&&ko(r,a)&&(t.flags|=32),Uf(e,t),$e(e,t,i,n),t.child;case 6:return e===null&&No(t),null;case 13:return Wf(e,t,n);case 4:return Cu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=yr(t,null,r,n):$e(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ft(r,l),ec(e,t,r,l,n);case 7:return $e(e,t,t.pendingProps,n),t.child;case 8:return $e(e,t,t.pendingProps.children,n),t.child;case 12:return $e(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,a=t.memoizedProps,i=l.value,le(Ta,r._currentValue),r._currentValue=i,a!==null)if(vt(a.value,i)){if(a.children===l.children&&!Xe.current){t=Bt(e,t,n);break e}}else for(a=t.child,a!==null&&(a.return=t);a!==null;){var o=a.dependencies;if(o!==null){i=a.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(a.tag===1){u=Ot(-1,n&-n),u.tag=2;var s=a.updateQueue;if(s!==null){s=s.shared;var c=s.pending;c===null?u.next=u:(u.next=c.next,c.next=u),s.pending=u}}a.lanes|=n,u=a.alternate,u!==null&&(u.lanes|=n),Mo(a.return,n,t),o.lanes|=n;break}u=u.next}}else if(a.tag===10)i=a.type===t.type?null:a.child;else if(a.tag===18){if(i=a.return,i===null)throw Error(_(341));i.lanes|=n,o=i.alternate,o!==null&&(o.lanes|=n),Mo(i,n,t),i=a.sibling}else i=a.child;if(i!==null)i.return=a;else for(i=a;i!==null;){if(i===t){i=null;break}if(a=i.sibling,a!==null){a.return=i.return,i=a;break}i=i.return}a=i}$e(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,fr(t,n),l=ut(l),r=r(l),t.flags|=1,$e(e,t,r,n),t.child;case 14:return r=t.type,l=ft(r,t.pendingProps),l=ft(r.type,l),tc(e,t,r,l,n);case 15:return Ff(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ft(r,l),fa(e,t),t.tag=1,Ke(r)?(e=!0,_a(t)):e=!1,fr(t,n),Df(t,r,l),jo(t,r,l,n),Lo(null,t,r,!0,e,n);case 19:return $f(e,t,n);case 22:return If(e,t,n)}throw Error(_(156,t.tag))};function rh(e,t){return jd(e,t)}function wg(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function it(e,t,n,r){return new wg(e,t,n,r)}function Bu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function xg(e){if(typeof e=="function")return Bu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lu)return 11;if(e===au)return 14}return 2}function fn(e,t){var n=e.alternate;return n===null?(n=it(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function ma(e,t,n,r,l,a){var i=2;if(r=e,typeof e=="function")Bu(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Jn:return Ln(n.children,l,a,t);case ru:i=8,l|=8;break;case Zi:return e=it(12,n,t,l|2),e.elementType=Zi,e.lanes=a,e;case qi:return e=it(13,n,t,l),e.elementType=qi,e.lanes=a,e;case eo:return e=it(19,n,t,l),e.elementType=eo,e.lanes=a,e;case fd:return li(n,l,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case cd:i=10;break e;case dd:i=9;break e;case lu:i=11;break e;case au:i=14;break e;case Gt:i=16,r=null;break e}throw Error(_(130,e==null?e:typeof e,""))}return t=it(i,n,t,l),t.elementType=e,t.type=r,t.lanes=a,t}function Ln(e,t,n,r){return e=it(7,e,r,t),e.lanes=n,e}function li(e,t,n,r){return e=it(22,e,r,t),e.elementType=fd,e.lanes=n,e.stateNode={isHidden:!1},e}function Hi(e,t,n){return e=it(6,e,null,t),e.lanes=n,e}function Vi(e,t,n){return t=it(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function kg(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ci(0),this.expirationTimes=Ci(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ci(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Wu(e,t,n,r,l,a,i,o,u){return e=new kg(e,t,n,o,u),t===1?(t=1,a===!0&&(t|=8)):t=0,a=it(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Eu(a),e}function Sg(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Gn,key:r==null?null:""+r,children:e,containerInfo:t,implementation:n}}function lh(e){if(!e)return pn;e=e._reactInternals;e:{if(Wn(e)!==e||e.tag!==1)throw Error(_(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Ke(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(_(171))}if(e.tag===1){var n=e.type;if(Ke(n))return rf(e,n,t)}return t}function ah(e,t,n,r,l,a,i,o,u){return e=Wu(n,r,!0,e,l,a,i,o,u),e.context=lh(null),n=e.current,r=Ae(),l=dn(n),a=Ot(r,l),a.callback=t??null,sn(n,a,l),e.current.lanes=l,Pl(e,l,r),Ge(e,r),e}function ai(e,t,n,r){var l=t.current,a=Ae(),i=dn(l);return n=lh(n),t.context===null?t.context=n:t.pendingContext=n,t=Ot(a,i),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=sn(l,t,i),e!==null&&(yt(e,l,i,a),sa(e,l,i)),i}function $a(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function hc(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function $u(e,t){hc(e,t),(e=e.alternate)&&hc(e,t)}var ih=typeof reportError=="function"?reportError:function(e){console.error(e)};function Au(e){this._internalRoot=e}ii.prototype.render=Au.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(_(409));ai(e,t,null,null)};ii.prototype.unmount=Au.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;In(function(){ai(null,e,null,null)}),t[It]=null}};function ii(e){this._internalRoot=e}ii.prototype.unstable_scheduleHydration=function(e){if(e){var t=Fd();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Zt.length&&t!==0&&t<Zt[n].priority;n++);Zt.splice(n,0,e),n===0&&Ud(e)}};function Hu(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function oi(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function pc(){}function Eg(e,t,n,r,l){if(l){if(typeof r=="function"){var a=r;r=function(){var s=$a(i);a.call(s)}}var i=ah(t,r,e,0,null,!1,!1,"",pc);return e._reactRootContainer=i,e[It]=i.current,dl(e.nodeType===8?e.parentNode:e),In(),i}for(;l=e.lastChild;)e.removeChild(l);if(typeof r=="function"){var o=r;r=function(){var s=$a(u);o.call(s)}}var u=Wu(e,0,!1,null,null,!1,!1,"",pc);return e._reactRootContainer=u,e[It]=u.current,dl(e.nodeType===8?e.parentNode:e),In(function(){ai(t,u,n,r)}),u}function ui(e,t,n,r,l){var a=n._reactRootContainer;if(a){var i=a;if(typeof l=="function"){var o=l;l=function(){var u=$a(i);o.call(u)}}ai(t,i,e,l)}else i=Eg(n,t,e,l,r);return $a(i)}Od=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=Yr(t.pendingLanes);n!==0&&(uu(t,n|1),Ge(t,we()),!(K&6)&&(xr=we()+500,yn()))}break;case 13:In(function(){var r=Ut(e,1);if(r!==null){var l=Ae();yt(r,e,1,l)}}),$u(e,1)}};su=function(e){if(e.tag===13){var t=Ut(e,134217728);if(t!==null){var n=Ae();yt(t,e,134217728,n)}$u(e,134217728)}};zd=function(e){if(e.tag===13){var t=dn(e),n=Ut(e,t);if(n!==null){var r=Ae();yt(n,e,t,r)}$u(e,t)}};Fd=function(){return ee};Id=function(e,t){var n=ee;try{return ee=e,t()}finally{ee=n}};co=function(e,t,n){switch(t){case"input":if(ro(e,n),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=Za(r);if(!l)throw Error(_(90));pd(r),ro(r,l)}}}break;case"textarea":gd(e,n);break;case"select":t=n.value,t!=null&&ur(e,!!n.multiple,t,!1)}};Ed=Fu;Cd=In;var Cg={usingClientEntryPoint:!1,Events:[Ml,tr,Za,kd,Sd,Fu]},Ir={findFiberByHostInstance:Mn,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Pg={bundleType:Ir.bundleType,version:Ir.version,rendererPackageName:Ir.rendererPackageName,rendererConfig:Ir.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:$t.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=Md(e),e===null?null:e.stateNode},findFiberByHostInstance:Ir.findFiberByHostInstance,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var ea=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!ea.isDisabled&&ea.supportsFiber)try{Xa=ea.inject(Pg),Ct=ea}catch{}}nt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Cg;nt.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Hu(t))throw Error(_(200));return Sg(e,t,null,n)};nt.createRoot=function(e,t){if(!Hu(e))throw Error(_(299));var n=!1,r="",l=ih;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onRecoverableError!==void 0&&(l=t.onRecoverableError)),t=Wu(e,1,!1,null,null,n,!1,r,l),e[It]=t.current,dl(e.nodeType===8?e.parentNode:e),new Au(t)};nt.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(_(188)):(e=Object.keys(e).join(","),Error(_(268,e)));return e=Md(t),e=e===null?null:e.stateNode,e};nt.flushSync=function(e){return In(e)};nt.hydrate=function(e,t,n){if(!oi(t))throw Error(_(200));return ui(null,e,t,!0,n)};nt.hydrateRoot=function(e,t,n){if(!Hu(e))throw Error(_(405));var r=n!=null&&n.hydratedSources||null,l=!1,a="",i=ih;if(n!=null&&(n.unstable_strictMode===!0&&(l=!0),n.identifierPrefix!==void 0&&(a=n.identifierPrefix),n.onRecoverableError!==void 0&&(i=n.onRecoverableError)),t=ah(t,null,e,1,n??null,l,!1,a,i),e[It]=t.current,dl(e),r)for(e=0;e<r.length;e++)n=r[e],l=n._getVersion,l=l(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,l]:t.mutableSourceEagerHydrationData.push(n,l);return new ii(t)};nt.render=function(e,t,n){if(!oi(t))throw Error(_(200));return ui(null,e,t,!1,n)};nt.unmountComponentAtNode=function(e){if(!oi(e))throw Error(_(40));return e._reactRootContainer?(In(function(){ui(null,null,e,!1,function(){e._reactRootContainer=null,e[It]=null})}),!0):!1};nt.unstable_batchedUpdates=Fu;nt.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!oi(n))throw Error(_(200));if(e==null||e._reactInternals===void 0)throw Error(_(38));return ui(e,t,n,!1,r)};nt.version="18.3.1-next-f1338f8080-20240426";function oh(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(oh)}catch(e){console.error(e)}}oh(),id.exports=nt;var si=id.exports;const Ng=Xc(si),Mg=bc({__proto__:null,default:Ng},[si]);var mc=si;Gi.createRoot=mc.createRoot,Gi.hydrateRoot=mc.hydrateRoot;/** - * @remix-run/router v1.21.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function ue(){return ue=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ue.apply(this,arguments)}var ve;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(ve||(ve={}));const gc="popstate";function _g(e){e===void 0&&(e={});function t(r,l){let{pathname:a,search:i,hash:o}=r.location;return xl("",{pathname:a,search:i,hash:o},l.state&&l.state.usr||null,l.state&&l.state.key||"default")}function n(r,l){return typeof l=="string"?l:Un(l)}return Rg(t,n,null,e)}function Y(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function kr(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function jg(){return Math.random().toString(36).substr(2,8)}function yc(e,t){return{usr:e.state,key:e.key,idx:t}}function xl(e,t,n,r){return n===void 0&&(n=null),ue({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?At(t):t,{state:n,key:t&&t.key||r||jg()})}function Un(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function At(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Rg(e,t,n,r){r===void 0&&(r={});let{window:l=document.defaultView,v5Compat:a=!1}=r,i=l.history,o=ve.Pop,u=null,s=c();s==null&&(s=0,i.replaceState(ue({},i.state,{idx:s}),""));function c(){return(i.state||{idx:null}).idx}function f(){o=ve.Pop;let P=c(),p=P==null?null:P-s;s=P,u&&u({action:o,location:v.location,delta:p})}function h(P,p){o=ve.Push;let d=xl(v.location,P,p);s=c()+1;let y=yc(d,s),C=v.createHref(d);try{i.pushState(y,"",C)}catch(R){if(R instanceof DOMException&&R.name==="DataCloneError")throw R;l.location.assign(C)}a&&u&&u({action:o,location:v.location,delta:1})}function k(P,p){o=ve.Replace;let d=xl(v.location,P,p);s=c();let y=yc(d,s),C=v.createHref(d);i.replaceState(y,"",C),a&&u&&u({action:o,location:v.location,delta:0})}function S(P){let p=l.location.origin!=="null"?l.location.origin:l.location.href,d=typeof P=="string"?P:Un(P);return d=d.replace(/ $/,"%20"),Y(p,"No window.location.(origin|href) available to create URL for href: "+d),new URL(d,p)}let v={get action(){return o},get location(){return e(l,i)},listen(P){if(u)throw new Error("A history only accepts one active listener");return l.addEventListener(gc,f),u=P,()=>{l.removeEventListener(gc,f),u=null}},createHref(P){return t(l,P)},createURL:S,encodeLocation(P){let p=S(P);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:k,go(P){return i.go(P)}};return v}var ne;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(ne||(ne={}));const Tg=new Set(["lazy","caseSensitive","path","id","index","children"]);function Lg(e){return e.index===!0}function Aa(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((l,a)=>{let i=[...n,String(a)],o=typeof l.id=="string"?l.id:i.join("-");if(Y(l.index!==!0||!l.children,"Cannot specify children on an index route"),Y(!r[o],'Found a route id collision on id "'+o+`". Route id's must be globally unique within Data Router usages`),Lg(l)){let u=ue({},l,t(l),{id:o});return r[o]=u,u}else{let u=ue({},l,t(l),{id:o,children:void 0});return r[o]=u,l.children&&(u.children=Aa(l.children,t,i,r)),u}})}function Pn(e,t,n){return n===void 0&&(n="/"),ga(e,t,n,!1)}function ga(e,t,n,r){let l=typeof t=="string"?At(t):t,a=Pr(l.pathname||"/",n);if(a==null)return null;let i=uh(e);Og(i);let o=null;for(let u=0;o==null&&u<i.length;++u){let s=Yg(a);o=Hg(i[u],s,r)}return o}function Dg(e,t){let{route:n,pathname:r,params:l}=e;return{id:n.id,pathname:r,params:l,data:t[n.id],handle:n.handle}}function uh(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let l=(a,i,o)=>{let u={relativePath:o===void 0?a.path||"":o,caseSensitive:a.caseSensitive===!0,childrenIndex:i,route:a};u.relativePath.startsWith("/")&&(Y(u.relativePath.startsWith(r),'Absolute route path "'+u.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),u.relativePath=u.relativePath.slice(r.length));let s=zt([r,u.relativePath]),c=n.concat(u);a.children&&a.children.length>0&&(Y(a.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+s+'".')),uh(a.children,t,c,s)),!(a.path==null&&!a.index)&&t.push({path:s,score:$g(s,a.index),routesMeta:c})};return e.forEach((a,i)=>{var o;if(a.path===""||!((o=a.path)!=null&&o.includes("?")))l(a,i);else for(let u of sh(a.path))l(a,i,u)}),t}function sh(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,l=n.endsWith("?"),a=n.replace(/\?$/,"");if(r.length===0)return l?[a,""]:[a];let i=sh(r.join("/")),o=[];return o.push(...i.map(u=>u===""?a:[a,u].join("/"))),l&&o.push(...i),o.map(u=>e.startsWith("/")&&u===""?"/":u)}function Og(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Ag(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const zg=/^:[\w-]+$/,Fg=3,Ig=2,Ug=1,Bg=10,Wg=-2,vc=e=>e==="*";function $g(e,t){let n=e.split("/"),r=n.length;return n.some(vc)&&(r+=Wg),t&&(r+=Ig),n.filter(l=>!vc(l)).reduce((l,a)=>l+(zg.test(a)?Fg:a===""?Ug:Bg),r)}function Ag(e,t){return e.length===t.length&&e.slice(0,-1).every((r,l)=>r===t[l])?e[e.length-1]-t[t.length-1]:0}function Hg(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,l={},a="/",i=[];for(let o=0;o<r.length;++o){let u=r[o],s=o===r.length-1,c=a==="/"?t:t.slice(a.length)||"/",f=wc({path:u.relativePath,caseSensitive:u.caseSensitive,end:s},c),h=u.route;if(!f&&s&&n&&!r[r.length-1].route.index&&(f=wc({path:u.relativePath,caseSensitive:u.caseSensitive,end:!1},c)),!f)return null;Object.assign(l,f.params),i.push({params:l,pathname:zt([a,f.pathname]),pathnameBase:Xg(zt([a,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(a=zt([a,f.pathnameBase]))}return i}function wc(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Vg(e.path,e.caseSensitive,e.end),l=t.match(n);if(!l)return null;let a=l[0],i=a.replace(/(.)\/+$/,"$1"),o=l.slice(1);return{params:r.reduce((s,c,f)=>{let{paramName:h,isOptional:k}=c;if(h==="*"){let v=o[f]||"";i=a.slice(0,a.length-v.length).replace(/(.)\/+$/,"$1")}const S=o[f];return k&&!S?s[h]=void 0:s[h]=(S||"").replace(/%2F/g,"/"),s},{}),pathname:a,pathnameBase:i,pattern:e}}function Vg(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),kr(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],l="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,o,u)=>(r.push({paramName:o,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),l+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?l+="\\/*$":e!==""&&e!=="/"&&(l+="(?:(?=\\/|$))"),[new RegExp(l,t?void 0:"i"),r]}function Yg(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return kr(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Pr(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Qg(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:l=""}=typeof e=="string"?At(e):e;return{pathname:n?n.startsWith("/")?n:bg(n,t):t,search:Kg(r),hash:Gg(l)}}function bg(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(l=>{l===".."?n.length>1&&n.pop():l!=="."&&n.push(l)}),n.length>1?n.join("/"):"/"}function Yi(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function ch(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Vu(e,t){let n=ch(e);return t?n.map((r,l)=>l===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Yu(e,t,n,r){r===void 0&&(r=!1);let l;typeof e=="string"?l=At(e):(l=ue({},e),Y(!l.pathname||!l.pathname.includes("?"),Yi("?","pathname","search",l)),Y(!l.pathname||!l.pathname.includes("#"),Yi("#","pathname","hash",l)),Y(!l.search||!l.search.includes("#"),Yi("#","search","hash",l)));let a=e===""||l.pathname==="",i=a?"/":l.pathname,o;if(i==null)o=n;else{let f=t.length-1;if(!r&&i.startsWith("..")){let h=i.split("/");for(;h[0]==="..";)h.shift(),f-=1;l.pathname=h.join("/")}o=f>=0?t[f]:"/"}let u=Qg(l,o),s=i&&i!=="/"&&i.endsWith("/"),c=(a||i===".")&&n.endsWith("/");return!u.pathname.endsWith("/")&&(s||c)&&(u.pathname+="/"),u}const zt=e=>e.join("/").replace(/\/\/+/g,"/"),Xg=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Kg=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Gg=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Ha{constructor(t,n,r,l){l===void 0&&(l=!1),this.status=t,this.statusText=n||"",this.internal=l,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function ci(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const dh=["post","put","patch","delete"],Jg=new Set(dh),Zg=["get",...dh],qg=new Set(Zg),ey=new Set([301,302,303,307,308]),ty=new Set([307,308]),Qi={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ny={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ur={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},Qu=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ry=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),fh="remix-router-transitions";function ly(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Y(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let l;if(e.mapRouteProperties)l=e.mapRouteProperties;else if(e.detectErrorBoundary){let m=e.detectErrorBoundary;l=x=>({hasErrorBoundary:m(x)})}else l=ry;let a={},i=Aa(e.routes,l,void 0,a),o,u=e.basename||"/",s=e.dataStrategy||uy,c=e.patchRoutesOnNavigation,f=ue({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),h=null,k=new Set,S=null,v=null,P=null,p=e.hydrationData!=null,d=Pn(i,e.history.location,u),y=null;if(d==null&&!c){let m=Ye(404,{pathname:e.history.location.pathname}),{matches:x,route:E}=Rc(i);d=x,y={[E.id]:m}}d&&!e.hydrationData&&Ol(d,i,e.history.location.pathname).active&&(d=null);let C;if(d)if(d.some(m=>m.route.lazy))C=!1;else if(!d.some(m=>m.route.loader))C=!0;else if(f.v7_partialHydration){let m=e.hydrationData?e.hydrationData.loaderData:null,x=e.hydrationData?e.hydrationData.errors:null;if(x){let E=d.findIndex(M=>x[M.route.id]!==void 0);C=d.slice(0,E+1).every(M=>!Yo(M.route,m,x))}else C=d.every(E=>!Yo(E.route,m,x))}else C=e.hydrationData!=null;else if(C=!1,d=[],f.v7_partialHydration){let m=Ol(null,i,e.history.location.pathname);m.active&&m.matches&&(d=m.matches)}let R,w={historyAction:e.history.action,location:e.history.location,matches:d,initialized:C,navigation:Qi,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||y,fetchers:new Map,blockers:new Map},T=ve.Pop,j=!1,B,U=!1,te=new Map,ce=null,xe=!1,ke=!1,Ht=[],Vt=new Set,pe=new Map,D=0,A=-1,H=new Map,J=new Set,ae=new Map,wt=new Map,Ce=new Set,ct=new Map,Be=new Map,Nt;function Uh(){if(h=e.history.listen(m=>{let{action:x,location:E,delta:M}=m;if(Nt){Nt(),Nt=void 0;return}kr(Be.size===0||M!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let L=rs({currentLocation:w.location,nextLocation:E,historyAction:x});if(L&&M!=null){let W=new Promise(V=>{Nt=V});e.history.go(M*-1),Dl(L,{state:"blocked",location:E,proceed(){Dl(L,{state:"proceeding",proceed:void 0,reset:void 0,location:E}),W.then(()=>e.history.go(M))},reset(){let V=new Map(w.blockers);V.set(L,Ur),We({blockers:V})}});return}return wn(x,E)}),n){Sy(t,te);let m=()=>Ey(t,te);t.addEventListener("pagehide",m),ce=()=>t.removeEventListener("pagehide",m)}return w.initialized||wn(ve.Pop,w.location,{initialHydration:!0}),R}function Bh(){h&&h(),ce&&ce(),k.clear(),B&&B.abort(),w.fetchers.forEach((m,x)=>Ll(x)),w.blockers.forEach((m,x)=>ns(x))}function Wh(m){return k.add(m),()=>k.delete(m)}function We(m,x){x===void 0&&(x={}),w=ue({},w,m);let E=[],M=[];f.v7_fetcherPersist&&w.fetchers.forEach((L,W)=>{L.state==="idle"&&(Ce.has(W)?M.push(W):E.push(W))}),Ce.forEach(L=>{!w.fetchers.has(L)&&!pe.has(L)&&M.push(L)}),[...k].forEach(L=>L(w,{deletedFetchers:M,viewTransitionOpts:x.viewTransitionOpts,flushSync:x.flushSync===!0})),f.v7_fetcherPersist?(E.forEach(L=>w.fetchers.delete(L)),M.forEach(L=>Ll(L))):M.forEach(L=>Ce.delete(L))}function An(m,x,E){var M,L;let{flushSync:W}=E===void 0?{}:E,V=w.actionData!=null&&w.navigation.formMethod!=null&&pt(w.navigation.formMethod)&&w.navigation.state==="loading"&&((M=m.state)==null?void 0:M._isRedirect)!==!0,F;x.actionData?Object.keys(x.actionData).length>0?F=x.actionData:F=null:V?F=w.actionData:F=null;let I=x.loaderData?_c(w.loaderData,x.loaderData,x.matches||[],x.errors):w.loaderData,z=w.blockers;z.size>0&&(z=new Map(z),z.forEach((X,Te)=>z.set(Te,Ur)));let $=j===!0||w.navigation.formMethod!=null&&pt(w.navigation.formMethod)&&((L=m.state)==null?void 0:L._isRedirect)!==!0;o&&(i=o,o=void 0),xe||T===ve.Pop||(T===ve.Push?e.history.push(m,m.state):T===ve.Replace&&e.history.replace(m,m.state));let b;if(T===ve.Pop){let X=te.get(w.location.pathname);X&&X.has(m.pathname)?b={currentLocation:w.location,nextLocation:m}:te.has(m.pathname)&&(b={currentLocation:m,nextLocation:w.location})}else if(U){let X=te.get(w.location.pathname);X?X.add(m.pathname):(X=new Set([m.pathname]),te.set(w.location.pathname,X)),b={currentLocation:w.location,nextLocation:m}}We(ue({},x,{actionData:F,loaderData:I,historyAction:T,location:m,initialized:!0,navigation:Qi,revalidation:"idle",restoreScrollPosition:as(m,x.matches||w.matches),preventScrollReset:$,blockers:z}),{viewTransitionOpts:b,flushSync:W===!0}),T=ve.Pop,j=!1,U=!1,xe=!1,ke=!1,Ht=[]}async function Ku(m,x){if(typeof m=="number"){e.history.go(m);return}let E=Vo(w.location,w.matches,u,f.v7_prependBasename,m,f.v7_relativeSplatPath,x==null?void 0:x.fromRouteId,x==null?void 0:x.relative),{path:M,submission:L,error:W}=xc(f.v7_normalizeFormMethod,!1,E,x),V=w.location,F=xl(w.location,M,x&&x.state);F=ue({},F,e.history.encodeLocation(F));let I=x&&x.replace!=null?x.replace:void 0,z=ve.Push;I===!0?z=ve.Replace:I===!1||L!=null&&pt(L.formMethod)&&L.formAction===w.location.pathname+w.location.search&&(z=ve.Replace);let $=x&&"preventScrollReset"in x?x.preventScrollReset===!0:void 0,b=(x&&x.flushSync)===!0,X=rs({currentLocation:V,nextLocation:F,historyAction:z});if(X){Dl(X,{state:"blocked",location:F,proceed(){Dl(X,{state:"proceeding",proceed:void 0,reset:void 0,location:F}),Ku(m,x)},reset(){let Te=new Map(w.blockers);Te.set(X,Ur),We({blockers:Te})}});return}return await wn(z,F,{submission:L,pendingError:W,preventScrollReset:$,replace:x&&x.replace,enableViewTransition:x&&x.viewTransition,flushSync:b})}function $h(){if(mi(),We({revalidation:"loading"}),w.navigation.state!=="submitting"){if(w.navigation.state==="idle"){wn(w.historyAction,w.location,{startUninterruptedRevalidation:!0});return}wn(T||w.historyAction,w.navigation.location,{overrideNavigation:w.navigation,enableViewTransition:U===!0})}}async function wn(m,x,E){B&&B.abort(),B=null,T=m,xe=(E&&E.startUninterruptedRevalidation)===!0,Jh(w.location,w.matches),j=(E&&E.preventScrollReset)===!0,U=(E&&E.enableViewTransition)===!0;let M=o||i,L=E&&E.overrideNavigation,W=Pn(M,x,u),V=(E&&E.flushSync)===!0,F=Ol(W,M,x.pathname);if(F.active&&F.matches&&(W=F.matches),!W){let{error:re,notFoundMatches:Z,route:me}=gi(x.pathname);An(x,{matches:Z,loaderData:{},errors:{[me.id]:re}},{flushSync:V});return}if(w.initialized&&!ke&&py(w.location,x)&&!(E&&E.submission&&pt(E.submission.formMethod))){An(x,{matches:W},{flushSync:V});return}B=new AbortController;let I=bn(e.history,x,B.signal,E&&E.submission),z;if(E&&E.pendingError)z=[Nn(W).route.id,{type:ne.error,error:E.pendingError}];else if(E&&E.submission&&pt(E.submission.formMethod)){let re=await Ah(I,x,E.submission,W,F.active,{replace:E.replace,flushSync:V});if(re.shortCircuited)return;if(re.pendingActionResult){let[Z,me]=re.pendingActionResult;if(Ze(me)&&ci(me.error)&&me.error.status===404){B=null,An(x,{matches:re.matches,loaderData:{},errors:{[Z]:me.error}});return}}W=re.matches||W,z=re.pendingActionResult,L=bi(x,E.submission),V=!1,F.active=!1,I=bn(e.history,I.url,I.signal)}let{shortCircuited:$,matches:b,loaderData:X,errors:Te}=await Hh(I,x,W,F.active,L,E&&E.submission,E&&E.fetcherSubmission,E&&E.replace,E&&E.initialHydration===!0,V,z);$||(B=null,An(x,ue({matches:b||W},jc(z),{loaderData:X,errors:Te})))}async function Ah(m,x,E,M,L,W){W===void 0&&(W={}),mi();let V=xy(x,E);if(We({navigation:V},{flushSync:W.flushSync===!0}),L){let z=await zl(M,x.pathname,m.signal);if(z.type==="aborted")return{shortCircuited:!0};if(z.type==="error"){let $=Nn(z.partialMatches).route.id;return{matches:z.partialMatches,pendingActionResult:[$,{type:ne.error,error:z.error}]}}else if(z.matches)M=z.matches;else{let{notFoundMatches:$,error:b,route:X}=gi(x.pathname);return{matches:$,pendingActionResult:[X.id,{type:ne.error,error:b}]}}}let F,I=br(M,x);if(!I.route.action&&!I.route.lazy)F={type:ne.error,error:Ye(405,{method:m.method,pathname:x.pathname,routeId:I.route.id})};else if(F=(await Nr("action",w,m,[I],M,null))[I.route.id],m.signal.aborted)return{shortCircuited:!0};if(Rn(F)){let z;return W&&W.replace!=null?z=W.replace:z=Pc(F.response.headers.get("Location"),new URL(m.url),u)===w.location.pathname+w.location.search,await xn(m,F,!0,{submission:E,replace:z}),{shortCircuited:!0}}if(nn(F))throw Ye(400,{type:"defer-action"});if(Ze(F)){let z=Nn(M,I.route.id);return(W&&W.replace)!==!0&&(T=ve.Push),{matches:M,pendingActionResult:[z.route.id,F]}}return{matches:M,pendingActionResult:[I.route.id,F]}}async function Hh(m,x,E,M,L,W,V,F,I,z,$){let b=L||bi(x,W),X=W||V||Lc(b),Te=!xe&&(!f.v7_partialHydration||!I);if(M){if(Te){let ge=Gu($);We(ue({navigation:b},ge!==void 0?{actionData:ge}:{}),{flushSync:z})}let G=await zl(E,x.pathname,m.signal);if(G.type==="aborted")return{shortCircuited:!0};if(G.type==="error"){let ge=Nn(G.partialMatches).route.id;return{matches:G.partialMatches,loaderData:{},errors:{[ge]:G.error}}}else if(G.matches)E=G.matches;else{let{error:ge,notFoundMatches:Vn,route:jr}=gi(x.pathname);return{matches:Vn,loaderData:{},errors:{[jr.id]:ge}}}}let re=o||i,[Z,me]=Sc(e.history,w,E,X,x,f.v7_partialHydration&&I===!0,f.v7_skipActionErrorRevalidation,ke,Ht,Vt,Ce,ae,J,re,u,$);if(yi(G=>!(E&&E.some(ge=>ge.route.id===G))||Z&&Z.some(ge=>ge.route.id===G)),A=++D,Z.length===0&&me.length===0){let G=es();return An(x,ue({matches:E,loaderData:{},errors:$&&Ze($[1])?{[$[0]]:$[1].error}:null},jc($),G?{fetchers:new Map(w.fetchers)}:{}),{flushSync:z}),{shortCircuited:!0}}if(Te){let G={};if(!M){G.navigation=b;let ge=Gu($);ge!==void 0&&(G.actionData=ge)}me.length>0&&(G.fetchers=Vh(me)),We(G,{flushSync:z})}me.forEach(G=>{Qt(G.key),G.controller&&pe.set(G.key,G.controller)});let Hn=()=>me.forEach(G=>Qt(G.key));B&&B.signal.addEventListener("abort",Hn);let{loaderResults:Mr,fetcherResults:_t}=await Ju(w,E,Z,me,m);if(m.signal.aborted)return{shortCircuited:!0};B&&B.signal.removeEventListener("abort",Hn),me.forEach(G=>pe.delete(G.key));let xt=ta(Mr);if(xt)return await xn(m,xt.result,!0,{replace:F}),{shortCircuited:!0};if(xt=ta(_t),xt)return J.add(xt.key),await xn(m,xt.result,!0,{replace:F}),{shortCircuited:!0};let{loaderData:vi,errors:_r}=Mc(w,E,Mr,$,me,_t,ct);ct.forEach((G,ge)=>{G.subscribe(Vn=>{(Vn||G.done)&&ct.delete(ge)})}),f.v7_partialHydration&&I&&w.errors&&(_r=ue({},w.errors,_r));let kn=es(),Fl=ts(A),Il=kn||Fl||me.length>0;return ue({matches:E,loaderData:vi,errors:_r},Il?{fetchers:new Map(w.fetchers)}:{})}function Gu(m){if(m&&!Ze(m[1]))return{[m[0]]:m[1].data};if(w.actionData)return Object.keys(w.actionData).length===0?null:w.actionData}function Vh(m){return m.forEach(x=>{let E=w.fetchers.get(x.key),M=Br(void 0,E?E.data:void 0);w.fetchers.set(x.key,M)}),new Map(w.fetchers)}function Yh(m,x,E,M){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");Qt(m);let L=(M&&M.flushSync)===!0,W=o||i,V=Vo(w.location,w.matches,u,f.v7_prependBasename,E,f.v7_relativeSplatPath,x,M==null?void 0:M.relative),F=Pn(W,V,u),I=Ol(F,W,V);if(I.active&&I.matches&&(F=I.matches),!F){Mt(m,x,Ye(404,{pathname:V}),{flushSync:L});return}let{path:z,submission:$,error:b}=xc(f.v7_normalizeFormMethod,!0,V,M);if(b){Mt(m,x,b,{flushSync:L});return}let X=br(F,z),Te=(M&&M.preventScrollReset)===!0;if($&&pt($.formMethod)){Qh(m,x,z,X,F,I.active,L,Te,$);return}ae.set(m,{routeId:x,path:z}),bh(m,x,z,X,F,I.active,L,Te,$)}async function Qh(m,x,E,M,L,W,V,F,I){mi(),ae.delete(m);function z(Se){if(!Se.route.action&&!Se.route.lazy){let Yn=Ye(405,{method:I.formMethod,pathname:E,routeId:x});return Mt(m,x,Yn,{flushSync:V}),!0}return!1}if(!W&&z(M))return;let $=w.fetchers.get(m);Yt(m,ky(I,$),{flushSync:V});let b=new AbortController,X=bn(e.history,E,b.signal,I);if(W){let Se=await zl(L,E,X.signal);if(Se.type==="aborted")return;if(Se.type==="error"){Mt(m,x,Se.error,{flushSync:V});return}else if(Se.matches){if(L=Se.matches,M=br(L,E),z(M))return}else{Mt(m,x,Ye(404,{pathname:E}),{flushSync:V});return}}pe.set(m,b);let Te=D,Z=(await Nr("action",w,X,[M],L,m))[M.route.id];if(X.signal.aborted){pe.get(m)===b&&pe.delete(m);return}if(f.v7_fetcherPersist&&Ce.has(m)){if(Rn(Z)||Ze(Z)){Yt(m,Kt(void 0));return}}else{if(Rn(Z))if(pe.delete(m),A>Te){Yt(m,Kt(void 0));return}else return J.add(m),Yt(m,Br(I)),xn(X,Z,!1,{fetcherSubmission:I,preventScrollReset:F});if(Ze(Z)){Mt(m,x,Z.error);return}}if(nn(Z))throw Ye(400,{type:"defer-action"});let me=w.navigation.location||w.location,Hn=bn(e.history,me,b.signal),Mr=o||i,_t=w.navigation.state!=="idle"?Pn(Mr,w.navigation.location,u):w.matches;Y(_t,"Didn't find any matches after fetcher action");let xt=++D;H.set(m,xt);let vi=Br(I,Z.data);w.fetchers.set(m,vi);let[_r,kn]=Sc(e.history,w,_t,I,me,!1,f.v7_skipActionErrorRevalidation,ke,Ht,Vt,Ce,ae,J,Mr,u,[M.route.id,Z]);kn.filter(Se=>Se.key!==m).forEach(Se=>{let Yn=Se.key,is=w.fetchers.get(Yn),ep=Br(void 0,is?is.data:void 0);w.fetchers.set(Yn,ep),Qt(Yn),Se.controller&&pe.set(Yn,Se.controller)}),We({fetchers:new Map(w.fetchers)});let Fl=()=>kn.forEach(Se=>Qt(Se.key));b.signal.addEventListener("abort",Fl);let{loaderResults:Il,fetcherResults:G}=await Ju(w,_t,_r,kn,Hn);if(b.signal.aborted)return;b.signal.removeEventListener("abort",Fl),H.delete(m),pe.delete(m),kn.forEach(Se=>pe.delete(Se.key));let ge=ta(Il);if(ge)return xn(Hn,ge.result,!1,{preventScrollReset:F});if(ge=ta(G),ge)return J.add(ge.key),xn(Hn,ge.result,!1,{preventScrollReset:F});let{loaderData:Vn,errors:jr}=Mc(w,_t,Il,void 0,kn,G,ct);if(w.fetchers.has(m)){let Se=Kt(Z.data);w.fetchers.set(m,Se)}ts(xt),w.navigation.state==="loading"&&xt>A?(Y(T,"Expected pending action"),B&&B.abort(),An(w.navigation.location,{matches:_t,loaderData:Vn,errors:jr,fetchers:new Map(w.fetchers)})):(We({errors:jr,loaderData:_c(w.loaderData,Vn,_t,jr),fetchers:new Map(w.fetchers)}),ke=!1)}async function bh(m,x,E,M,L,W,V,F,I){let z=w.fetchers.get(m);Yt(m,Br(I,z?z.data:void 0),{flushSync:V});let $=new AbortController,b=bn(e.history,E,$.signal);if(W){let Z=await zl(L,E,b.signal);if(Z.type==="aborted")return;if(Z.type==="error"){Mt(m,x,Z.error,{flushSync:V});return}else if(Z.matches)L=Z.matches,M=br(L,E);else{Mt(m,x,Ye(404,{pathname:E}),{flushSync:V});return}}pe.set(m,$);let X=D,re=(await Nr("loader",w,b,[M],L,m))[M.route.id];if(nn(re)&&(re=await bu(re,b.signal,!0)||re),pe.get(m)===$&&pe.delete(m),!b.signal.aborted){if(Ce.has(m)){Yt(m,Kt(void 0));return}if(Rn(re))if(A>X){Yt(m,Kt(void 0));return}else{J.add(m),await xn(b,re,!1,{preventScrollReset:F});return}if(Ze(re)){Mt(m,x,re.error);return}Y(!nn(re),"Unhandled fetcher deferred data"),Yt(m,Kt(re.data))}}async function xn(m,x,E,M){let{submission:L,fetcherSubmission:W,preventScrollReset:V,replace:F}=M===void 0?{}:M;x.response.headers.has("X-Remix-Revalidate")&&(ke=!0);let I=x.response.headers.get("Location");Y(I,"Expected a Location header on the redirect Response"),I=Pc(I,new URL(m.url),u);let z=xl(w.location,I,{_isRedirect:!0});if(n){let Z=!1;if(x.response.headers.has("X-Remix-Reload-Document"))Z=!0;else if(Qu.test(I)){const me=e.history.createURL(I);Z=me.origin!==t.location.origin||Pr(me.pathname,u)==null}if(Z){F?t.location.replace(I):t.location.assign(I);return}}B=null;let $=F===!0||x.response.headers.has("X-Remix-Replace")?ve.Replace:ve.Push,{formMethod:b,formAction:X,formEncType:Te}=w.navigation;!L&&!W&&b&&X&&Te&&(L=Lc(w.navigation));let re=L||W;if(ty.has(x.response.status)&&re&&pt(re.formMethod))await wn($,z,{submission:ue({},re,{formAction:I}),preventScrollReset:V||j,enableViewTransition:E?U:void 0});else{let Z=bi(z,L);await wn($,z,{overrideNavigation:Z,fetcherSubmission:W,preventScrollReset:V||j,enableViewTransition:E?U:void 0})}}async function Nr(m,x,E,M,L,W){let V,F={};try{V=await sy(s,m,x,E,M,L,W,a,l)}catch(I){return M.forEach(z=>{F[z.route.id]={type:ne.error,error:I}}),F}for(let[I,z]of Object.entries(V))if(my(z)){let $=z.result;F[I]={type:ne.redirect,response:fy($,E,I,L,u,f.v7_relativeSplatPath)}}else F[I]=await dy(z);return F}async function Ju(m,x,E,M,L){let W=m.matches,V=Nr("loader",m,L,E,x,null),F=Promise.all(M.map(async $=>{if($.matches&&$.match&&$.controller){let X=(await Nr("loader",m,bn(e.history,$.path,$.controller.signal),[$.match],$.matches,$.key))[$.match.route.id];return{[$.key]:X}}else return Promise.resolve({[$.key]:{type:ne.error,error:Ye(404,{pathname:$.path})}})})),I=await V,z=(await F).reduce(($,b)=>Object.assign($,b),{});return await Promise.all([vy(x,I,L.signal,W,m.loaderData),wy(x,z,M)]),{loaderResults:I,fetcherResults:z}}function mi(){ke=!0,Ht.push(...yi()),ae.forEach((m,x)=>{pe.has(x)&&Vt.add(x),Qt(x)})}function Yt(m,x,E){E===void 0&&(E={}),w.fetchers.set(m,x),We({fetchers:new Map(w.fetchers)},{flushSync:(E&&E.flushSync)===!0})}function Mt(m,x,E,M){M===void 0&&(M={});let L=Nn(w.matches,x);Ll(m),We({errors:{[L.route.id]:E},fetchers:new Map(w.fetchers)},{flushSync:(M&&M.flushSync)===!0})}function Zu(m){return wt.set(m,(wt.get(m)||0)+1),Ce.has(m)&&Ce.delete(m),w.fetchers.get(m)||ny}function Ll(m){let x=w.fetchers.get(m);pe.has(m)&&!(x&&x.state==="loading"&&H.has(m))&&Qt(m),ae.delete(m),H.delete(m),J.delete(m),f.v7_fetcherPersist&&Ce.delete(m),Vt.delete(m),w.fetchers.delete(m)}function Xh(m){let x=(wt.get(m)||0)-1;x<=0?(wt.delete(m),Ce.add(m),f.v7_fetcherPersist||Ll(m)):wt.set(m,x),We({fetchers:new Map(w.fetchers)})}function Qt(m){let x=pe.get(m);x&&(x.abort(),pe.delete(m))}function qu(m){for(let x of m){let E=Zu(x),M=Kt(E.data);w.fetchers.set(x,M)}}function es(){let m=[],x=!1;for(let E of J){let M=w.fetchers.get(E);Y(M,"Expected fetcher: "+E),M.state==="loading"&&(J.delete(E),m.push(E),x=!0)}return qu(m),x}function ts(m){let x=[];for(let[E,M]of H)if(M<m){let L=w.fetchers.get(E);Y(L,"Expected fetcher: "+E),L.state==="loading"&&(Qt(E),H.delete(E),x.push(E))}return qu(x),x.length>0}function Kh(m,x){let E=w.blockers.get(m)||Ur;return Be.get(m)!==x&&Be.set(m,x),E}function ns(m){w.blockers.delete(m),Be.delete(m)}function Dl(m,x){let E=w.blockers.get(m)||Ur;Y(E.state==="unblocked"&&x.state==="blocked"||E.state==="blocked"&&x.state==="blocked"||E.state==="blocked"&&x.state==="proceeding"||E.state==="blocked"&&x.state==="unblocked"||E.state==="proceeding"&&x.state==="unblocked","Invalid blocker state transition: "+E.state+" -> "+x.state);let M=new Map(w.blockers);M.set(m,x),We({blockers:M})}function rs(m){let{currentLocation:x,nextLocation:E,historyAction:M}=m;if(Be.size===0)return;Be.size>1&&kr(!1,"A router only supports one blocker at a time");let L=Array.from(Be.entries()),[W,V]=L[L.length-1],F=w.blockers.get(W);if(!(F&&F.state==="proceeding")&&V({currentLocation:x,nextLocation:E,historyAction:M}))return W}function gi(m){let x=Ye(404,{pathname:m}),E=o||i,{matches:M,route:L}=Rc(E);return yi(),{notFoundMatches:M,route:L,error:x}}function yi(m){let x=[];return ct.forEach((E,M)=>{(!m||m(M))&&(E.cancel(),x.push(M),ct.delete(M))}),x}function Gh(m,x,E){if(S=m,P=x,v=E||null,!p&&w.navigation===Qi){p=!0;let M=as(w.location,w.matches);M!=null&&We({restoreScrollPosition:M})}return()=>{S=null,P=null,v=null}}function ls(m,x){return v&&v(m,x.map(M=>Dg(M,w.loaderData)))||m.key}function Jh(m,x){if(S&&P){let E=ls(m,x);S[E]=P()}}function as(m,x){if(S){let E=ls(m,x),M=S[E];if(typeof M=="number")return M}return null}function Ol(m,x,E){if(c)if(m){if(Object.keys(m[0].params).length>0)return{active:!0,matches:ga(x,E,u,!0)}}else return{active:!0,matches:ga(x,E,u,!0)||[]};return{active:!1,matches:null}}async function zl(m,x,E){if(!c)return{type:"success",matches:m};let M=m;for(;;){let L=o==null,W=o||i,V=a;try{await c({path:x,matches:M,patch:(z,$)=>{E.aborted||Cc(z,$,W,V,l)}})}catch(z){return{type:"error",error:z,partialMatches:M}}finally{L&&!E.aborted&&(i=[...i])}if(E.aborted)return{type:"aborted"};let F=Pn(W,x,u);if(F)return{type:"success",matches:F};let I=ga(W,x,u,!0);if(!I||M.length===I.length&&M.every((z,$)=>z.route.id===I[$].route.id))return{type:"success",matches:null};M=I}}function Zh(m){a={},o=Aa(m,l,void 0,a)}function qh(m,x){let E=o==null;Cc(m,x,o||i,a,l),E&&(i=[...i],We({}))}return R={get basename(){return u},get future(){return f},get state(){return w},get routes(){return i},get window(){return t},initialize:Uh,subscribe:Wh,enableScrollRestoration:Gh,navigate:Ku,fetch:Yh,revalidate:$h,createHref:m=>e.history.createHref(m),encodeLocation:m=>e.history.encodeLocation(m),getFetcher:Zu,deleteFetcher:Xh,dispose:Bh,getBlocker:Kh,deleteBlocker:ns,patchRoutes:qh,_internalFetchControllers:pe,_internalActiveDeferreds:ct,_internalSetRoutes:Zh},R}function ay(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Vo(e,t,n,r,l,a,i,o){let u,s;if(i){u=[];for(let f of t)if(u.push(f),f.route.id===i){s=f;break}}else u=t,s=t[t.length-1];let c=Yu(l||".",Vu(u,a),Pr(e.pathname,n)||e.pathname,o==="path");if(l==null&&(c.search=e.search,c.hash=e.hash),(l==null||l===""||l===".")&&s){let f=Xu(c.search);if(s.route.index&&!f)c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index";else if(!s.route.index&&f){let h=new URLSearchParams(c.search),k=h.getAll("index");h.delete("index"),k.filter(v=>v).forEach(v=>h.append("index",v));let S=h.toString();c.search=S?"?"+S:""}}return r&&n!=="/"&&(c.pathname=c.pathname==="/"?n:zt([n,c.pathname])),Un(c)}function xc(e,t,n,r){if(!r||!ay(r))return{path:n};if(r.formMethod&&!yy(r.formMethod))return{path:n,error:Ye(405,{method:r.formMethod})};let l=()=>({path:n,error:Ye(400,{type:"invalid-body"})}),a=r.formMethod||"get",i=e?a.toUpperCase():a.toLowerCase(),o=mh(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!pt(i))return l();let h=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((k,S)=>{let[v,P]=S;return""+k+v+"="+P+` -`},""):String(r.body);return{path:n,submission:{formMethod:i,formAction:o,formEncType:r.formEncType,formData:void 0,json:void 0,text:h}}}else if(r.formEncType==="application/json"){if(!pt(i))return l();try{let h=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:i,formAction:o,formEncType:r.formEncType,formData:void 0,json:h,text:void 0}}}catch{return l()}}}Y(typeof FormData=="function","FormData is not available in this environment");let u,s;if(r.formData)u=Qo(r.formData),s=r.formData;else if(r.body instanceof FormData)u=Qo(r.body),s=r.body;else if(r.body instanceof URLSearchParams)u=r.body,s=Nc(u);else if(r.body==null)u=new URLSearchParams,s=new FormData;else try{u=new URLSearchParams(r.body),s=Nc(u)}catch{return l()}let c={formMethod:i,formAction:o,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:s,json:void 0,text:void 0};if(pt(c.formMethod))return{path:n,submission:c};let f=At(n);return t&&f.search&&Xu(f.search)&&u.append("index",""),f.search="?"+u,{path:Un(f),submission:c}}function kc(e,t,n){n===void 0&&(n=!1);let r=e.findIndex(l=>l.route.id===t);return r>=0?e.slice(0,n?r+1:r):e}function Sc(e,t,n,r,l,a,i,o,u,s,c,f,h,k,S,v){let P=v?Ze(v[1])?v[1].error:v[1].data:void 0,p=e.createURL(t.location),d=e.createURL(l),y=n;a&&t.errors?y=kc(n,Object.keys(t.errors)[0],!0):v&&Ze(v[1])&&(y=kc(n,v[0]));let C=v?v[1].statusCode:void 0,R=i&&C&&C>=400,w=y.filter((j,B)=>{let{route:U}=j;if(U.lazy)return!0;if(U.loader==null)return!1;if(a)return Yo(U,t.loaderData,t.errors);if(iy(t.loaderData,t.matches[B],j)||u.some(xe=>xe===j.route.id))return!0;let te=t.matches[B],ce=j;return Ec(j,ue({currentUrl:p,currentParams:te.params,nextUrl:d,nextParams:ce.params},r,{actionResult:P,actionStatus:C,defaultShouldRevalidate:R?!1:o||p.pathname+p.search===d.pathname+d.search||p.search!==d.search||hh(te,ce)}))}),T=[];return f.forEach((j,B)=>{if(a||!n.some(ke=>ke.route.id===j.routeId)||c.has(B))return;let U=Pn(k,j.path,S);if(!U){T.push({key:B,routeId:j.routeId,path:j.path,matches:null,match:null,controller:null});return}let te=t.fetchers.get(B),ce=br(U,j.path),xe=!1;h.has(B)?xe=!1:s.has(B)?(s.delete(B),xe=!0):te&&te.state!=="idle"&&te.data===void 0?xe=o:xe=Ec(ce,ue({currentUrl:p,currentParams:t.matches[t.matches.length-1].params,nextUrl:d,nextParams:n[n.length-1].params},r,{actionResult:P,actionStatus:C,defaultShouldRevalidate:R?!1:o})),xe&&T.push({key:B,routeId:j.routeId,path:j.path,matches:U,match:ce,controller:new AbortController})}),[w,T]}function Yo(e,t,n){if(e.lazy)return!0;if(!e.loader)return!1;let r=t!=null&&t[e.id]!==void 0,l=n!=null&&n[e.id]!==void 0;return!r&&l?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!r&&!l}function iy(e,t,n){let r=!t||n.route.id!==t.route.id,l=e[n.route.id]===void 0;return r||l}function hh(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function Ec(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function Cc(e,t,n,r,l){var a;let i;if(e){let s=r[e];Y(s,"No route found to patch children into: routeId = "+e),s.children||(s.children=[]),i=s.children}else i=n;let o=t.filter(s=>!i.some(c=>ph(s,c))),u=Aa(o,l,[e||"_","patch",String(((a=i)==null?void 0:a.length)||"0")],r);i.push(...u)}function ph(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((n,r)=>{var l;return(l=t.children)==null?void 0:l.some(a=>ph(n,a))}):!1}async function oy(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let l=n[e.id];Y(l,"No route found in manifest");let a={};for(let i in r){let u=l[i]!==void 0&&i!=="hasErrorBoundary";kr(!u,'Route "'+l.id+'" has a static property "'+i+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+i+'" will be ignored.')),!u&&!Tg.has(i)&&(a[i]=r[i])}Object.assign(l,a),Object.assign(l,ue({},t(l),{lazy:void 0}))}async function uy(e){let{matches:t}=e,n=t.filter(l=>l.shouldLoad);return(await Promise.all(n.map(l=>l.resolve()))).reduce((l,a,i)=>Object.assign(l,{[n[i].route.id]:a}),{})}async function sy(e,t,n,r,l,a,i,o,u,s){let c=a.map(k=>k.route.lazy?oy(k.route,u,o):void 0),f=a.map((k,S)=>{let v=c[S],P=l.some(d=>d.route.id===k.route.id);return ue({},k,{shouldLoad:P,resolve:async d=>(d&&r.method==="GET"&&(k.route.lazy||k.route.loader)&&(P=!0),P?cy(t,r,k,v,d,s):Promise.resolve({type:ne.data,result:void 0}))})}),h=await e({matches:f,request:r,params:a[0].params,fetcherKey:i,context:s});try{await Promise.all(c)}catch{}return h}async function cy(e,t,n,r,l,a){let i,o,u=s=>{let c,f=new Promise((S,v)=>c=v);o=()=>c(),t.signal.addEventListener("abort",o);let h=S=>typeof s!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):s({request:t,params:n.params,context:a},...S!==void 0?[S]:[]),k=(async()=>{try{return{type:"data",result:await(l?l(v=>h(v)):h())}}catch(S){return{type:"error",result:S}}})();return Promise.race([k,f])};try{let s=n.route[e];if(r)if(s){let c,[f]=await Promise.all([u(s).catch(h=>{c=h}),r]);if(c!==void 0)throw c;i=f}else if(await r,s=n.route[e],s)i=await u(s);else if(e==="action"){let c=new URL(t.url),f=c.pathname+c.search;throw Ye(405,{method:t.method,pathname:f,routeId:n.route.id})}else return{type:ne.data,result:void 0};else if(s)i=await u(s);else{let c=new URL(t.url),f=c.pathname+c.search;throw Ye(404,{pathname:f})}Y(i.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(s){return{type:ne.error,result:s}}finally{o&&t.signal.removeEventListener("abort",o)}return i}async function dy(e){let{result:t,type:n}=e;if(gh(t)){let s;try{let c=t.headers.get("Content-Type");c&&/\bapplication\/json\b/.test(c)?t.body==null?s=null:s=await t.json():s=await t.text()}catch(c){return{type:ne.error,error:c}}return n===ne.error?{type:ne.error,error:new Ha(t.status,t.statusText,s),statusCode:t.status,headers:t.headers}:{type:ne.data,data:s,statusCode:t.status,headers:t.headers}}if(n===ne.error){if(Tc(t)){var r;if(t.data instanceof Error){var l;return{type:ne.error,error:t.data,statusCode:(l=t.init)==null?void 0:l.status}}t=new Ha(((r=t.init)==null?void 0:r.status)||500,void 0,t.data)}return{type:ne.error,error:t,statusCode:ci(t)?t.status:void 0}}if(gy(t)){var a,i;return{type:ne.deferred,deferredData:t,statusCode:(a=t.init)==null?void 0:a.status,headers:((i=t.init)==null?void 0:i.headers)&&new Headers(t.init.headers)}}if(Tc(t)){var o,u;return{type:ne.data,data:t.data,statusCode:(o=t.init)==null?void 0:o.status,headers:(u=t.init)!=null&&u.headers?new Headers(t.init.headers):void 0}}return{type:ne.data,data:t}}function fy(e,t,n,r,l,a){let i=e.headers.get("Location");if(Y(i,"Redirects returned/thrown from loaders/actions must have a Location header"),!Qu.test(i)){let o=r.slice(0,r.findIndex(u=>u.route.id===n)+1);i=Vo(new URL(t.url),o,l,!0,i,a),e.headers.set("Location",i)}return e}function Pc(e,t,n){if(Qu.test(e)){let r=e,l=r.startsWith("//")?new URL(t.protocol+r):new URL(r),a=Pr(l.pathname,n)!=null;if(l.origin===t.origin&&a)return l.pathname+l.search+l.hash}return e}function bn(e,t,n,r){let l=e.createURL(mh(t)).toString(),a={signal:n};if(r&&pt(r.formMethod)){let{formMethod:i,formEncType:o}=r;a.method=i.toUpperCase(),o==="application/json"?(a.headers=new Headers({"Content-Type":o}),a.body=JSON.stringify(r.json)):o==="text/plain"?a.body=r.text:o==="application/x-www-form-urlencoded"&&r.formData?a.body=Qo(r.formData):a.body=r.formData}return new Request(l,a)}function Qo(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Nc(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function hy(e,t,n,r,l){let a={},i=null,o,u=!1,s={},c=n&&Ze(n[1])?n[1].error:void 0;return e.forEach(f=>{if(!(f.route.id in t))return;let h=f.route.id,k=t[h];if(Y(!Rn(k),"Cannot handle redirect results in processLoaderData"),Ze(k)){let S=k.error;c!==void 0&&(S=c,c=void 0),i=i||{};{let v=Nn(e,h);i[v.route.id]==null&&(i[v.route.id]=S)}a[h]=void 0,u||(u=!0,o=ci(k.error)?k.error.status:500),k.headers&&(s[h]=k.headers)}else nn(k)?(r.set(h,k.deferredData),a[h]=k.deferredData.data,k.statusCode!=null&&k.statusCode!==200&&!u&&(o=k.statusCode),k.headers&&(s[h]=k.headers)):(a[h]=k.data,k.statusCode&&k.statusCode!==200&&!u&&(o=k.statusCode),k.headers&&(s[h]=k.headers))}),c!==void 0&&n&&(i={[n[0]]:c},a[n[0]]=void 0),{loaderData:a,errors:i,statusCode:o||200,loaderHeaders:s}}function Mc(e,t,n,r,l,a,i){let{loaderData:o,errors:u}=hy(t,n,r,i);return l.forEach(s=>{let{key:c,match:f,controller:h}=s,k=a[c];if(Y(k,"Did not find corresponding fetcher result"),!(h&&h.signal.aborted))if(Ze(k)){let S=Nn(e.matches,f==null?void 0:f.route.id);u&&u[S.route.id]||(u=ue({},u,{[S.route.id]:k.error})),e.fetchers.delete(c)}else if(Rn(k))Y(!1,"Unhandled fetcher revalidation redirect");else if(nn(k))Y(!1,"Unhandled fetcher deferred data");else{let S=Kt(k.data);e.fetchers.set(c,S)}}),{loaderData:o,errors:u}}function _c(e,t,n,r){let l=ue({},t);for(let a of n){let i=a.route.id;if(t.hasOwnProperty(i)?t[i]!==void 0&&(l[i]=t[i]):e[i]!==void 0&&a.route.loader&&(l[i]=e[i]),r&&r.hasOwnProperty(i))break}return l}function jc(e){return e?Ze(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Nn(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function Rc(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Ye(e,t){let{pathname:n,routeId:r,method:l,type:a,message:i}=t===void 0?{}:t,o="Unknown Server Error",u="Unknown @remix-run/router error";return e===400?(o="Bad Request",l&&n&&r?u="You made a "+l+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":a==="defer-action"?u="defer() is not supported in actions":a==="invalid-body"&&(u="Unable to encode submission body")):e===403?(o="Forbidden",u='Route "'+r+'" does not match URL "'+n+'"'):e===404?(o="Not Found",u='No route matches URL "'+n+'"'):e===405&&(o="Method Not Allowed",l&&n&&r?u="You made a "+l.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":l&&(u='Invalid request method "'+l.toUpperCase()+'"')),new Ha(e||500,o,new Error(u),!0)}function ta(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,l]=t[n];if(Rn(l))return{key:r,result:l}}}function mh(e){let t=typeof e=="string"?At(e):e;return Un(ue({},t,{hash:""}))}function py(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function my(e){return gh(e.result)&&ey.has(e.result.status)}function nn(e){return e.type===ne.deferred}function Ze(e){return e.type===ne.error}function Rn(e){return(e&&e.type)===ne.redirect}function Tc(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function gy(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function gh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function yy(e){return qg.has(e.toLowerCase())}function pt(e){return Jg.has(e.toLowerCase())}async function vy(e,t,n,r,l){let a=Object.entries(t);for(let i=0;i<a.length;i++){let[o,u]=a[i],s=e.find(h=>(h==null?void 0:h.route.id)===o);if(!s)continue;let c=r.find(h=>h.route.id===s.route.id),f=c!=null&&!hh(c,s)&&(l&&l[s.route.id])!==void 0;nn(u)&&f&&await bu(u,n,!1).then(h=>{h&&(t[o]=h)})}}async function wy(e,t,n){for(let r=0;r<n.length;r++){let{key:l,routeId:a,controller:i}=n[r],o=t[l];e.find(s=>(s==null?void 0:s.route.id)===a)&&nn(o)&&(Y(i,"Expected an AbortController for revalidating fetcher deferred result"),await bu(o,i.signal,!0).then(s=>{s&&(t[l]=s)}))}}async function bu(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:ne.data,data:e.deferredData.unwrappedData}}catch(l){return{type:ne.error,error:l}}return{type:ne.data,data:e.deferredData.data}}}function Xu(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function br(e,t){let n=typeof t=="string"?At(t).search:t.search;if(e[e.length-1].route.index&&Xu(n||""))return e[e.length-1];let r=ch(e);return r[r.length-1]}function Lc(e){let{formMethod:t,formAction:n,formEncType:r,text:l,formData:a,json:i}=e;if(!(!t||!n||!r)){if(l!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:l};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(i!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:i,text:void 0}}}function bi(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function xy(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Br(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function ky(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Kt(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function Sy(e,t){try{let n=e.sessionStorage.getItem(fh);if(n){let r=JSON.parse(n);for(let[l,a]of Object.entries(r||{}))a&&Array.isArray(a)&&t.set(l,new Set(a||[]))}}catch{}}function Ey(e,t){if(t.size>0){let n={};for(let[r,l]of t)n[r]=[...l];try{e.sessionStorage.setItem(fh,JSON.stringify(n))}catch(r){kr(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** - * React Router v6.28.2 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function kl(){return kl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},kl.apply(this,arguments)}const di=N.createContext(null),yh=N.createContext(null),$n=N.createContext(null),fi=N.createContext(null),vn=N.createContext({outlet:null,matches:[],isDataRoute:!1}),vh=N.createContext(null);function Cy(e,t){let{relative:n}=t===void 0?{}:t;jl()||Y(!1);let{basename:r,navigator:l}=N.useContext($n),{hash:a,pathname:i,search:o}=kh(e,{relative:n}),u=i;return r!=="/"&&(u=i==="/"?r:zt([r,i])),l.createHref({pathname:u,search:o,hash:a})}function jl(){return N.useContext(fi)!=null}function Rl(){return jl()||Y(!1),N.useContext(fi).location}function wh(e){N.useContext($n).static||N.useLayoutEffect(e)}function xh(){let{isDataRoute:e}=N.useContext(vn);return e?Iy():Py()}function Py(){jl()||Y(!1);let e=N.useContext(di),{basename:t,future:n,navigator:r}=N.useContext($n),{matches:l}=N.useContext(vn),{pathname:a}=Rl(),i=JSON.stringify(Vu(l,n.v7_relativeSplatPath)),o=N.useRef(!1);return wh(()=>{o.current=!0}),N.useCallback(function(s,c){if(c===void 0&&(c={}),!o.current)return;if(typeof s=="number"){r.go(s);return}let f=Yu(s,JSON.parse(i),a,c.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:zt([t,f.pathname])),(c.replace?r.replace:r.push)(f,c.state,c)},[t,r,i,a,e])}function Ny(){let{matches:e}=N.useContext(vn),t=e[e.length-1];return t?t.params:{}}function kh(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=N.useContext($n),{matches:l}=N.useContext(vn),{pathname:a}=Rl(),i=JSON.stringify(Vu(l,r.v7_relativeSplatPath));return N.useMemo(()=>Yu(e,JSON.parse(i),a,n==="path"),[e,i,a,n])}function My(e,t){return Sh(e,t)}function Sh(e,t,n,r){jl()||Y(!1);let{navigator:l}=N.useContext($n),{matches:a}=N.useContext(vn),i=a[a.length-1],o=i?i.params:{};i&&i.pathname;let u=i?i.pathnameBase:"/";i&&i.route;let s=Rl(),c;if(t){var f;let P=typeof t=="string"?At(t):t;u==="/"||(f=P.pathname)!=null&&f.startsWith(u)||Y(!1),c=P}else c=s;let h=c.pathname||"/",k=h;if(u!=="/"){let P=u.replace(/^\//,"").split("/");k="/"+h.replace(/^\//,"").split("/").slice(P.length).join("/")}let S=Pn(e,{pathname:k}),v=Ly(S&&S.map(P=>Object.assign({},P,{params:Object.assign({},o,P.params),pathname:zt([u,l.encodeLocation?l.encodeLocation(P.pathname).pathname:P.pathname]),pathnameBase:P.pathnameBase==="/"?u:zt([u,l.encodeLocation?l.encodeLocation(P.pathnameBase).pathname:P.pathnameBase])})),a,n,r);return t&&v?N.createElement(fi.Provider,{value:{location:kl({pathname:"/",search:"",hash:"",state:null,key:"default"},c),navigationType:ve.Pop}},v):v}function _y(){let e=Fy(),t=ci(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,l={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},t),n?N.createElement("pre",{style:l},n):null,null)}const jy=N.createElement(_y,null);class Ry extends N.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?N.createElement(vn.Provider,{value:this.props.routeContext},N.createElement(vh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Ty(e){let{routeContext:t,match:n,children:r}=e,l=N.useContext(di);return l&&l.static&&l.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(l.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(vn.Provider,{value:t},r)}function Ly(e,t,n,r){var l;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var a;if(!n)return null;if(n.errors)e=n.matches;else if((a=r)!=null&&a.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let i=e,o=(l=n)==null?void 0:l.errors;if(o!=null){let c=i.findIndex(f=>f.route.id&&(o==null?void 0:o[f.route.id])!==void 0);c>=0||Y(!1),i=i.slice(0,Math.min(i.length,c+1))}let u=!1,s=-1;if(n&&r&&r.v7_partialHydration)for(let c=0;c<i.length;c++){let f=i[c];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(s=c),f.route.id){let{loaderData:h,errors:k}=n,S=f.route.loader&&h[f.route.id]===void 0&&(!k||k[f.route.id]===void 0);if(f.route.lazy||S){u=!0,s>=0?i=i.slice(0,s+1):i=[i[0]];break}}}return i.reduceRight((c,f,h)=>{let k,S=!1,v=null,P=null;n&&(k=o&&f.route.id?o[f.route.id]:void 0,v=f.route.errorElement||jy,u&&(s<0&&h===0?(Uy("route-fallback"),S=!0,P=null):s===h&&(S=!0,P=f.route.hydrateFallbackElement||null)));let p=t.concat(i.slice(0,h+1)),d=()=>{let y;return k?y=v:S?y=P:f.route.Component?y=N.createElement(f.route.Component,null):f.route.element?y=f.route.element:y=c,N.createElement(Ty,{match:f,routeContext:{outlet:c,matches:p,isDataRoute:n!=null},children:y})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?N.createElement(Ry,{location:n.location,revalidation:n.revalidation,component:v,error:k,children:d(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):d()},null)}var Eh=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Eh||{}),Va=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Va||{});function Dy(e){let t=N.useContext(di);return t||Y(!1),t}function Oy(e){let t=N.useContext(yh);return t||Y(!1),t}function zy(e){let t=N.useContext(vn);return t||Y(!1),t}function Ch(e){let t=zy(),n=t.matches[t.matches.length-1];return n.route.id||Y(!1),n.route.id}function Fy(){var e;let t=N.useContext(vh),n=Oy(Va.UseRouteError),r=Ch(Va.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function Iy(){let{router:e}=Dy(Eh.UseNavigateStable),t=Ch(Va.UseNavigateStable),n=N.useRef(!1);return wh(()=>{n.current=!0}),N.useCallback(function(l,a){a===void 0&&(a={}),n.current&&(typeof l=="number"?e.navigate(l):e.navigate(l,kl({fromRouteId:t},a)))},[e,t])}const Dc={};function Uy(e,t,n){Dc[e]||(Dc[e]=!0)}const Oc={};function By(e,t){Oc[t]||(Oc[t]=!0,console.warn(t))}const Xn=(e,t,n)=>By(e,"⚠️ React Router Future Flag Warning: "+t+". "+("You can use the `"+e+"` future flag to opt-in early. ")+("For more information, see "+n+"."));function Wy(e,t){(e==null?void 0:e.v7_startTransition)===void 0&&Xn("v7_startTransition","React Router will begin wrapping state updates in `React.startTransition` in v7","https://reactrouter.com/v6/upgrading/future#v7_starttransition"),(e==null?void 0:e.v7_relativeSplatPath)===void 0&&(!t||!t.v7_relativeSplatPath)&&Xn("v7_relativeSplatPath","Relative route resolution within Splat routes is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath"),t&&(t.v7_fetcherPersist===void 0&&Xn("v7_fetcherPersist","The persistence behavior of fetchers is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist"),t.v7_normalizeFormMethod===void 0&&Xn("v7_normalizeFormMethod","Casing of `formMethod` fields is being normalized to uppercase in v7","https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod"),t.v7_partialHydration===void 0&&Xn("v7_partialHydration","`RouterProvider` hydration behavior is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_partialhydration"),t.v7_skipActionErrorRevalidation===void 0&&Xn("v7_skipActionErrorRevalidation","The revalidation behavior after 4xx/5xx `action` responses is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation"))}function bo(e){Y(!1)}function $y(e){let{basename:t="/",children:n=null,location:r,navigationType:l=ve.Pop,navigator:a,static:i=!1,future:o}=e;jl()&&Y(!1);let u=t.replace(/^\/*/,"/"),s=N.useMemo(()=>({basename:u,navigator:a,static:i,future:kl({v7_relativeSplatPath:!1},o)}),[u,o,a,i]);typeof r=="string"&&(r=At(r));let{pathname:c="/",search:f="",hash:h="",state:k=null,key:S="default"}=r,v=N.useMemo(()=>{let P=Pr(c,u);return P==null?null:{location:{pathname:P,search:f,hash:h,state:k,key:S},navigationType:l}},[u,c,f,h,k,S,l]);return v==null?null:N.createElement($n.Provider,{value:s},N.createElement(fi.Provider,{children:n,value:v}))}function Ay(e){let{children:t,location:n}=e;return My(Xo(t),n)}new Promise(()=>{});function Xo(e,t){t===void 0&&(t=[]);let n=[];return N.Children.forEach(e,(r,l)=>{if(!N.isValidElement(r))return;let a=[...t,l];if(r.type===N.Fragment){n.push.apply(n,Xo(r.props.children,a));return}r.type!==bo&&Y(!1),!r.props.index||!r.props.children||Y(!1);let i={id:r.props.id||a.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=Xo(r.props.children,a)),n.push(i)}),n}function Hy(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:N.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:N.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:N.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** - * React Router DOM v6.28.2 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Sl(){return Sl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Sl.apply(this,arguments)}function Vy(e,t){if(e==null)return{};var n={},r=Object.keys(e),l,a;for(a=0;a<r.length;a++)l=r[a],!(t.indexOf(l)>=0)&&(n[l]=e[l]);return n}function Yy(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Qy(e,t){return e.button===0&&(!t||t==="_self")&&!Yy(e)}function Ko(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(l=>[n,l]):[[n,r]])},[]))}function by(e,t){let n=Ko(e);return t&&t.forEach((r,l)=>{n.has(l)||t.getAll(l).forEach(a=>{n.append(l,a)})}),n}const Xy=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Ky="6";try{window.__reactRouterVersion=Ky}catch{}function Gy(e,t){return ly({basename:t==null?void 0:t.basename,future:Sl({},t==null?void 0:t.future,{v7_prependBasename:!0}),history:_g({window:t==null?void 0:t.window}),hydrationData:(t==null?void 0:t.hydrationData)||Jy(),routes:e,mapRouteProperties:Hy,dataStrategy:t==null?void 0:t.dataStrategy,patchRoutesOnNavigation:t==null?void 0:t.patchRoutesOnNavigation,window:t==null?void 0:t.window}).initialize()}function Jy(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=Sl({},t,{errors:Zy(t.errors)})),t}function Zy(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,l]of t)if(l&&l.__type==="RouteErrorResponse")n[r]=new Ha(l.status,l.statusText,l.data,l.internal===!0);else if(l&&l.__type==="Error"){if(l.__subType){let a=window[l.__subType];if(typeof a=="function")try{let i=new a(l.message);i.stack="",n[r]=i}catch{}}if(n[r]==null){let a=new Error(l.message);a.stack="",n[r]=a}}else n[r]=l;return n}const qy=N.createContext({isTransitioning:!1}),ev=N.createContext(new Map),tv="startTransition",zc=gp[tv],nv="flushSync",Fc=Mg[nv];function rv(e){zc?zc(e):e()}function Wr(e){Fc?Fc(e):e()}class lv{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function av(e){let{fallbackElement:t,router:n,future:r}=e,[l,a]=N.useState(n.state),[i,o]=N.useState(),[u,s]=N.useState({isTransitioning:!1}),[c,f]=N.useState(),[h,k]=N.useState(),[S,v]=N.useState(),P=N.useRef(new Map),{v7_startTransition:p}=r||{},d=N.useCallback(j=>{p?rv(j):j()},[p]),y=N.useCallback((j,B)=>{let{deletedFetchers:U,flushSync:te,viewTransitionOpts:ce}=B;j.fetchers.forEach((ke,Ht)=>{ke.data!==void 0&&P.current.set(Ht,ke.data)}),U.forEach(ke=>P.current.delete(ke));let xe=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!ce||xe){te?Wr(()=>a(j)):d(()=>a(j));return}if(te){Wr(()=>{h&&(c&&c.resolve(),h.skipTransition()),s({isTransitioning:!0,flushSync:!0,currentLocation:ce.currentLocation,nextLocation:ce.nextLocation})});let ke=n.window.document.startViewTransition(()=>{Wr(()=>a(j))});ke.finished.finally(()=>{Wr(()=>{f(void 0),k(void 0),o(void 0),s({isTransitioning:!1})})}),Wr(()=>k(ke));return}h?(c&&c.resolve(),h.skipTransition(),v({state:j,currentLocation:ce.currentLocation,nextLocation:ce.nextLocation})):(o(j),s({isTransitioning:!0,flushSync:!1,currentLocation:ce.currentLocation,nextLocation:ce.nextLocation}))},[n.window,h,c,P,d]);N.useLayoutEffect(()=>n.subscribe(y),[n,y]),N.useEffect(()=>{u.isTransitioning&&!u.flushSync&&f(new lv)},[u]),N.useEffect(()=>{if(c&&i&&n.window){let j=i,B=c.promise,U=n.window.document.startViewTransition(async()=>{d(()=>a(j)),await B});U.finished.finally(()=>{f(void 0),k(void 0),o(void 0),s({isTransitioning:!1})}),k(U)}},[d,i,c,n.window]),N.useEffect(()=>{c&&i&&l.location.key===i.location.key&&c.resolve()},[c,h,l.location,i]),N.useEffect(()=>{!u.isTransitioning&&S&&(o(S.state),s({isTransitioning:!0,flushSync:!1,currentLocation:S.currentLocation,nextLocation:S.nextLocation}),v(void 0))},[u.isTransitioning,S]),N.useEffect(()=>{},[]);let C=N.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:j=>n.navigate(j),push:(j,B,U)=>n.navigate(j,{state:B,preventScrollReset:U==null?void 0:U.preventScrollReset}),replace:(j,B,U)=>n.navigate(j,{replace:!0,state:B,preventScrollReset:U==null?void 0:U.preventScrollReset})}),[n]),R=n.basename||"/",w=N.useMemo(()=>({router:n,navigator:C,static:!1,basename:R}),[n,C,R]),T=N.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return N.useEffect(()=>Wy(r,n.future),[r,n.future]),N.createElement(N.Fragment,null,N.createElement(di.Provider,{value:w},N.createElement(yh.Provider,{value:l},N.createElement(ev.Provider,{value:P.current},N.createElement(qy.Provider,{value:u},N.createElement($y,{basename:R,location:l.location,navigationType:l.historyAction,navigator:C,future:T},l.initialized||n.future.v7_partialHydration?N.createElement(iv,{routes:n.routes,future:n.future,state:l}):t))))),null)}const iv=N.memo(ov);function ov(e){let{routes:t,future:n,state:r}=e;return Sh(t,void 0,r,n)}const uv=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",sv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rn=N.forwardRef(function(t,n){let{onClick:r,relative:l,reloadDocument:a,replace:i,state:o,target:u,to:s,preventScrollReset:c,viewTransition:f}=t,h=Vy(t,Xy),{basename:k}=N.useContext($n),S,v=!1;if(typeof s=="string"&&sv.test(s)&&(S=s,uv))try{let y=new URL(window.location.href),C=s.startsWith("//")?new URL(y.protocol+s):new URL(s),R=Pr(C.pathname,k);C.origin===y.origin&&R!=null?s=R+C.search+C.hash:v=!0}catch{}let P=Cy(s,{relative:l}),p=cv(s,{replace:i,state:o,target:u,preventScrollReset:c,relative:l,viewTransition:f});function d(y){r&&r(y),y.defaultPrevented||p(y)}return N.createElement("a",Sl({},h,{href:S||P,onClick:v||a?r:d,ref:n,target:u}))});var Ic;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Ic||(Ic={}));var Uc;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Uc||(Uc={}));function cv(e,t){let{target:n,replace:r,state:l,preventScrollReset:a,relative:i,viewTransition:o}=t===void 0?{}:t,u=xh(),s=Rl(),c=kh(e,{relative:i});return N.useCallback(f=>{if(Qy(f,n)){f.preventDefault();let h=r!==void 0?r:Un(s)===Un(c);u(e,{replace:h,state:l,preventScrollReset:a,relative:i,viewTransition:o})}},[s,u,c,r,l,n,e,a,i,o])}function dv(e){let t=N.useRef(Ko(e)),n=N.useRef(!1),r=Rl(),l=N.useMemo(()=>by(r.search,n.current?null:t.current),[r.search]),a=xh(),i=N.useCallback((o,u)=>{const s=Ko(typeof o=="function"?o(l):o);n.current=!0,a("?"+s,u)},[a,l]);return[l,i]}function jt(e){if(e===0)return"0 B";const t=1024,n=["B","KiB","MiB","GiB","TiB"],r=Math.floor(Math.log(e)/Math.log(t));return`${(e/Math.pow(t,r)).toFixed(2)} ${n[r]}`}const Ph=6048e5,fv=864e5,na=43200,Bc=1440,Wc=Symbol.for("constructDateFrom");function Wt(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Wc in e?e[Wc](t):e instanceof Date?new e.constructor(t):new Date(t)}function Re(e,t){return Wt(t||e,e)}let hv={};function Tl(){return hv}function El(e,t){var o,u,s,c;const n=Tl(),r=(t==null?void 0:t.weekStartsOn)??((u=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:u.weekStartsOn)??n.weekStartsOn??((c=(s=n.locale)==null?void 0:s.options)==null?void 0:c.weekStartsOn)??0,l=Re(e,t==null?void 0:t.in),a=l.getDay(),i=(a<r?7:0)+a-r;return l.setDate(l.getDate()-i),l.setHours(0,0,0,0),l}function Ya(e,t){return El(e,{...t,weekStartsOn:1})}function Nh(e,t){const n=Re(e,t==null?void 0:t.in),r=n.getFullYear(),l=Wt(n,0);l.setFullYear(r+1,0,4),l.setHours(0,0,0,0);const a=Ya(l),i=Wt(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const o=Ya(i);return n.getTime()>=a.getTime()?r+1:n.getTime()>=o.getTime()?r:r-1}function Qa(e){const t=Re(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function hi(e,...t){const n=Wt.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function $c(e,t){const n=Re(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function pv(e,t,n){const[r,l]=hi(n==null?void 0:n.in,e,t),a=$c(r),i=$c(l),o=+a-Qa(a),u=+i-Qa(i);return Math.round((o-u)/fv)}function mv(e,t){const n=Nh(e,t),r=Wt(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Ya(r)}function ya(e,t){const n=+Re(e)-+Re(t);return n<0?-1:n>0?1:n}function gv(e){return Wt(e,Date.now())}function yv(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function vv(e){return!(!yv(e)&&typeof e!="number"||isNaN(+Re(e)))}function wv(e,t,n){const[r,l]=hi(n==null?void 0:n.in,e,t),a=r.getFullYear()-l.getFullYear(),i=r.getMonth()-l.getMonth();return a*12+i}function xv(e){return t=>{const r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function kv(e,t){return+Re(e)-+Re(t)}function Sv(e,t){const n=Re(e,t==null?void 0:t.in);return n.setHours(23,59,59,999),n}function Ev(e,t){const n=Re(e,t==null?void 0:t.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function Cv(e,t){const n=Re(e,t==null?void 0:t.in);return+Sv(n,t)==+Ev(n,t)}function Pv(e,t,n){const[r,l,a]=hi(n==null?void 0:n.in,e,e,t),i=ya(l,a),o=Math.abs(wv(l,a));if(o<1)return 0;l.getMonth()===1&&l.getDate()>27&&l.setDate(30),l.setMonth(l.getMonth()-i*o);let u=ya(l,a)===-i;Cv(r)&&o===1&&ya(r,a)===1&&(u=!1);const s=i*(o-+u);return s===0?0:s}function Nv(e,t,n){const r=kv(e,t)/1e3;return xv(n==null?void 0:n.roundingMethod)(r)}function Mv(e,t){const n=Re(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const _v={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},jv=(e,t,n)=>{let r;const l=_v[e];return typeof l=="string"?r=l:t===1?r=l.one:r=l.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Xi(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const Rv={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Tv={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Lv={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Dv={date:Xi({formats:Rv,defaultWidth:"full"}),time:Xi({formats:Tv,defaultWidth:"full"}),dateTime:Xi({formats:Lv,defaultWidth:"full"})},Ov={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},zv=(e,t,n,r)=>Ov[e];function $r(e){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let l;if(r==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,o=n!=null&&n.width?String(n.width):i;l=e.formattingValues[o]||e.formattingValues[i]}else{const i=e.defaultWidth,o=n!=null&&n.width?String(n.width):e.defaultWidth;l=e.values[o]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return l[a]}}const Fv={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Iv={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Uv={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Bv={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Wv={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},$v={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Av=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},Hv={ordinalNumber:Av,era:$r({values:Fv,defaultWidth:"wide"}),quarter:$r({values:Iv,defaultWidth:"wide",argumentCallback:e=>e-1}),month:$r({values:Uv,defaultWidth:"wide"}),day:$r({values:Bv,defaultWidth:"wide"}),dayPeriod:$r({values:Wv,defaultWidth:"wide",formattingValues:$v,defaultFormattingWidth:"wide"})};function Ar(e){return(t,n={})=>{const r=n.width,l=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],a=t.match(l);if(!a)return null;const i=a[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],u=Array.isArray(o)?Yv(o,f=>f.test(i)):Vv(o,f=>f.test(i));let s;s=e.valueCallback?e.valueCallback(u):u,s=n.valueCallback?n.valueCallback(s):s;const c=t.slice(i.length);return{value:s,rest:c}}}function Vv(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function Yv(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Qv(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const l=r[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=n.valueCallback?n.valueCallback(i):i;const o=t.slice(l.length);return{value:i,rest:o}}}const bv=/^(\d+)(th|st|nd|rd)?/i,Xv=/\d+/i,Kv={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Gv={any:[/^b/i,/^(a|c)/i]},Jv={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Zv={any:[/1/i,/2/i,/3/i,/4/i]},qv={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},e0={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},t0={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},n0={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},r0={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},l0={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},a0={ordinalNumber:Qv({matchPattern:bv,parsePattern:Xv,valueCallback:e=>parseInt(e,10)}),era:Ar({matchPatterns:Kv,defaultMatchWidth:"wide",parsePatterns:Gv,defaultParseWidth:"any"}),quarter:Ar({matchPatterns:Jv,defaultMatchWidth:"wide",parsePatterns:Zv,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ar({matchPatterns:qv,defaultMatchWidth:"wide",parsePatterns:e0,defaultParseWidth:"any"}),day:Ar({matchPatterns:t0,defaultMatchWidth:"wide",parsePatterns:n0,defaultParseWidth:"any"}),dayPeriod:Ar({matchPatterns:r0,defaultMatchWidth:"any",parsePatterns:l0,defaultParseWidth:"any"})},Mh={code:"en-US",formatDistance:jv,formatLong:Dv,formatRelative:zv,localize:Hv,match:a0,options:{weekStartsOn:0,firstWeekContainsDate:1}};function i0(e,t){const n=Re(e,t==null?void 0:t.in);return pv(n,Mv(n))+1}function o0(e,t){const n=Re(e,t==null?void 0:t.in),r=+Ya(n)-+mv(n);return Math.round(r/Ph)+1}function _h(e,t){var c,f,h,k;const n=Re(e,t==null?void 0:t.in),r=n.getFullYear(),l=Tl(),a=(t==null?void 0:t.firstWeekContainsDate)??((f=(c=t==null?void 0:t.locale)==null?void 0:c.options)==null?void 0:f.firstWeekContainsDate)??l.firstWeekContainsDate??((k=(h=l.locale)==null?void 0:h.options)==null?void 0:k.firstWeekContainsDate)??1,i=Wt((t==null?void 0:t.in)||e,0);i.setFullYear(r+1,0,a),i.setHours(0,0,0,0);const o=El(i,t),u=Wt((t==null?void 0:t.in)||e,0);u.setFullYear(r,0,a),u.setHours(0,0,0,0);const s=El(u,t);return+n>=+o?r+1:+n>=+s?r:r-1}function u0(e,t){var o,u,s,c;const n=Tl(),r=(t==null?void 0:t.firstWeekContainsDate)??((u=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:u.firstWeekContainsDate)??n.firstWeekContainsDate??((c=(s=n.locale)==null?void 0:s.options)==null?void 0:c.firstWeekContainsDate)??1,l=_h(e,t),a=Wt((t==null?void 0:t.in)||e,0);return a.setFullYear(l,0,r),a.setHours(0,0,0,0),El(a,t)}function s0(e,t){const n=Re(e,t==null?void 0:t.in),r=+El(n,t)-+u0(n,t);return Math.round(r/Ph)+1}function q(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Xt={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return q(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):q(n+1,2)},d(e,t){return q(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return q(e.getHours()%12||12,t.length)},H(e,t){return q(e.getHours(),t.length)},m(e,t){return q(e.getMinutes(),t.length)},s(e,t){return q(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),l=Math.trunc(r*Math.pow(10,n-3));return q(l,t.length)}},Kn={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ac={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),l=r>0?r:1-r;return n.ordinalNumber(l,{unit:"year"})}return Xt.y(e,t)},Y:function(e,t,n,r){const l=_h(e,r),a=l>0?l:1-l;if(t==="YY"){const i=a%100;return q(i,2)}return t==="Yo"?n.ordinalNumber(a,{unit:"year"}):q(a,t.length)},R:function(e,t){const n=Nh(e);return q(n,t.length)},u:function(e,t){const n=e.getFullYear();return q(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return q(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return q(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return Xt.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return q(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const l=s0(e,r);return t==="wo"?n.ordinalNumber(l,{unit:"week"}):q(l,t.length)},I:function(e,t,n){const r=o0(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):q(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):Xt.d(e,t)},D:function(e,t,n){const r=i0(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):q(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const l=e.getDay(),a=(l-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return q(a,2);case"eo":return n.ordinalNumber(a,{unit:"day"});case"eee":return n.day(l,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(l,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(l,{width:"short",context:"formatting"});case"eeee":default:return n.day(l,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const l=e.getDay(),a=(l-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return q(a,t.length);case"co":return n.ordinalNumber(a,{unit:"day"});case"ccc":return n.day(l,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(l,{width:"narrow",context:"standalone"});case"cccccc":return n.day(l,{width:"short",context:"standalone"});case"cccc":default:return n.day(l,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),l=r===0?7:r;switch(t){case"i":return String(l);case"ii":return q(l,t.length);case"io":return n.ordinalNumber(l,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const l=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(l,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(l,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(l,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let l;switch(r===12?l=Kn.noon:r===0?l=Kn.midnight:l=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(l,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(l,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(l,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let l;switch(r>=17?l=Kn.evening:r>=12?l=Kn.afternoon:r>=4?l=Kn.morning:l=Kn.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(l,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(l,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Xt.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Xt.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):q(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):q(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xt.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Xt.s(e,t)},S:function(e,t){return Xt.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Vc(r);case"XXXX":case"XX":return Cn(r);case"XXXXX":case"XXX":default:return Cn(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return Vc(r);case"xxxx":case"xx":return Cn(r);case"xxxxx":case"xxx":default:return Cn(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Hc(r,":");case"OOOO":default:return"GMT"+Cn(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Hc(r,":");case"zzzz":default:return"GMT"+Cn(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return q(r,t.length)},T:function(e,t,n){return q(+e,t.length)}};function Hc(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),l=Math.trunc(r/60),a=r%60;return a===0?n+String(l):n+String(l)+t+q(a,2)}function Vc(e,t){return e%60===0?(e>0?"-":"+")+q(Math.abs(e)/60,2):Cn(e,t)}function Cn(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),l=q(Math.trunc(r/60),2),a=q(r%60,2);return n+l+t+a}const Yc=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},jh=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},c0=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],l=n[2];if(!l)return Yc(e,t);let a;switch(r){case"P":a=t.dateTime({width:"short"});break;case"PP":a=t.dateTime({width:"medium"});break;case"PPP":a=t.dateTime({width:"long"});break;case"PPPP":default:a=t.dateTime({width:"full"});break}return a.replace("{{date}}",Yc(r,t)).replace("{{time}}",jh(l,t))},d0={p:jh,P:c0},f0=/^D+$/,h0=/^Y+$/,p0=["D","DD","YY","YYYY"];function m0(e){return f0.test(e)}function g0(e){return h0.test(e)}function y0(e,t,n){const r=v0(e,t,n);if(console.warn(r),p0.includes(e))throw new RangeError(r)}function v0(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const w0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,x0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,k0=/^'([^]*?)'?$/,S0=/''/g,E0=/[a-zA-Z]/;function Qc(e,t,n){var c,f,h,k;const r=Tl(),l=r.locale??Mh,a=r.firstWeekContainsDate??((f=(c=r.locale)==null?void 0:c.options)==null?void 0:f.firstWeekContainsDate)??1,i=r.weekStartsOn??((k=(h=r.locale)==null?void 0:h.options)==null?void 0:k.weekStartsOn)??0,o=Re(e,n==null?void 0:n.in);if(!vv(o))throw new RangeError("Invalid time value");let u=t.match(x0).map(S=>{const v=S[0];if(v==="p"||v==="P"){const P=d0[v];return P(S,l.formatLong)}return S}).join("").match(w0).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const v=S[0];if(v==="'")return{isToken:!1,value:C0(S)};if(Ac[v])return{isToken:!0,value:S};if(v.match(E0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+v+"`");return{isToken:!1,value:S}});l.localize.preprocessor&&(u=l.localize.preprocessor(o,u));const s={firstWeekContainsDate:a,weekStartsOn:i,locale:l};return u.map(S=>{if(!S.isToken)return S.value;const v=S.value;(g0(v)||m0(v))&&y0(v,t,String(e));const P=Ac[v[0]];return P(o,v,l.localize,s)}).join("")}function C0(e){const t=e.match(k0);return t?t[1].replace(S0,"'"):e}function P0(e,t,n){const r=Tl(),l=(n==null?void 0:n.locale)??r.locale??Mh,a=2520,i=ya(e,t);if(isNaN(i))throw new RangeError("Invalid time value");const o=Object.assign({},n,{addSuffix:n==null?void 0:n.addSuffix,comparison:i}),[u,s]=hi(n==null?void 0:n.in,...i>0?[t,e]:[e,t]),c=Nv(s,u),f=(Qa(s)-Qa(u))/1e3,h=Math.round((c-f)/60);let k;if(h<2)return n!=null&&n.includeSeconds?c<5?l.formatDistance("lessThanXSeconds",5,o):c<10?l.formatDistance("lessThanXSeconds",10,o):c<20?l.formatDistance("lessThanXSeconds",20,o):c<40?l.formatDistance("halfAMinute",0,o):c<60?l.formatDistance("lessThanXMinutes",1,o):l.formatDistance("xMinutes",1,o):h===0?l.formatDistance("lessThanXMinutes",1,o):l.formatDistance("xMinutes",h,o);if(h<45)return l.formatDistance("xMinutes",h,o);if(h<90)return l.formatDistance("aboutXHours",1,o);if(h<Bc){const S=Math.round(h/60);return l.formatDistance("aboutXHours",S,o)}else{if(h<a)return l.formatDistance("xDays",1,o);if(h<na){const S=Math.round(h/Bc);return l.formatDistance("xDays",S,o)}else if(h<na*2)return k=Math.round(h/na),l.formatDistance("aboutXMonths",k,o)}if(k=Pv(s,u),k<12){const S=Math.round(h/na);return l.formatDistance("xMonths",S,o)}else{const S=k%12,v=Math.trunc(k/12);return S<3?l.formatDistance("aboutXYears",v,o):S<9?l.formatDistance("overXYears",v,o):l.formatDistance("almostXYears",v+1,o)}}function N0(e,t){return P0(e,gv(e),t)}const Rh=({date:e,className:t=""})=>{const[n,r]=Ne.useState(!1),l=N0(e,{addSuffix:!0}),a=Qc(e,"yyyy-MM-dd HH:mm:ss"),i=Qc(new Date(e.getTime()+e.getTimezoneOffset()*6e4),"yyyy-MM-dd HH:mm:ss"),[o,u]=Ne.useState({top:0,left:0}),s=Ne.useRef(null),c=Ne.useCallback(()=>{if(s.current){const f=s.current.getBoundingClientRect();u({top:f.top+window.scrollY-70,left:f.left+window.scrollX})}},[]);return Ne.useEffect(()=>(n&&(c(),window.addEventListener("scroll",c),window.addEventListener("resize",c)),()=>{window.removeEventListener("scroll",c),window.removeEventListener("resize",c)}),[n,c]),g.jsxs(g.Fragment,{children:[g.jsx("div",{ref:s,className:`inline-block ${t}`,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:l}),n&&si.createPortal(g.jsx("div",{style:{position:"absolute",top:`${o.top}px`,left:`${o.left}px`},className:"z-[9999] min-w-[280px] text-sm text-gray-500 bg-white border border-gray-200 rounded-lg shadow-sm dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800",children:g.jsxs("div",{className:"px-3 py-2 space-y-2",children:[g.jsxs("div",{className:"flex items-center gap-3",children:[g.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"UTC"}),g.jsx("span",{className:"font-mono",children:i})]}),g.jsxs("div",{className:"flex items-center gap-3",children:[g.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"Local"}),g.jsx("span",{className:"font-mono",children:a})]})]})}),document.body)]})},Th=N.createContext(void 0);function pi(){const e=N.useContext(Th);if(e===void 0)throw new Error("useBasename must be used within a BasenameProvider");return e.basename}function M0({basename:e,children:t}){return g.jsx(Th.Provider,{value:{basename:e},children:t})}const ra=({compressed:e,uncompressed:t,showVisualization:n=!1})=>{if(e===0||t===0)return g.jsx("span",{className:"dark:text-gray-200",children:"-"});const r=t/e,l=r>1;return g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsxs("div",{className:"font-medium whitespace-nowrap dark:text-gray-200",children:[r.toFixed(1),"x"]}),n&&l&&g.jsx("div",{className:"flex-1 h-2.5 bg-gray-100 dark:bg-gray-600 border border-gray-200 dark:border-gray-500 rounded relative",children:g.jsx("div",{className:"absolute inset-y-0 left-0 bg-blue-600 dark:bg-blue-500 rounded",style:{width:`${e/t*100}%`}})})]})},_0=({metadata:e,filename:t,className:n=""})=>{const[r,l]=N.useState(null),[a,i]=N.useState({});if(e.error)return g.jsxs("div",{className:"p-4 bg-red-100 border border-red-400 text-red-700 rounded",children:["Error: ",e.error]});const o=v=>{l(r===v?null:v)},u=(v,P)=>{const p=`${v}-${P}`;i(d=>({...d,[p]:!d[p]}))},s=e.sections.reduce((v,P)=>v+P.totalCompressedSize,0),c=e.sections.reduce((v,P)=>v+P.totalUncompressedSize,0),f=e.sections.filter(v=>v.type==="SECTION_TYPE_STREAMS"),h=e.sections.filter(v=>v.type==="SECTION_TYPE_LOGS"),k=f==null?void 0:f.reduce((v,P)=>v+(P.columns[0].rows_count||0),0),S=h==null?void 0:h.reduce((v,P)=>v+(P.columns[0].rows_count||0),0);return pi(),g.jsx("div",{className:`space-y-6 p-4 ${n}`,children:g.jsxs("div",{className:"bg-white dark:bg-gray-700 shadow rounded-lg",children:[g.jsxs("div",{className:"p-4 border-b dark:border-gray-700",children:[g.jsxs("div",{className:"flex justify-between items-start mb-4",children:[g.jsxs("div",{children:[g.jsx("h2",{className:"text-lg font-semibold mb-2 dark:text-gray-200",children:"Thor Dataobj File"}),g.jsxs("div",{className:"flex flex-col gap-1",children:[g.jsx("p",{className:"text-sm font-mono dark:text-gray-300",children:t}),e.lastModified&&g.jsxs("div",{className:"text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2",children:[g.jsx("span",{children:"Last modified:"}),g.jsx(Rh,{date:new Date(e.lastModified)})]})]})]}),g.jsx(rn,{to:`/api/download?file=${encodeURIComponent(t)}`,target:"_blank",rel:"noopener noreferrer",className:"px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm",children:"Download"})]}),g.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Compression"}),g.jsx(ra,{compressed:s,uncompressed:c,showVisualization:!0}),g.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[jt(s)," →"," ",jt(c)]})]}),g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Sections"}),g.jsx("div",{className:"font-medium",children:e.sections.length}),g.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:e.sections.map(v=>v.type).join(", ")})]}),k&&g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Stream Count"}),g.jsx("div",{className:"font-medium",children:k.toLocaleString()})]}),S&&g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Log Count"}),g.jsx("div",{className:"font-medium",children:S.toLocaleString()})]})]})]}),g.jsx("div",{className:"divide-y dark:divide-gray-900",children:e.sections.map((v,P)=>g.jsxs("div",{className:"dark:bg-gray-700",children:[g.jsxs("div",{className:"p-4 cursor-pointer flex justify-between items-center hover:bg-gray-50 dark:hover:bg-gray-700",onClick:()=>o(P),children:[g.jsxs("h3",{className:"text-lg font-semibold dark:text-gray-200",children:["Section #",P+1,": ",v.type]}),g.jsx("svg",{className:`w-5 h-5 transform transition-transform duration-700 ${r===P?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]}),g.jsx("div",{className:`transition-all duration-700 ease-in-out ${r===P?"opacity-100":"opacity-0 hidden"}`,children:g.jsxs("div",{className:"p-4 bg-gray-50 dark:bg-gray-800",children:[g.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mb-6",children:[g.jsxs("div",{className:"bg-white dark:bg-gray-700 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Compression"}),g.jsx(ra,{compressed:v.totalCompressedSize,uncompressed:v.totalUncompressedSize,showVisualization:!0}),g.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[jt(v.totalCompressedSize)," →"," ",jt(v.totalUncompressedSize)]})]}),g.jsxs("div",{className:"bg-white dark:bg-gray-700 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Column Count"}),g.jsx("div",{className:"font-medium",children:v.columnCount})]}),g.jsxs("div",{className:"bg-white dark:bg-gray-700 p-3 rounded",children:[g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Type"}),g.jsx("div",{className:"font-medium",children:v.type})]})]}),g.jsxs("div",{className:"space-y-4",children:[g.jsxs("h4",{className:"font-medium text-lg mb-4 dark:text-gray-200",children:["Columns (",v.columnCount,")"]}),v.columns.map((p,d)=>g.jsxs("div",{className:"bg-white dark:bg-gray-700 shadow rounded-lg overflow-hidden",children:[g.jsxs("div",{className:"flex justify-between items-center cursor-pointer p-4 border-b dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600",onClick:()=>u(P,d),children:[g.jsxs("div",{children:[g.jsx("h5",{className:"font-medium text-gray-900 dark:text-gray-200",children:p.name?`${p.name} (${p.type})`:p.type}),g.jsxs("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Type: ",p.value_type]})]}),g.jsxs("div",{className:"flex items-center",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-600 dark:text-gray-300 mr-4",children:["Compression: ",p.compression]}),g.jsx("svg",{className:`w-4 h-4 transform transition-transform text-gray-400 ${a[`${P}-${d}`]?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]})]}),a[`${P}-${d}`]&&g.jsxs("div",{className:"p-4 bg-white dark:bg-gray-700",children:[g.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-600 p-3 rounded-lg",children:[g.jsxs("div",{className:"text-gray-500 dark:text-gray-400 mb-1",children:["Compression (",p.compression,")"]}),g.jsx("div",{className:"font-medium whitespace-nowrap",children:g.jsx(ra,{compressed:p.compressed_size,uncompressed:p.uncompressed_size})}),g.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[jt(p.compressed_size)," →"," ",jt(p.uncompressed_size)]})]}),g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-600 p-3 rounded-lg",children:[g.jsx("div",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"Rows"}),g.jsx("div",{className:"font-medium",children:p.rows_count.toLocaleString()})]}),g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-600 p-3 rounded-lg",children:[g.jsx("div",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"Values Count"}),g.jsx("div",{className:"font-medium",children:p.values_count.toLocaleString()})]}),g.jsxs("div",{className:"bg-gray-50 dark:bg-gray-600 p-3 rounded-lg",children:[g.jsx("div",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"Offset"}),g.jsx("div",{className:"font-medium",children:jt(p.metadata_offset)})]})]}),p.pages.length>0&&g.jsxs("div",{className:"mt-6",children:[g.jsxs("h6",{className:"font-medium text-sm mb-3 dark:text-gray-200",children:["Pages (",p.pages.length,")"]}),g.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-600",children:g.jsxs("table",{className:"min-w-full text-sm",children:[g.jsx("thead",{children:g.jsxs("tr",{className:"bg-gray-50 dark:bg-gray-600 border-b border-gray-200 dark:border-gray-500",children:[g.jsx("th",{className:"text-left p-3 font-medium text-gray-600 dark:text-gray-200",children:"#"}),g.jsx("th",{className:"text-left p-3 font-medium text-gray-600 dark:text-gray-200",children:"Rows"}),g.jsx("th",{className:"text-left p-3 font-medium text-gray-600 dark:text-gray-200",children:"Values"}),g.jsx("th",{className:"text-left p-3 font-medium text-gray-600 dark:text-gray-200",children:"Encoding"}),g.jsx("th",{className:"text-left p-3 font-medium text-gray-600 dark:text-gray-200",children:"Compression"})]})}),g.jsx("tbody",{className:"bg-white dark:bg-gray-700",children:p.pages.map((y,C)=>g.jsxs("tr",{className:"border-t border-gray-100 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600",children:[g.jsx("td",{className:"p-3 dark:text-gray-200",children:C+1}),g.jsx("td",{className:"p-3 dark:text-gray-200",children:y.rows_count.toLocaleString()}),g.jsx("td",{className:"p-3 dark:text-gray-200",children:y.values_count.toLocaleString()}),g.jsx("td",{className:"p-3 dark:text-gray-200",children:y.encoding}),g.jsx("td",{className:"p-3",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx(ra,{compressed:y.compressed_size,uncompressed:y.uncompressed_size}),g.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",jt(y.compressed_size)," ","→"," ",jt(y.uncompressed_size),")"]})]})})]},C))})]})})]})]})]},d))]})]})})]},P))})]})})},j0=({isDarkMode:e,onToggle:t})=>g.jsx("button",{onClick:t,className:"p-2 rounded-lg bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors","aria-label":e?"Switch to light mode":"Switch to dark mode",children:e?g.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}):g.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"})})}),R0=e=>{switch(e){case"S3":return{bg:"bg-orange-100",text:"text-orange-800",darkBg:"dark:bg-orange-900",darkText:"dark:text-orange-300"};case"GCS":return{bg:"bg-blue-100",text:"text-blue-800",darkBg:"dark:bg-blue-900",darkText:"dark:text-blue-300"};case"AZURE":return{bg:"bg-sky-100",text:"text-sky-800",darkBg:"dark:bg-sky-900",darkText:"dark:text-sky-300"};case"SWIFT":return{bg:"bg-red-100",text:"text-red-800",darkBg:"dark:bg-red-900",darkText:"dark:text-red-300"};case"COS":return{bg:"bg-purple-100",text:"text-purple-800",darkBg:"dark:bg-purple-900",darkText:"dark:text-purple-300"};case"ALIYUNOSS":return{bg:"bg-rose-100",text:"text-rose-800",darkBg:"dark:bg-rose-900",darkText:"dark:text-rose-300"};case"OCI":return{bg:"bg-red-100",text:"text-red-800",darkBg:"dark:bg-red-900",darkText:"dark:text-red-300"};case"OBS":return{bg:"bg-cyan-100",text:"text-cyan-800",darkBg:"dark:bg-cyan-900",darkText:"dark:text-cyan-300"};case"FILESYSTEM":return{bg:"bg-green-100",text:"text-green-800",darkBg:"dark:bg-green-900",darkText:"dark:text-green-300"};case"MEMORY":return{bg:"bg-yellow-100",text:"text-yellow-800",darkBg:"dark:bg-yellow-900",darkText:"dark:text-yellow-300"};default:return{bg:"bg-gray-100",text:"text-gray-800",darkBg:"dark:bg-gray-700",darkText:"dark:text-gray-300"}}},T0=({parts:e,isLastPartClickable:t=!1})=>{const[n,r]=Ne.useState(""),l=pi();Ne.useEffect(()=>{fetch(`${l}api/provider`).then(i=>i.json()).then(i=>r(i.provider)).catch(console.error)},[l]);const a=R0(n);return g.jsx("nav",{className:"flex mb-4","aria-label":"Breadcrumb",children:g.jsxs("ol",{className:"inline-flex items-center space-x-1 md:space-x-3",children:[g.jsx("li",{className:"inline-flex items-center",children:n&&g.jsxs(rn,{to:"/",className:`inline-flex items-center h-7 gap-2 px-3 py-1 text-xs font-medium ${a.bg} ${a.text} ${a.darkBg} ${a.darkText} rounded-full hover:ring-2 hover:ring-gray-300 dark:hover:ring-gray-600 transition-all duration-200`,children:[g.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",className:"w-4 h-4",fill:"currentColor",children:g.jsx("path",{d:"M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z"})}),n]})}),e.map((i,o,u)=>g.jsx("li",{children:g.jsxs("div",{className:"flex items-center",children:[g.jsx("svg",{className:"w-3 h-3 text-gray-400 mx-1","aria-hidden":"true",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 6 10",children:g.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"m1 9 4-4-4-4"})}),!t&&o===u.length-1?g.jsx("span",{className:"ml-1 text-sm font-medium text-gray-500 md:ml-2",children:i}):g.jsx(rn,{to:`/?path=${encodeURIComponent(u.slice(0,o+1).join("/"))}`,className:"ml-1 text-sm font-medium text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 md:ml-2",children:i})]})},o))]})})},L0=()=>{const[e,t]=N.useState(!1);N.useEffect(()=>{const r=()=>{t(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return e?g.jsx("button",{onClick:n,className:"fixed bottom-8 right-8 bg-blue-500 dark:bg-blue-600 hover:bg-blue-600 dark:hover:bg-blue-700 text-white rounded-full p-3 shadow-lg transition-all duration-300","aria-label":"Back to top",children:g.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 10l7-7m0 0l7 7m-7-7v18"})})}):null},Lh=({children:e,breadcrumbParts:t=[],isLastBreadcrumbClickable:n=!0})=>{const[r,l]=N.useState(()=>{const a=localStorage.getItem("theme"),i=window.matchMedia("(prefers-color-scheme: dark)").matches;return a?a==="dark":i});return N.useEffect(()=>{document.documentElement.classList.toggle("dark",r),localStorage.setItem("theme",r?"dark":"light")},[r]),g.jsx("div",{className:`min-h-screen ${r?"dark:bg-gray-900 dark:text-gray-200":"bg-white text-black"}`,children:g.jsxs("div",{className:"container mx-auto px-4 py-8",children:[g.jsxs("div",{className:"flex justify-between items-center mb-6",children:[g.jsx(T0,{parts:t,isLastPartClickable:n}),g.jsx(j0,{isDarkMode:r,onToggle:()=>l(!r)})]}),e,g.jsx(L0,{})]})})},D0=({filePath:e})=>g.jsxs(rn,{to:`/?path=${encodeURIComponent(e?e.split("/").slice(0,-1).join("/"):"")}`,className:"mb-4 p-4 inline-flex items-center text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300",children:[g.jsx("svg",{className:"w-4 h-4 mr-1",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M15 19l-7-7 7-7"})}),"Back to file list"]}),Dh=({fullScreen:e=!1})=>g.jsx("div",{className:`flex items-center justify-center ${e?"min-h-screen":"min-h-[200px]"} dark:bg-gray-900`,children:g.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500 dark:border-blue-400"})}),Oh=({message:e,fullScreen:t=!1})=>g.jsx("div",{className:`flex items-center justify-center ${t?"min-h-screen":""}`,children:g.jsxs("div",{className:"text-red-500 p-4",children:["Error: ",e]})}),O0=e=>{const[t,n]=Ne.useState(null),[r,l]=Ne.useState(!0),[a,i]=Ne.useState(null),o=pi();return Ne.useEffect(()=>{(async()=>{if(e)try{l(!0);const s=await fetch(`${o}api/inspect?file=${encodeURIComponent(e)}`);if(!s.ok)throw new Error(`Failed to fetch metadata: ${s.statusText}`);const c=await s.json();n(c),i(null)}catch(s){i(s instanceof Error?s.message:"An error occurred")}finally{l(!1)}})()},[e,o]),{metadata:t,loading:r,error:a}},zh=()=>{const{filePath:e}=Ny(),{metadata:t,loading:n,error:r}=O0(e),l=Ne.useMemo(()=>(e||"").split("/").filter(Boolean),[e]);return g.jsx(Lh,{breadcrumbParts:l,isLastBreadcrumbClickable:!1,children:g.jsx("div",{className:"bg-gray-50 dark:bg-gray-800 shadow-md rounded-lg overflow-hidden dark:text-gray-200",children:n?g.jsx(Dh,{}):r?g.jsx(Oh,{message:r}):g.jsxs(g.Fragment,{children:[g.jsx(D0,{filePath:e||""}),t&&e&&g.jsx(_0,{metadata:t,filename:e,className:"dark:bg-gray-800 dark:text-gray-200"})]})})})};function z0(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB","TB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}const F0=({current:e,parent:t,files:n,folders:r})=>g.jsxs("div",{className:"bg-white dark:bg-gray-800 shadow-md rounded-lg overflow-hidden",children:[g.jsxs("div",{className:"grid grid-cols-12 bg-gray-50 dark:bg-gray-700 border-b dark:border-gray-600",children:[g.jsx("div",{className:"col-span-5 p-4 font-semibold text-gray-600 dark:text-gray-200",children:"Name"}),g.jsx("div",{className:"col-span-3 p-4 font-semibold text-gray-600 dark:text-gray-200",children:"Last Modified"}),g.jsx("div",{className:"col-span-3 p-4 font-semibold text-gray-600 dark:text-gray-200",children:"Size"}),g.jsx("div",{className:"col-span-1 p-4"})]}),t!==e&&g.jsxs(rn,{to:`/?path=${encodeURIComponent(t)}`,className:"grid grid-cols-12 border-b dark:border-gray-600 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200",children:[g.jsxs("div",{className:"col-span-5 p-4 flex items-center",children:[g.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M15 19l-7-7 7-7"})}),".."]}),g.jsx("div",{className:"col-span-3 p-4",children:"-"}),g.jsx("div",{className:"col-span-3 p-4",children:"-"}),g.jsx("div",{className:"col-span-1 p-4"})]}),r.map(l=>g.jsxs(rn,{to:`/?path=${encodeURIComponent(e?`${e}/${l}`:l)}`,className:"grid grid-cols-12 border-b dark:border-gray-600 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200",children:[g.jsxs("div",{className:"col-span-5 p-4 flex items-center",children:[g.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"})}),l]}),g.jsx("div",{className:"col-span-3 p-4",children:"-"}),g.jsx("div",{className:"col-span-3 p-4",children:"-"}),g.jsx("div",{className:"col-span-1 p-4"})]},l)),g.jsx("div",{className:"space-y-2",children:n.map(l=>{const a=e?`${e}/${l.name}`:l.name;return g.jsxs("div",{className:"grid grid-cols-12 border-b dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200",children:[g.jsxs(rn,{to:`file/${encodeURIComponent(a)}`,className:"col-span-5 p-4 flex items-center",children:[g.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"})}),l.name]}),g.jsx("div",{className:"col-span-3 p-4",children:g.jsx(Rh,{date:new Date(l.lastModified)})}),g.jsx("div",{className:"col-span-3 p-4",children:z0(l.size)}),g.jsx("div",{className:"col-span-1 p-4 flex justify-center",children:g.jsx(rn,{to:`/api/download?file=${encodeURIComponent(a)}`,target:"_blank",rel:"noopener noreferrer",className:"text-gray-600 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400",title:"Download file",children:g.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})})})]},l.name)})})]}),I0=e=>[...e].sort((t,n)=>new Date(n.lastModified).getTime()-new Date(t.lastModified).getTime()),U0=e=>{const[t,n]=Ne.useState(null),[r,l]=Ne.useState(!0),[a,i]=Ne.useState(null),o=pi(),u=N.useMemo(()=>t?{...t,files:I0(t.files)}:null,[t]);return Ne.useEffect(()=>{(async()=>{try{l(!0);const c=await fetch(`${o}api/list?path=${encodeURIComponent(e)}`);if(!c.ok)throw new Error("Failed to fetch data");const f=await c.json();n(f),i(null)}catch(c){i(c instanceof Error?c.message:"An error occurred")}finally{l(!1)}})()},[e,o]),{data:u,loading:r,error:a}},Fh=()=>{const[e]=dv(),t=e.get("path")||"",{data:n,loading:r,error:l}=U0(t),a=Ne.useMemo(()=>((n==null?void 0:n.current)||"").split("/").filter(Boolean),[n==null?void 0:n.current]);return g.jsx(Lh,{breadcrumbParts:a,isLastBreadcrumbClickable:!0,children:g.jsx("div",{className:"relative",style:{overflow:"visible"},children:r?g.jsx(Dh,{fullScreen:!0}):l?g.jsx(Oh,{message:l,fullScreen:!0}):n?g.jsx("div",{className:"relative",style:{overflow:"visible"},children:g.jsx(F0,{current:n.current,parent:n.parent,files:n.files,folders:n.folders})}):null})})};function B0(){return g.jsxs(Ay,{children:[g.jsx(bo,{path:"file/:filePath",element:g.jsx(zh,{})}),g.jsx(bo,{path:"*",element:g.jsx(Fh,{})})]})}const W0=window.location.pathname,Ki=W0.match(/(.*\/dataobj\/explorer\/)/),Ih=(Ki==null?void 0:Ki[1])||"/dataobj/explorer/",$0=Gy([{path:"*",element:g.jsx(B0,{}),children:[{index:!0,element:g.jsx(Fh,{})},{path:"file/:filePath",element:g.jsx(zh,{})}]}],{basename:Ih,future:{v7_relativeSplatPath:!0}});Gi.createRoot(document.getElementById("root")).render(g.jsx(Ne.StrictMode,{children:g.jsx(M0,{basename:Ih,children:g.jsx(av,{router:$0,future:{v7_startTransition:!0}})})})); diff --git a/pkg/dataobj/explorer/dist/assets/style-Dz5w-Rts.css b/pkg/dataobj/explorer/dist/assets/style-Dz5w-Rts.css deleted file mode 100644 index 0488ba247648c..0000000000000 --- a/pkg/dataobj/explorer/dist/assets/style-Dz5w-Rts.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-y-0{top:0;bottom:0}.bottom-8{bottom:2rem}.left-0{left:0}.right-8{right:2rem}.z-\[9999\]{z-index:9999}.col-span-1{grid-column:span 1 / span 1}.col-span-3{grid-column:span 3 / span 3}.col-span-5{grid-column:span 5 / span 5}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.ml-1{margin-left:.25rem}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-4{margin-right:1rem}.mt-1{margin-top:.25rem}.mt-6{margin-top:1.5rem}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.min-h-\[200px\]{min-height:200px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.min-w-\[280px\]{min-width:280px}.min-w-full{min-width:100%}.flex-1{flex:1 1 0%}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-pointer{cursor:pointer}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-t{border-top-width:1px}.border-t-2{border-top-width:2px}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-red-400{--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-rose-100{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.bg-sky-100{--tw-bg-opacity: 1;background-color:rgb(224 242 254 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-cyan-800{--tw-text-opacity: 1;color:rgb(21 94 117 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-rose-800{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.text-sky-800{--tw-text-opacity: 1;color:rgb(7 89 133 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.opacity-0{opacity:0}.opacity-100{opacity:1}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-700{transition-duration:.7s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-800:hover{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.hover\:ring-2:hover{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.hover\:ring-gray-300:hover{--tw-ring-opacity: 1;--tw-ring-color: rgb(209 213 219 / var(--tw-ring-opacity, 1))}.dark\:divide-gray-900:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(17 24 39 / var(--tw-divide-opacity, 1))}.dark\:border-blue-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.dark\:border-gray-500:is(.dark *){--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:bg-blue-500:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:bg-rose-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(136 19 55 / var(--tw-bg-opacity, 1))}.dark\:bg-sky-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(12 74 110 / var(--tw-bg-opacity, 1))}.dark\:bg-yellow-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-gray-200:is(.dark *){--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-green-300:is(.dark *){--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-red-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.dark\:text-rose-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.dark\:text-sky-300:is(.dark *){--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.dark\:text-yellow-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-blue-700:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-blue-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:hover\:text-blue-400:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:hover\:ring-gray-600:hover:is(.dark *){--tw-ring-opacity: 1;--tw-ring-color: rgb(75 85 99 / var(--tw-ring-opacity, 1))}@media (min-width: 768px){.md\:ml-2{margin-left:.5rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}}@media (min-width: 1024px){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/pkg/dataobj/explorer/dist/index.html b/pkg/dataobj/explorer/dist/index.html deleted file mode 100644 index 79e2f449e25dc..0000000000000 --- a/pkg/dataobj/explorer/dist/index.html +++ /dev/null @@ -1,16 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - -<head> - <meta charset="UTF-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>DataObj Explorer</title> - <script type="module" crossorigin src="/dataobj/explorer/assets/index-CWzBrpZu.js"></script> - <link rel="stylesheet" crossorigin href="/dataobj/explorer/assets/style-Dz5w-Rts.css"> -</head> - -<body> - <div id="root"></div> -</body> - -</html> diff --git a/pkg/dataobj/explorer/service.go b/pkg/dataobj/explorer/service.go index a80bb5e4f6b83..fd8e41ecbe569 100644 --- a/pkg/dataobj/explorer/service.go +++ b/pkg/dataobj/explorer/service.go @@ -2,11 +2,8 @@ package explorer import ( "context" - "embed" "encoding/json" - "io/fs" "net/http" - "strings" "github.com/go-kit/log" "github.com/go-kit/log/level" @@ -14,30 +11,17 @@ import ( "github.com/thanos-io/objstore" ) -//go:embed dist -var uiFS embed.FS - type Service struct { *services.BasicService bucket objstore.Bucket logger log.Logger - uiFS fs.FS } func New(bucket objstore.Bucket, logger log.Logger) (*Service, error) { - var ui fs.FS - - var err error - ui, err = fs.Sub(uiFS, "dist") - if err != nil { - return nil, err - } - s := &Service{ bucket: bucket, logger: logger, - uiFS: ui, } s.BasicService = services.NewBasicService(nil, s.running, nil) @@ -50,24 +34,16 @@ func (s *Service) running(ctx context.Context) error { return nil } -func (s *Service) Handler() http.Handler { +func (s *Service) Handler() (string, http.Handler) { mux := http.NewServeMux() // API endpoints - mux.HandleFunc("/dataobj/explorer/api/list", s.handleList) - mux.HandleFunc("/dataobj/explorer/api/inspect", s.handleInspect) - mux.HandleFunc("/dataobj/explorer/api/download", s.handleDownload) - mux.HandleFunc("/dataobj/explorer/api/provider", s.handleProvider) - - fsHandler := http.FileServer(http.FS(s.uiFS)) - mux.Handle("/dataobj/explorer/", http.StripPrefix("/dataobj/explorer/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if _, err := s.uiFS.Open(strings.TrimPrefix(r.URL.Path, "/")); err != nil { - r.URL.Path = "/" - } - fsHandler.ServeHTTP(w, r) - }))) + mux.HandleFunc("/dataobj/api/v1/list", s.handleList) + mux.HandleFunc("/dataobj/api/v1/inspect", s.handleInspect) + mux.HandleFunc("/dataobj/api/v1/download", s.handleDownload) + mux.HandleFunc("/dataobj/api/v1/provider", s.handleProvider) - return mux + return "/dataobj", mux } func (s *Service) handleProvider(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/dataobj/explorer/ui/Makefile b/pkg/dataobj/explorer/ui/Makefile deleted file mode 100644 index d8c0f295a51c6..0000000000000 --- a/pkg/dataobj/explorer/ui/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -.PHONY: build -build: - npm install - npm run build - -.PHONY: dev -dev: - npm install - npm run dev diff --git a/pkg/dataobj/explorer/ui/package-lock.json b/pkg/dataobj/explorer/ui/package-lock.json deleted file mode 100644 index bce9eac06d75c..0000000000000 --- a/pkg/dataobj/explorer/ui/package-lock.json +++ /dev/null @@ -1,3166 +0,0 @@ -{ - "name": "dataobj-explorer", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "dataobj-explorer", - "version": "0.1.0", - "dependencies": { - "date-fns": "^4.1.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "react-router-dom": "^7.0.0" - }, - "devDependencies": { - "@types/node": "^22.10.7", - "@types/react": "^19.0.0", - "@types/react-dom": "^19.0.0", - "@vitejs/plugin-react": "^4.2.1", - "autoprefixer": "^10.4.16", - "postcss": "^8.4.32", - "tailwindcss": "^3.4.0", - "typescript": "^5.2.2", - "vite": "^6.0.0" - } - }, - "node_modules/@alloc/quick-lru": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", - "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@ampproject/remapping": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", - "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.26.2", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", - "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.25.9", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.5.tgz", - "integrity": "sha512-XvcZi1KWf88RVbF9wn8MN6tYFloU5qX8KjuF3E1PVBmJ9eypXfs4GRiJwLuTZL0iSnJUKn1BFPa5BPZZJyFzPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.0.tgz", - "integrity": "sha512-i1SLeK+DzNnQ3LL/CswPCa/E5u4lh1k6IAEphON8F+cXt0t9euTshDru0q7/IqMa1PMPz5RnHuHscF8/ZJsStg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.26.0", - "@babel/generator": "^7.26.0", - "@babel/helper-compilation-targets": "^7.25.9", - "@babel/helper-module-transforms": "^7.26.0", - "@babel/helpers": "^7.26.0", - "@babel/parser": "^7.26.0", - "@babel/template": "^7.25.9", - "@babel/traverse": "^7.25.9", - "@babel/types": "^7.26.0", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.5.tgz", - "integrity": "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.26.5", - "@babel/types": "^7.26.5", - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.25", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.26.5.tgz", - "integrity": "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.26.5", - "@babel/helper-validator-option": "^7.25.9", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.25.9.tgz", - "integrity": "sha512-tnUA4RsrmflIM6W6RFTLFSXITtl0wKjgpnLgXyowocVPrbYrLUXSBXDgTs8BlbmIzIdlBySRQjINYs2BAkiLtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.25.9", - "@babel/types": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.26.0.tgz", - "integrity": "sha512-xO+xu6B5K2czEnQye6BHA7DolFFmS3LB7stHZFaOLb1pAwO1HWLS8fXA+eh0A2yIvltPVmx3eNNDBJA2SLHXFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.25.9", - "@babel/helper-validator-identifier": "^7.25.9", - "@babel/traverse": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.26.5.tgz", - "integrity": "sha512-RS+jZcRdZdRFzMyr+wcsaqOmld1/EqTghfaBGQQd/WnRdzdlvSZ//kF7U8VQTxf1ynZ4cjUcYgjVGx13ewNPMg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", - "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", - "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.25.9.tgz", - "integrity": "sha512-e/zv1co8pp55dNdEcCynfj9X7nyUKUXoUEwfXqaZt0omVOmDe9oOTdKStH4GmAw6zxMFs50ZayuMfHDKlO7Tfw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz", - "integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.25.9", - "@babel/types": "^7.26.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.5.tgz", - "integrity": "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.26.5" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-self": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.25.9.tgz", - "integrity": "sha512-y8quW6p0WHkEhmErnfe58r7x0A70uKphQm8Sp8cV7tjNQwK56sNVK0M73LK3WuYmsuyrftut4xAkjjgU0twaMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-source": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.25.9.tgz", - "integrity": "sha512-+iqjT8xmXhhYv4/uiYd8FNQsraMFZIfxVSqxxVSZP0WbbSAWvBXAul0m/zu+7Vv4O/3WtApy9pmaTMiumEZgfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz", - "integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.25.9", - "@babel/parser": "^7.25.9", - "@babel/types": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.5.tgz", - "integrity": "sha512-rkOSPOw+AXbgtwUga3U4u8RpoK9FEFWBNAlTpcnkLFjL5CT+oyHNuUUC/xx6XefEJ16r38r8Bc/lfp6rYuHeJQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.26.2", - "@babel/generator": "^7.26.5", - "@babel/parser": "^7.26.5", - "@babel/template": "^7.25.9", - "@babel/types": "^7.26.5", - "debug": "^4.3.1", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.26.5", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.5.tgz", - "integrity": "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.25.9", - "@babel/helper-validator-identifier": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz", - "integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz", - "integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz", - "integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz", - "integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz", - "integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz", - "integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz", - "integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz", - "integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz", - "integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz", - "integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz", - "integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz", - "integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz", - "integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz", - "integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz", - "integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz", - "integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz", - "integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz", - "integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz", - "integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz", - "integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz", - "integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz", - "integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz", - "integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz", - "integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz", - "integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz", - "integrity": "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/set-array": "^1.2.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/set-array": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", - "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", - "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=14" - } - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.31.0.tgz", - "integrity": "sha512-9NrR4033uCbUBRgvLcBrJofa2KY9DzxL2UKZ1/4xA/mnTNyhZCWBuD8X3tPm1n4KxcgaraOYgrFKSgwjASfmlA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.31.0.tgz", - "integrity": "sha512-iBbODqT86YBFHajxxF8ebj2hwKm1k8PTBQSojSt3d1FFt1gN+xf4CowE47iN0vOSdnd+5ierMHBbu/rHc7nq5g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.31.0.tgz", - "integrity": "sha512-WHIZfXgVBX30SWuTMhlHPXTyN20AXrLH4TEeH/D0Bolvx9PjgZnn4H677PlSGvU6MKNsjCQJYczkpvBbrBnG6g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.31.0.tgz", - "integrity": "sha512-hrWL7uQacTEF8gdrQAqcDy9xllQ0w0zuL1wk1HV8wKGSGbKPVjVUv/DEwT2+Asabf8Dh/As+IvfdU+H8hhzrQQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.31.0.tgz", - "integrity": "sha512-S2oCsZ4hJviG1QjPY1h6sVJLBI6ekBeAEssYKad1soRFv3SocsQCzX6cwnk6fID6UQQACTjeIMB+hyYrFacRew==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.31.0.tgz", - "integrity": "sha512-pCANqpynRS4Jirn4IKZH4tnm2+2CqCNLKD7gAdEjzdLGbH1iO0zouHz4mxqg0uEMpO030ejJ0aA6e1PJo2xrPA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.31.0.tgz", - "integrity": "sha512-0O8ViX+QcBd3ZmGlcFTnYXZKGbFu09EhgD27tgTdGnkcYXLat4KIsBBQeKLR2xZDCXdIBAlWLkiXE1+rJpCxFw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.31.0.tgz", - "integrity": "sha512-w5IzG0wTVv7B0/SwDnMYmbr2uERQp999q8FMkKG1I+j8hpPX2BYFjWe69xbhbP6J9h2gId/7ogesl9hwblFwwg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.31.0.tgz", - "integrity": "sha512-JyFFshbN5xwy6fulZ8B/8qOqENRmDdEkcIMF0Zz+RsfamEW+Zabl5jAb0IozP/8UKnJ7g2FtZZPEUIAlUSX8cA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.31.0.tgz", - "integrity": "sha512-kpQXQ0UPFeMPmPYksiBL9WS/BDiQEjRGMfklVIsA0Sng347H8W2iexch+IEwaR7OVSKtr2ZFxggt11zVIlZ25g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.31.0.tgz", - "integrity": "sha512-pMlxLjt60iQTzt9iBb3jZphFIl55a70wexvo8p+vVFK+7ifTRookdoXX3bOsRdmfD+OKnMozKO6XM4zR0sHRrQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.31.0.tgz", - "integrity": "sha512-D7TXT7I/uKEuWiRkEFbed1UUYZwcJDU4vZQdPTcepK7ecPhzKOYk4Er2YR4uHKme4qDeIh6N3XrLfpuM7vzRWQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.31.0.tgz", - "integrity": "sha512-wal2Tc8O5lMBtoePLBYRKj2CImUCJ4UNGJlLwspx7QApYny7K1cUYlzQ/4IGQBLmm+y0RS7dwc3TDO/pmcneTw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.31.0.tgz", - "integrity": "sha512-O1o5EUI0+RRMkK9wiTVpk2tyzXdXefHtRTIjBbmFREmNMy7pFeYXCFGbhKFwISA3UOExlo5GGUuuj3oMKdK6JQ==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.31.0.tgz", - "integrity": "sha512-zSoHl356vKnNxwOWnLd60ixHNPRBglxpv2g7q0Cd3Pmr561gf0HiAcUBRL3S1vPqRC17Zo2CX/9cPkqTIiai1g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.31.0.tgz", - "integrity": "sha512-ypB/HMtcSGhKUQNiFwqgdclWNRrAYDH8iMYH4etw/ZlGwiTVxBz2tDrGRrPlfZu6QjXwtd+C3Zib5pFqID97ZA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.31.0.tgz", - "integrity": "sha512-JuhN2xdI/m8Hr+aVO3vspO7OQfUFO6bKLIRTAy0U15vmWjnZDLrEgCZ2s6+scAYaQVpYSh9tZtRijApw9IXyMw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.31.0.tgz", - "integrity": "sha512-U1xZZXYkvdf5MIWmftU8wrM5PPXzyaY1nGCI4KI4BFfoZxHamsIe+BtnPLIvvPykvQWlVbqUXdLa4aJUuilwLQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.31.0.tgz", - "integrity": "sha512-ul8rnCsUumNln5YWwz0ted2ZHFhzhRRnkpBZ+YRuHoRAlUji9KChpOUOndY7uykrPEPXVbHLlsdo6v5yXo/TXw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.6.8", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", - "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.20.6", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", - "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.20.7" - } - }, - "node_modules/@types/cookie": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", - "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "22.13.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.3.tgz", - "integrity": "sha512-nR7dEScXY87nBVt9gPL0sP93GCxG7nMzFicbYjOcGdKcLytrXBgrnMIYcghBW0+YfLj3t7G5FgUccrhdZuTB9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.20.0" - } - }, - "node_modules/@types/react": { - "version": "19.0.8", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.0.8.tgz", - "integrity": "sha512-9P/o1IGdfmQxrujGbIMDyYaaCykhLKc0NGCtYcECNUr9UAaDe4gwvV9bR6tvd5Br1SG0j+PBpbKr2UYY8CwqSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "csstype": "^3.0.2" - } - }, - "node_modules/@types/react-dom": { - "version": "19.0.3", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.0.3.tgz", - "integrity": "sha512-0Knk+HJiMP/qOZgMyNFamlIjw9OFCsyC2ZbigmEEyXXixgre6IQpm/4V+r3qH4GC1JPvRJKInw+on2rV6YZLeA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^19.0.0" - } - }, - "node_modules/@vitejs/plugin-react": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.4.tgz", - "integrity": "sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.26.0", - "@babel/plugin-transform-react-jsx-self": "^7.25.9", - "@babel/plugin-transform-react-jsx-source": "^7.25.9", - "@types/babel__core": "^7.20.5", - "react-refresh": "^0.14.2" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "peerDependencies": { - "vite": "^4.2.0 || ^5.0.0 || ^6.0.0" - } - }, - "node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/any-promise": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", - "dev": true, - "license": "MIT" - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arg": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", - "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", - "dev": true, - "license": "MIT" - }, - "node_modules/autoprefixer": { - "version": "10.4.20", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", - "integrity": "sha512-XY25y5xSv/wEoqzDyXXME4AFfkZI0P23z6Fs3YgymDnKJkCGOnkL0iTxCa85UTqaSgfcqyf3UA6+c7wUvx/16g==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/autoprefixer" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "browserslist": "^4.23.3", - "caniuse-lite": "^1.0.30001646", - "fraction.js": "^4.3.7", - "normalize-range": "^0.1.2", - "picocolors": "^1.0.1", - "postcss-value-parser": "^4.2.0" - }, - "bin": { - "autoprefixer": "bin/autoprefixer" - }, - "engines": { - "node": "^10 || ^12 || >=14" - }, - "peerDependencies": { - "postcss": "^8.1.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.24.4", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.4.tgz", - "integrity": "sha512-KDi1Ny1gSePi1vm0q4oxSF8b4DR44GF4BbmS2YdhPLOEqd8pDviZOGH/GsmRwoWJ2+5Lr085X7naowMwKHDG1A==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "caniuse-lite": "^1.0.30001688", - "electron-to-chromium": "^1.5.73", - "node-releases": "^2.0.19", - "update-browserslist-db": "^1.1.1" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/camelcase-css": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", - "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001695", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001695.tgz", - "integrity": "sha512-vHyLade6wTgI2u1ec3WQBxv+2BrTERV28UXQu9LO6lZ9pYeMk34vjXFLOxo1A4UBA8XTL4njRQZdno/yYaSmWw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/chokidar/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/commander": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", - "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cookie": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz", - "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/csstype": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", - "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", - "dev": true, - "license": "MIT" - }, - "node_modules/date-fns": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", - "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/kossnocorp" - } - }, - "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/didyoumean": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", - "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/dlv": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", - "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", - "dev": true, - "license": "MIT" - }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "dev": true, - "license": "MIT" - }, - "node_modules/electron-to-chromium": { - "version": "1.5.83", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.83.tgz", - "integrity": "sha512-LcUDPqSt+V0QmI47XLzZrz5OqILSMGsPFkDYus22rIbgorSvBYEFqq854ltTmUdHkY92FSdAAvsh4jWEULMdfQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/esbuild": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz", - "integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.24.2", - "@esbuild/android-arm": "0.24.2", - "@esbuild/android-arm64": "0.24.2", - "@esbuild/android-x64": "0.24.2", - "@esbuild/darwin-arm64": "0.24.2", - "@esbuild/darwin-x64": "0.24.2", - "@esbuild/freebsd-arm64": "0.24.2", - "@esbuild/freebsd-x64": "0.24.2", - "@esbuild/linux-arm": "0.24.2", - "@esbuild/linux-arm64": "0.24.2", - "@esbuild/linux-ia32": "0.24.2", - "@esbuild/linux-loong64": "0.24.2", - "@esbuild/linux-mips64el": "0.24.2", - "@esbuild/linux-ppc64": "0.24.2", - "@esbuild/linux-riscv64": "0.24.2", - "@esbuild/linux-s390x": "0.24.2", - "@esbuild/linux-x64": "0.24.2", - "@esbuild/netbsd-arm64": "0.24.2", - "@esbuild/netbsd-x64": "0.24.2", - "@esbuild/openbsd-arm64": "0.24.2", - "@esbuild/openbsd-x64": "0.24.2", - "@esbuild/sunos-x64": "0.24.2", - "@esbuild/win32-arm64": "0.24.2", - "@esbuild/win32-ia32": "0.24.2", - "@esbuild/win32-x64": "0.24.2" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fastq": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.0.tgz", - "integrity": "sha512-7SFSRCNjBQIZH/xZR3iy5iQYR8aGBE0h3VG6/cwlbrpdciNYBMotQav8c1XI3HjHH+NikUpP53nPdlZSdWmFzA==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/foreground-child": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", - "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", - "dev": true, - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.0", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/fraction.js": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", - "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - }, - "funding": { - "type": "patreon", - "url": "https://github.com/sponsors/rawify" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/glob": { - "version": "10.4.5", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", - "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", - "dev": true, - "license": "ISC", - "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^3.1.2", - "minimatch": "^9.0.4", - "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^1.11.1" - }, - "bin": { - "glob": "dist/esm/bin.mjs" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/jackspeak": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", - "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" - } - }, - "node_modules/jiti": { - "version": "1.21.7", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", - "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "bin/jiti.js" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/lilconfig": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", - "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/antonk52" - } - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/mz": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", - "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0", - "object-assign": "^4.0.1", - "thenify-all": "^1.0.0" - } - }, - "node_modules/nanoid": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/node-releases": { - "version": "2.0.19", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", - "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", - "dev": true, - "license": "MIT" - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-hash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", - "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/package-json-from-dist": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", - "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", - "dev": true, - "license": "BlueOak-1.0.0" - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" - }, - "engines": { - "node": ">=16 || 14 >=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/postcss": { - "version": "8.5.2", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.2.tgz", - "integrity": "sha512-MjOadfU3Ys9KYoX0AdkBlFEF1Vx37uCCeN4ZHnmwm9FfpbsGWMZeBLMmmpY+6Ocqod7mkdZ0DT31OlbsFrLlkA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.8", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postcss-import": { - "version": "15.1.0", - "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", - "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", - "dev": true, - "license": "MIT", - "dependencies": { - "postcss-value-parser": "^4.0.0", - "read-cache": "^1.0.0", - "resolve": "^1.1.7" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "postcss": "^8.0.0" - } - }, - "node_modules/postcss-js": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", - "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", - "dev": true, - "license": "MIT", - "dependencies": { - "camelcase-css": "^2.0.1" - }, - "engines": { - "node": "^12 || ^14 || >= 16" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - "peerDependencies": { - "postcss": "^8.4.21" - } - }, - "node_modules/postcss-load-config": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", - "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "lilconfig": "^3.0.0", - "yaml": "^2.3.4" - }, - "engines": { - "node": ">= 14" - }, - "peerDependencies": { - "postcss": ">=8.0.9", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "postcss": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/postcss-nested": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", - "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "postcss-selector-parser": "^6.1.1" - }, - "engines": { - "node": ">=12.0" - }, - "peerDependencies": { - "postcss": "^8.2.14" - } - }, - "node_modules/postcss-selector-parser": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", - "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/postcss-value-parser": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", - "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/react": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz", - "integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "19.0.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.0.0.tgz", - "integrity": "sha512-4GV5sHFG0e/0AD4X+ySy6UJd3jVl1iNsNHdpad0qhABJ11twS3TTBnseqsKurKcsNqCEFeGL3uLpVChpIO3QfQ==", - "license": "MIT", - "dependencies": { - "scheduler": "^0.25.0" - }, - "peerDependencies": { - "react": "^19.0.0" - } - }, - "node_modules/react-refresh": { - "version": "0.14.2", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", - "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-router": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.1.5.tgz", - "integrity": "sha512-8BUF+hZEU4/z/JD201yK6S+UYhsf58bzYIDq2NS1iGpwxSXDu7F+DeGSkIXMFBuHZB21FSiCzEcUb18cQNdRkA==", - "license": "MIT", - "dependencies": { - "@types/cookie": "^0.6.0", - "cookie": "^1.0.1", - "set-cookie-parser": "^2.6.0", - "turbo-stream": "2.4.0" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - }, - "peerDependenciesMeta": { - "react-dom": { - "optional": true - } - } - }, - "node_modules/react-router-dom": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.1.5.tgz", - "integrity": "sha512-/4f9+up0Qv92D3bB8iN5P1s3oHAepSGa9h5k6tpTFlixTTskJZwKGhJ6vRJ277tLD1zuaZTt95hyGWV1Z37csQ==", - "license": "MIT", - "dependencies": { - "react-router": "7.1.5" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - } - }, - "node_modules/read-cache": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", - "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pify": "^2.3.0" - } - }, - "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-core-module": "^2.16.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rollup": { - "version": "4.31.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.31.0.tgz", - "integrity": "sha512-9cCE8P4rZLx9+PjoyqHLs31V9a9Vpvfo4qNcs6JCiGWYhw2gijSetFbH6SSy1whnkgcefnUwr8sad7tgqsGvnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.6" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.31.0", - "@rollup/rollup-android-arm64": "4.31.0", - "@rollup/rollup-darwin-arm64": "4.31.0", - "@rollup/rollup-darwin-x64": "4.31.0", - "@rollup/rollup-freebsd-arm64": "4.31.0", - "@rollup/rollup-freebsd-x64": "4.31.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.31.0", - "@rollup/rollup-linux-arm-musleabihf": "4.31.0", - "@rollup/rollup-linux-arm64-gnu": "4.31.0", - "@rollup/rollup-linux-arm64-musl": "4.31.0", - "@rollup/rollup-linux-loongarch64-gnu": "4.31.0", - "@rollup/rollup-linux-powerpc64le-gnu": "4.31.0", - "@rollup/rollup-linux-riscv64-gnu": "4.31.0", - "@rollup/rollup-linux-s390x-gnu": "4.31.0", - "@rollup/rollup-linux-x64-gnu": "4.31.0", - "@rollup/rollup-linux-x64-musl": "4.31.0", - "@rollup/rollup-win32-arm64-msvc": "4.31.0", - "@rollup/rollup-win32-ia32-msvc": "4.31.0", - "@rollup/rollup-win32-x64-msvc": "4.31.0", - "fsevents": "~2.3.2" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/scheduler": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz", - "integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/set-cookie-parser": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz", - "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==", - "license": "MIT" - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/string-width-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/sucrase": { - "version": "3.35.0", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", - "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "glob": "^10.3.10", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "ts-interface-checker": "^0.1.9" - }, - "bin": { - "sucrase": "bin/sucrase", - "sucrase-node": "bin/sucrase-node" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/tailwindcss": { - "version": "3.4.17", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", - "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", - "dev": true, - "license": "MIT", - "dependencies": { - "@alloc/quick-lru": "^5.2.0", - "arg": "^5.0.2", - "chokidar": "^3.6.0", - "didyoumean": "^1.2.2", - "dlv": "^1.1.3", - "fast-glob": "^3.3.2", - "glob-parent": "^6.0.2", - "is-glob": "^4.0.3", - "jiti": "^1.21.6", - "lilconfig": "^3.1.3", - "micromatch": "^4.0.8", - "normalize-path": "^3.0.0", - "object-hash": "^3.0.0", - "picocolors": "^1.1.1", - "postcss": "^8.4.47", - "postcss-import": "^15.1.0", - "postcss-js": "^4.0.1", - "postcss-load-config": "^4.0.2", - "postcss-nested": "^6.2.0", - "postcss-selector-parser": "^6.1.2", - "resolve": "^1.22.8", - "sucrase": "^3.35.0" - }, - "bin": { - "tailwind": "lib/cli.js", - "tailwindcss": "lib/cli.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/thenify": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", - "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0" - } - }, - "node_modules/thenify-all": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", - "dev": true, - "license": "MIT", - "dependencies": { - "thenify": ">= 3.1.0 < 4" - }, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/ts-interface-checker": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", - "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/turbo-stream": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/turbo-stream/-/turbo-stream-2.4.0.tgz", - "integrity": "sha512-FHncC10WpBd2eOmGwpmQsWLDoK4cqsA/UT/GqNoaKOQnT8uzhtCbg3EoUDMvqpOSAI0S26mr0rkjzbOO6S3v1g==", - "license": "ISC" - }, - "node_modules/typescript": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", - "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", - "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", - "dev": true, - "license": "MIT" - }, - "node_modules/update-browserslist-db": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.2.tgz", - "integrity": "sha512-PPypAm5qvlD7XMZC3BujecnaOxwhrtoFR+Dqkk5Aa/6DssiH0ibKoketaj9w8LP7Bont1rYeoV5plxD7RTEPRg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, - "license": "MIT" - }, - "node_modules/vite": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.1.0.tgz", - "integrity": "sha512-RjjMipCKVoR4hVfPY6GQTgveinjNuyLw+qruksLDvA5ktI1150VmcMBKmQaEWJhg/j6Uaf6dNCNA0AfdzUb/hQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.24.2", - "postcss": "^8.5.1", - "rollup": "^4.30.1" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || ^20.0.0 || >=22.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", - "jiti": ">=1.21.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi-cjs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/yaml": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.0.tgz", - "integrity": "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14" - } - } - } -} diff --git a/pkg/dataobj/explorer/ui/package.json b/pkg/dataobj/explorer/ui/package.json deleted file mode 100644 index 6d395838764e9..0000000000000 --- a/pkg/dataobj/explorer/ui/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "dataobj-explorer", - "version": "0.1.0", - "private": true, - "type": "module", - "scripts": { - "dev": "vite", - "build": "vite build", - "preview": "vite preview" - }, - "dependencies": { - "date-fns": "^4.1.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "react-router-dom": "^7.0.0" - }, - "devDependencies": { - "@types/node": "^22.10.7", - "@types/react": "^19.0.0", - "@types/react-dom": "^19.0.0", - "@vitejs/plugin-react": "^4.2.1", - "autoprefixer": "^10.4.16", - "postcss": "^8.4.32", - "tailwindcss": "^3.4.0", - "typescript": "^5.2.2", - "vite": "^6.0.0" - } -} diff --git a/pkg/dataobj/explorer/ui/src/App.tsx b/pkg/dataobj/explorer/ui/src/App.tsx deleted file mode 100644 index d4159052ca4a4..0000000000000 --- a/pkg/dataobj/explorer/ui/src/App.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import React from "react"; -import { Routes, Route } from "react-router-dom"; -import { FileMetadataPage } from "./pages/FileMetadataPage"; -import { ExplorerPage } from "./pages/ExplorerPage"; - -export default function App() { - return ( - <Routes> - <Route path="file/:filePath" element={<FileMetadataPage />} /> - <Route path="*" element={<ExplorerPage />} /> - </Routes> - ); -} diff --git a/pkg/dataobj/explorer/ui/src/components/common/DateWithHover.tsx b/pkg/dataobj/explorer/ui/src/components/common/DateWithHover.tsx deleted file mode 100644 index 65c5fcb41c17f..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/common/DateWithHover.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import React from "react"; -import { formatDistanceToNow, format } from "date-fns"; -import { createPortal } from "react-dom"; - -interface DateWithHoverProps { - date: Date; - className?: string; -} - -export const DateWithHover: React.FC<DateWithHoverProps> = ({ - date, - className = "", -}) => { - const [isHovered, setIsHovered] = React.useState(false); - const relativeTime = formatDistanceToNow(date, { addSuffix: true }); - const localTime = format(date, "yyyy-MM-dd HH:mm:ss"); - const utcTime = format( - new Date(date.getTime() + date.getTimezoneOffset() * 60000), - "yyyy-MM-dd HH:mm:ss" - ); - - const [position, setPosition] = React.useState({ top: 0, left: 0 }); - const triggerRef = React.useRef<HTMLDivElement>(null); - - const updatePosition = React.useCallback(() => { - if (triggerRef.current) { - const rect = triggerRef.current.getBoundingClientRect(); - setPosition({ - top: rect.top + window.scrollY - 70, // Position above the element - left: rect.left + window.scrollX, - }); - } - }, []); - - React.useEffect(() => { - if (isHovered) { - updatePosition(); - window.addEventListener("scroll", updatePosition); - window.addEventListener("resize", updatePosition); - } - return () => { - window.removeEventListener("scroll", updatePosition); - window.removeEventListener("resize", updatePosition); - }; - }, [isHovered, updatePosition]); - - return ( - <> - <div - ref={triggerRef} - className={`inline-block ${className}`} - onMouseEnter={() => setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - {relativeTime} - </div> - {isHovered && - createPortal( - <div - style={{ - position: "absolute", - top: `${position.top}px`, - left: `${position.left}px`, - }} - className="z-[9999] min-w-[280px] text-sm text-gray-500 bg-white border border-gray-200 rounded-lg shadow-sm dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800" - > - <div className="px-3 py-2 space-y-2"> - <div className="flex items-center gap-3"> - <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> - UTC - </span> - <span className="font-mono">{utcTime}</span> - </div> - <div className="flex items-center gap-3"> - <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> - Local - </span> - <span className="font-mono">{localTime}</span> - </div> - </div> - </div>, - document.body - )} - </> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/components/common/ErrorContainer.tsx b/pkg/dataobj/explorer/ui/src/components/common/ErrorContainer.tsx deleted file mode 100644 index f2e1ef4897f4c..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/common/ErrorContainer.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import React from "react"; - -interface ErrorContainerProps { - message: string; - fullScreen?: boolean; -} - -export const ErrorContainer: React.FC<ErrorContainerProps> = ({ - message, - fullScreen = false, -}) => ( - <div - className={`flex items-center justify-center ${ - fullScreen ? "min-h-screen" : "" - }`} - > - <div className="text-red-500 p-4">Error: {message}</div> - </div> -); diff --git a/pkg/dataobj/explorer/ui/src/components/common/LoadingContainer.tsx b/pkg/dataobj/explorer/ui/src/components/common/LoadingContainer.tsx deleted file mode 100644 index 4372ad917bf83..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/common/LoadingContainer.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import React from "react"; - -interface LoadingContainerProps { - fullScreen?: boolean; -} - -export const LoadingContainer: React.FC<LoadingContainerProps> = ({ - fullScreen = false, -}) => ( - <div - className={`flex items-center justify-center ${ - fullScreen ? "min-h-screen" : "min-h-[200px]" - } dark:bg-gray-900`} - > - <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500 dark:border-blue-400" /> - </div> -); diff --git a/pkg/dataobj/explorer/ui/src/components/explorer/FileList.tsx b/pkg/dataobj/explorer/ui/src/components/explorer/FileList.tsx deleted file mode 100644 index 559e75d4f4b71..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/explorer/FileList.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import React from "react"; -import { Link } from "react-router-dom"; -import { DateWithHover } from "../common/DateWithHover"; - -interface FileInfo { - name: string; - size: number; - lastModified: string; -} - -interface FileListProps { - current: string; - parent: string; - files: FileInfo[]; - folders: string[]; -} - -function formatBytes(bytes: number): string { - if (bytes === 0) return "0 Bytes"; - const k = 1024; - const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]; -} - -export const FileList: React.FC<FileListProps> = ({ - current, - parent, - files, - folders, -}) => { - return ( - <div className="bg-white dark:bg-gray-800 shadow-md rounded-lg overflow-hidden"> - <div className="grid grid-cols-12 bg-gray-50 dark:bg-gray-700 border-b dark:border-gray-600"> - <div className="col-span-5 p-4 font-semibold text-gray-600 dark:text-gray-200"> - Name - </div> - <div className="col-span-3 p-4 font-semibold text-gray-600 dark:text-gray-200"> - Last Modified - </div> - <div className="col-span-3 p-4 font-semibold text-gray-600 dark:text-gray-200"> - Size - </div> - <div className="col-span-1 p-4"></div> - </div> - - {parent !== current && ( - <Link - to={`/?path=${encodeURIComponent(parent)}`} - className="grid grid-cols-12 border-b dark:border-gray-600 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200" - > - <div className="col-span-5 p-4 flex items-center"> - <svg - className="w-5 h-5 mr-2" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M15 19l-7-7 7-7" - /> - </svg> - .. - </div> - <div className="col-span-3 p-4">-</div> - <div className="col-span-3 p-4">-</div> - <div className="col-span-1 p-4"></div> - </Link> - )} - - {folders.map((folder) => ( - <Link - key={folder} - to={`/?path=${encodeURIComponent( - current ? `${current}/${folder}` : folder - )}`} - className="grid grid-cols-12 border-b dark:border-gray-600 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200" - > - <div className="col-span-5 p-4 flex items-center"> - <svg - className="w-5 h-5 mr-2" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" - /> - </svg> - {folder} - </div> - <div className="col-span-3 p-4">-</div> - <div className="col-span-3 p-4">-</div> - <div className="col-span-1 p-4"></div> - </Link> - ))} - - <div className="space-y-2"> - {files.map((file) => { - const filePath = current ? `${current}/${file.name}` : file.name; - - return ( - <div - key={file.name} - className="grid grid-cols-12 border-b dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 dark:text-gray-200" - > - <Link - to={`file/${encodeURIComponent(filePath)}`} - className="col-span-5 p-4 flex items-center" - > - <svg - className="w-5 h-5 mr-2" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" - /> - </svg> - {file.name} - </Link> - <div className="col-span-3 p-4"> - <DateWithHover date={new Date(file.lastModified)} /> - </div> - <div className="col-span-3 p-4">{formatBytes(file.size)}</div> - <div className="col-span-1 p-4 flex justify-center"> - <Link - to={`/api/download?file=${encodeURIComponent(filePath)}`} - target="_blank" - rel="noopener noreferrer" - className="text-gray-600 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400" - title="Download file" - > - <svg - className="w-5 h-5" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" - /> - </svg> - </Link> - </div> - </div> - ); - })} - </div> - </div> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/components/file-metadata/BackToList.tsx b/pkg/dataobj/explorer/ui/src/components/file-metadata/BackToList.tsx deleted file mode 100644 index d5ac9c8ccd40c..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/file-metadata/BackToList.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import React from "react"; -import { Link } from "react-router-dom"; - -export const BackToListButton: React.FC<{ filePath: string }> = ({ - filePath, -}) => ( - <Link - to={`/?path=${encodeURIComponent( - filePath ? filePath.split("/").slice(0, -1).join("/") : "" - )}`} - className="mb-4 p-4 inline-flex items-center text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300" - > - <svg - className="w-4 h-4 mr-1" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M15 19l-7-7 7-7" - /> - </svg> - Back to file list - </Link> -); diff --git a/pkg/dataobj/explorer/ui/src/components/file-metadata/FileMetadata.tsx b/pkg/dataobj/explorer/ui/src/components/file-metadata/FileMetadata.tsx deleted file mode 100644 index 5f0e91bd9bb02..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/file-metadata/FileMetadata.tsx +++ /dev/null @@ -1,410 +0,0 @@ -import React, { useState } from "react"; -import { formatBytes } from "../../utils/format"; -import { DateWithHover } from "../common/DateWithHover"; -import { Link } from "react-router-dom"; -import { useBasename } from "../../contexts/BasenameContext"; -import { CompressionRatio } from "./CompressionRatio"; -import { FileMetadataResponse } from "../../types/metadata"; - -interface FileMetadataProps { - metadata: FileMetadataResponse; - filename: string; - className?: string; -} - -export const FileMetadata: React.FC<FileMetadataProps> = ({ - metadata, - filename, - className = "", -}) => { - const [expandedSectionIndex, setExpandedSectionIndex] = useState< - number | null - >(null); - const [expandedColumns, setExpandedColumns] = useState< - Record<string, boolean> - >({}); - - if (metadata.error) { - return ( - <div className="p-4 bg-red-100 border border-red-400 text-red-700 rounded"> - Error: {metadata.error} - </div> - ); - } - - const toggleSection = (sectionIndex: number) => { - setExpandedSectionIndex( - expandedSectionIndex === sectionIndex ? null : sectionIndex - ); - }; - - const toggleColumn = (sectionIndex: number, columnIndex: number) => { - const key = `${sectionIndex}-${columnIndex}`; - setExpandedColumns((prev) => ({ - ...prev, - [key]: !prev[key], - })); - }; - - // Calculate file-level stats - const totalCompressed = metadata.sections.reduce( - (sum, section) => sum + section.totalCompressedSize, - 0 - ); - const totalUncompressed = metadata.sections.reduce( - (sum, section) => sum + section.totalUncompressedSize, - 0 - ); - - // Get stream and log counts from first column of each section - const streamSection = metadata.sections.filter( - (s) => s.type === "SECTION_TYPE_STREAMS" - ); - const logSection = metadata.sections.filter( - (s) => s.type === "SECTION_TYPE_LOGS" - ); - const streamCount = streamSection?.reduce( - (sum, sec) => sum + (sec.columns[0].rows_count || 0), - 0 - ); - const logCount = logSection?.reduce( - (sum, sec) => sum + (sec.columns[0].rows_count || 0), - 0 - ); - - const basename = useBasename(); - - return ( - <div className={`space-y-6 p-4 ${className}`}> - {/* Thor Dataobj File */} - <div className="bg-white dark:bg-gray-700 shadow rounded-lg"> - {/* Overview */} - <div className="p-4 border-b dark:border-gray-700"> - <div className="flex justify-between items-start mb-4"> - <div> - <h2 className="text-lg font-semibold mb-2 dark:text-gray-200"> - Thor Dataobj File - </h2> - <div className="flex flex-col gap-1"> - <p className="text-sm font-mono dark:text-gray-300"> - {filename} - </p> - {metadata.lastModified && ( - <div className="text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2"> - <span>Last modified:</span> - <DateWithHover date={new Date(metadata.lastModified)} /> - </div> - )} - </div> - </div> - <Link - to={`/api/download?file=${encodeURIComponent(filename)}`} - target="_blank" - rel="noopener noreferrer" - className="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm" - > - Download - </Link> - </div> - - <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"> - <div className="bg-gray-50 dark:bg-gray-800 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Compression - </div> - <CompressionRatio - compressed={totalCompressed} - uncompressed={totalUncompressed} - showVisualization - /> - <div className="text-xs text-gray-500 dark:text-gray-400 mt-1"> - {formatBytes(totalCompressed)} →{" "} - {formatBytes(totalUncompressed)} - </div> - </div> - <div className="bg-gray-50 dark:bg-gray-800 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Sections - </div> - <div className="font-medium">{metadata.sections.length}</div> - <div className="text-xs text-gray-500 dark:text-gray-400 mt-1"> - {metadata.sections.map((s) => s.type).join(", ")} - </div> - </div> - {streamCount && ( - <div className="bg-gray-50 dark:bg-gray-800 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Stream Count - </div> - <div className="font-medium"> - {streamCount.toLocaleString()} - </div> - </div> - )} - {logCount && ( - <div className="bg-gray-50 dark:bg-gray-800 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Log Count - </div> - <div className="font-medium">{logCount.toLocaleString()}</div> - </div> - )} - </div> - </div> - - {/* Sections */} - <div className="divide-y dark:divide-gray-900"> - {metadata.sections.map((section, sectionIndex) => ( - <div key={sectionIndex} className="dark:bg-gray-700"> - {/* Section Header */} - <div - className="p-4 cursor-pointer flex justify-between items-center hover:bg-gray-50 dark:hover:bg-gray-700" - onClick={() => toggleSection(sectionIndex)} - > - <h3 className="text-lg font-semibold dark:text-gray-200"> - Section #{sectionIndex + 1}: {section.type} - </h3> - <svg - className={`w-5 h-5 transform transition-transform duration-700 ${ - expandedSectionIndex === sectionIndex ? "rotate-180" : "" - }`} - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M19 9l-7 7-7-7" - /> - </svg> - </div> - - {/* Section Content */} - <div - className={`transition-all duration-700 ease-in-out ${ - expandedSectionIndex === sectionIndex - ? "opacity-100" - : "opacity-0 hidden" - }`} - > - <div className="p-4 bg-gray-50 dark:bg-gray-800"> - {/* Section Stats */} - <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6"> - <div className="bg-white dark:bg-gray-700 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Compression - </div> - <CompressionRatio - compressed={section.totalCompressedSize} - uncompressed={section.totalUncompressedSize} - showVisualization - /> - <div className="text-xs text-gray-500 dark:text-gray-400 mt-1"> - {formatBytes(section.totalCompressedSize)} →{" "} - {formatBytes(section.totalUncompressedSize)} - </div> - </div> - <div className="bg-white dark:bg-gray-700 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Column Count - </div> - <div className="font-medium">{section.columnCount}</div> - </div> - <div className="bg-white dark:bg-gray-700 p-3 rounded"> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Type - </div> - <div className="font-medium">{section.type}</div> - </div> - </div> - - {/* Columns */} - <div className="space-y-4"> - <h4 className="font-medium text-lg mb-4 dark:text-gray-200"> - Columns ({section.columnCount}) - </h4> - {section.columns.map((column, columnIndex) => ( - <div - key={columnIndex} - className="bg-white dark:bg-gray-700 shadow rounded-lg overflow-hidden" - > - {/* Column Header */} - <div - className="flex justify-between items-center cursor-pointer p-4 border-b dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600" - onClick={() => - toggleColumn(sectionIndex, columnIndex) - } - > - <div> - <h5 className="font-medium text-gray-900 dark:text-gray-200"> - {column.name - ? `${column.name} (${column.type})` - : column.type} - </h5> - <div className="text-sm text-gray-500 dark:text-gray-400"> - Type: {column.value_type} - </div> - </div> - <div className="flex items-center"> - <div className="text-sm font-medium text-gray-600 dark:text-gray-300 mr-4"> - Compression: {column.compression} - </div> - <svg - className={`w-4 h-4 transform transition-transform text-gray-400 ${ - expandedColumns[ - `${sectionIndex}-${columnIndex}` - ] - ? "rotate-180" - : "" - }`} - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M19 9l-7 7-7-7" - /> - </svg> - </div> - </div> - - {/* Column Content */} - {expandedColumns[`${sectionIndex}-${columnIndex}`] && ( - <div className="p-4 bg-white dark:bg-gray-700"> - {/* Column Stats */} - <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6"> - <div className="bg-gray-50 dark:bg-gray-600 p-3 rounded-lg"> - <div className="text-gray-500 dark:text-gray-400 mb-1"> - Compression ({column.compression}) - </div> - <div className="font-medium whitespace-nowrap"> - <CompressionRatio - compressed={column.compressed_size} - uncompressed={column.uncompressed_size} - /> - </div> - <div className="text-xs text-gray-500 dark:text-gray-400 mt-1"> - {formatBytes(column.compressed_size)} →{" "} - {formatBytes(column.uncompressed_size)} - </div> - </div> - <div className="bg-gray-50 dark:bg-gray-600 p-3 rounded-lg"> - <div className="text-gray-500 dark:text-gray-400 mb-1"> - Rows - </div> - <div className="font-medium"> - {column.rows_count.toLocaleString()} - </div> - </div> - <div className="bg-gray-50 dark:bg-gray-600 p-3 rounded-lg"> - <div className="text-gray-500 dark:text-gray-400 mb-1"> - Values Count - </div> - <div className="font-medium"> - {column.values_count.toLocaleString()} - </div> - </div> - <div className="bg-gray-50 dark:bg-gray-600 p-3 rounded-lg"> - <div className="text-gray-500 dark:text-gray-400 mb-1"> - Offset - </div> - <div className="font-medium"> - {formatBytes(column.metadata_offset)} - </div> - </div> - </div> - - {/* Pages */} - {column.pages.length > 0 && ( - <div className="mt-6"> - <h6 className="font-medium text-sm mb-3 dark:text-gray-200"> - Pages ({column.pages.length}) - </h6> - <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-600"> - <table className="min-w-full text-sm"> - <thead> - <tr className="bg-gray-50 dark:bg-gray-600 border-b border-gray-200 dark:border-gray-500"> - <th className="text-left p-3 font-medium text-gray-600 dark:text-gray-200"> - # - </th> - <th className="text-left p-3 font-medium text-gray-600 dark:text-gray-200"> - Rows - </th> - <th className="text-left p-3 font-medium text-gray-600 dark:text-gray-200"> - Values - </th> - <th className="text-left p-3 font-medium text-gray-600 dark:text-gray-200"> - Encoding - </th> - <th className="text-left p-3 font-medium text-gray-600 dark:text-gray-200"> - Compression - </th> - </tr> - </thead> - <tbody className="bg-white dark:bg-gray-700"> - {column.pages.map((page, pageIndex) => ( - <tr - key={pageIndex} - className="border-t border-gray-100 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600" - > - <td className="p-3 dark:text-gray-200"> - {pageIndex + 1} - </td> - <td className="p-3 dark:text-gray-200"> - {page.rows_count.toLocaleString()} - </td> - <td className="p-3 dark:text-gray-200"> - {page.values_count.toLocaleString()} - </td> - <td className="p-3 dark:text-gray-200"> - {page.encoding} - </td> - <td className="p-3"> - <div className="flex items-center gap-2"> - <CompressionRatio - compressed={ - page.compressed_size - } - uncompressed={ - page.uncompressed_size - } - /> - <span className="text-xs text-gray-500 dark:text-gray-400"> - ( - {formatBytes( - page.compressed_size - )}{" "} - →{" "} - {formatBytes( - page.uncompressed_size - )} - ) - </span> - </div> - </td> - </tr> - ))} - </tbody> - </table> - </div> - </div> - )} - </div> - )} - </div> - ))} - </div> - </div> - </div> - </div> - ))} - </div> - </div> - </div> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/components/layout/DarkModeToggle.tsx b/pkg/dataobj/explorer/ui/src/components/layout/DarkModeToggle.tsx deleted file mode 100644 index 398c11547ff73..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/layout/DarkModeToggle.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import React from "react"; - -interface DarkModeToggleProps { - isDarkMode: boolean; - onToggle: () => void; -} - -export const DarkModeToggle: React.FC<DarkModeToggleProps> = ({ - isDarkMode, - onToggle, -}) => { - return ( - <button - onClick={onToggle} - className="p-2 rounded-lg bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors" - aria-label={isDarkMode ? "Switch to light mode" : "Switch to dark mode"} - > - {isDarkMode ? ( - <svg - className="w-6 h-6" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" - /> - </svg> - ) : ( - <svg - className="w-6 h-6" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" - /> - </svg> - )} - </button> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/components/layout/Layout.tsx b/pkg/dataobj/explorer/ui/src/components/layout/Layout.tsx deleted file mode 100644 index 83b41f9f9941f..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/layout/Layout.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import React, { useEffect, useState } from "react"; -import { DarkModeToggle } from "./DarkModeToggle"; -import { Breadcrumb } from "./Breadcrumb"; -import { ScrollToTopButton } from "./ScrollToTopButton"; - -interface LayoutProps { - children: React.ReactNode; - breadcrumbParts?: string[]; - isLastBreadcrumbClickable?: boolean; -} - -export const Layout: React.FC<LayoutProps> = ({ - children, - breadcrumbParts = [], - isLastBreadcrumbClickable = true, -}) => { - const [isDarkMode, setIsDarkMode] = useState(() => { - const savedTheme = localStorage.getItem("theme"); - const systemPreference = window.matchMedia( - "(prefers-color-scheme: dark)" - ).matches; - return savedTheme ? savedTheme === "dark" : systemPreference; - }); - - useEffect(() => { - document.documentElement.classList.toggle("dark", isDarkMode); - localStorage.setItem("theme", isDarkMode ? "dark" : "light"); - }, [isDarkMode]); - - return ( - <div - className={`min-h-screen ${ - isDarkMode - ? "dark:bg-gray-900 dark:text-gray-200" - : "bg-white text-black" - }`} - > - <div className="container mx-auto px-4 py-8"> - <div className="flex justify-between items-center mb-6"> - <Breadcrumb - parts={breadcrumbParts} - isLastPartClickable={isLastBreadcrumbClickable} - /> - <DarkModeToggle - isDarkMode={isDarkMode} - onToggle={() => setIsDarkMode(!isDarkMode)} - /> - </div> - {children} - <ScrollToTopButton /> - </div> - </div> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/components/layout/ScrollToTopButton.tsx b/pkg/dataobj/explorer/ui/src/components/layout/ScrollToTopButton.tsx deleted file mode 100644 index c145bb6c904ca..0000000000000 --- a/pkg/dataobj/explorer/ui/src/components/layout/ScrollToTopButton.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React, { useState, useEffect } from "react"; - -export const ScrollToTopButton: React.FC = () => { - const [show, setShow] = useState(false); - - useEffect(() => { - const handleScroll = () => { - setShow(window.scrollY > 300); - }; - - window.addEventListener("scroll", handleScroll); - return () => window.removeEventListener("scroll", handleScroll); - }, []); - - const scrollToTop = () => { - window.scrollTo({ - top: 0, - behavior: "smooth", - }); - }; - - if (!show) return null; - - return ( - <button - onClick={scrollToTop} - className="fixed bottom-8 right-8 bg-blue-500 dark:bg-blue-600 hover:bg-blue-600 dark:hover:bg-blue-700 text-white rounded-full p-3 shadow-lg transition-all duration-300" - aria-label="Back to top" - > - <svg - className="w-6 h-6" - fill="none" - stroke="currentColor" - viewBox="0 0 24 24" - > - <path - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="M5 10l7-7m0 0l7 7m-7-7v18" - /> - </svg> - </button> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/contexts/BasenameContext.tsx b/pkg/dataobj/explorer/ui/src/contexts/BasenameContext.tsx deleted file mode 100644 index f435f8bf201dd..0000000000000 --- a/pkg/dataobj/explorer/ui/src/contexts/BasenameContext.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import React, { createContext, useContext } from "react"; - -interface BasenameContextType { - basename: string; -} - -const BasenameContext = createContext<BasenameContextType | undefined>( - undefined -); - -export function useBasename() { - const context = useContext(BasenameContext); - if (context === undefined) { - throw new Error("useBasename must be used within a BasenameProvider"); - } - return context.basename; -} - -export function BasenameProvider({ - basename, - children, -}: { - basename: string; - children: React.ReactNode; -}) { - return ( - <BasenameContext.Provider value={{ basename }}> - {children} - </BasenameContext.Provider> - ); -} diff --git a/pkg/dataobj/explorer/ui/src/hooks/useExplorerData.ts b/pkg/dataobj/explorer/ui/src/hooks/useExplorerData.ts deleted file mode 100644 index 5ce22e24a398e..0000000000000 --- a/pkg/dataobj/explorer/ui/src/hooks/useExplorerData.ts +++ /dev/null @@ -1,57 +0,0 @@ -import React, { useMemo } from "react"; -import { useBasename } from "../contexts/BasenameContext"; -import { ListResponse, FileInfo } from "../types/explorer"; - -const sortFilesByDate = (files: FileInfo[]): FileInfo[] => { - return [...files].sort( - (a, b) => - new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime() - ); -}; - -interface UseExplorerDataResult { - data: ListResponse | null; - loading: boolean; - error: string | null; -} - -export const useExplorerData = (path: string): UseExplorerDataResult => { - const [rawData, setRawData] = React.useState<ListResponse | null>(null); - const [loading, setLoading] = React.useState(true); - const [error, setError] = React.useState<string | null>(null); - const basename = useBasename(); - - // Memoize the sorted data - const data = useMemo(() => { - if (!rawData) return null; - return { - ...rawData, - files: sortFilesByDate(rawData.files), - }; - }, [rawData]); - - React.useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await fetch( - `${basename}api/list?path=${encodeURIComponent(path)}` - ); - if (!response.ok) { - throw new Error("Failed to fetch data"); - } - const json = (await response.json()) as ListResponse; - setRawData(json); - setError(null); - } catch (err) { - setError(err instanceof Error ? err.message : "An error occurred"); - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [path, basename]); - - return { data, loading, error }; -}; diff --git a/pkg/dataobj/explorer/ui/src/hooks/useFileMetadata.ts b/pkg/dataobj/explorer/ui/src/hooks/useFileMetadata.ts deleted file mode 100644 index f3783b38a4b75..0000000000000 --- a/pkg/dataobj/explorer/ui/src/hooks/useFileMetadata.ts +++ /dev/null @@ -1,46 +0,0 @@ -import React from "react"; -import { useBasename } from "../contexts/BasenameContext"; -import { FileMetadataResponse } from "../types/metadata"; - -interface UseFileMetadataResult { - metadata: FileMetadataResponse | null; - loading: boolean; - error: string | null; -} - -export const useFileMetadata = ( - filePath: string | undefined -): UseFileMetadataResult => { - const [metadata, setMetadata] = React.useState<FileMetadataResponse | null>( - null - ); - const [loading, setLoading] = React.useState(true); - const [error, setError] = React.useState<string | null>(null); - const basename = useBasename(); - - React.useEffect(() => { - const fetchMetadata = async () => { - if (!filePath) return; - try { - setLoading(true); - const response = await fetch( - `${basename}api/inspect?file=${encodeURIComponent(filePath)}` - ); - if (!response.ok) { - throw new Error(`Failed to fetch metadata: ${response.statusText}`); - } - const data = await response.json(); - setMetadata(data); - setError(null); - } catch (err) { - setError(err instanceof Error ? err.message : "An error occurred"); - } finally { - setLoading(false); - } - }; - - fetchMetadata(); - }, [filePath, basename]); - - return { metadata, loading, error }; -}; diff --git a/pkg/dataobj/explorer/ui/src/index.css b/pkg/dataobj/explorer/ui/src/index.css deleted file mode 100644 index b5c61c956711f..0000000000000 --- a/pkg/dataobj/explorer/ui/src/index.css +++ /dev/null @@ -1,3 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; diff --git a/pkg/dataobj/explorer/ui/src/main.tsx b/pkg/dataobj/explorer/ui/src/main.tsx deleted file mode 100644 index fcdc60105ea11..0000000000000 --- a/pkg/dataobj/explorer/ui/src/main.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import React from "react"; -import ReactDOM from "react-dom/client"; -import { - createBrowserRouter, - RouterProvider, - type RouterProviderProps, -} from "react-router-dom"; -import App from "./App"; -import { ExplorerPage } from "./pages/ExplorerPage"; -import { FileMetadataPage } from "./pages/FileMetadataPage"; -import { BasenameProvider } from "./contexts/BasenameContext"; -import "./index.css"; - -// Extract basename from current URL by matching everything up to and including /dataobj/explorer -const pathname = window.location.pathname; -const match = pathname.match(/(.*\/dataobj\/explorer\/)/); -const basename = match?.[1] || "/dataobj/explorer/"; - -const router = createBrowserRouter( - [ - { - path: "*", - element: <App />, - children: [ - { - index: true, - element: <ExplorerPage />, - }, - { - path: "file/:filePath", - element: <FileMetadataPage />, - }, - ], - }, - ], - { - basename, - future: { - v7_relativeSplatPath: true, - }, - } -); - -ReactDOM.createRoot(document.getElementById("root")!).render( - <React.StrictMode> - <BasenameProvider basename={basename}> - <RouterProvider - router={router} - future={{ - v7_startTransition: true, - }} - /> - </BasenameProvider> - </React.StrictMode> -); diff --git a/pkg/dataobj/explorer/ui/src/pages/ExplorerPage.tsx b/pkg/dataobj/explorer/ui/src/pages/ExplorerPage.tsx deleted file mode 100644 index 08daacf736fa0..0000000000000 --- a/pkg/dataobj/explorer/ui/src/pages/ExplorerPage.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import React from "react"; -import { useSearchParams } from "react-router-dom"; -import { FileList } from "../components/explorer/FileList"; -import { Layout } from "../components/layout/Layout"; -import { LoadingContainer } from "../components/common/LoadingContainer"; -import { ErrorContainer } from "../components/common/ErrorContainer"; -import { useExplorerData } from "../hooks/useExplorerData"; - -export const ExplorerPage: React.FC = () => { - const [searchParams] = useSearchParams(); - const path = searchParams.get("path") || ""; - const { data, loading, error } = useExplorerData(path); - - // Get path parts for breadcrumb - const pathParts = React.useMemo( - () => (data?.current || "").split("/").filter(Boolean), - [data?.current] - ); - - return ( - <Layout breadcrumbParts={pathParts} isLastBreadcrumbClickable={true}> - <div className="relative" style={{ overflow: "visible" }}> - {loading ? ( - <LoadingContainer fullScreen /> - ) : error ? ( - <ErrorContainer message={error} fullScreen /> - ) : data ? ( - <div className="relative" style={{ overflow: "visible" }}> - <FileList - current={data.current} - parent={data.parent} - files={data.files} - folders={data.folders} - /> - </div> - ) : null} - </div> - </Layout> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/pages/FileMetadataPage.tsx b/pkg/dataobj/explorer/ui/src/pages/FileMetadataPage.tsx deleted file mode 100644 index 19fa181e75354..0000000000000 --- a/pkg/dataobj/explorer/ui/src/pages/FileMetadataPage.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import React from "react"; -import { useParams } from "react-router-dom"; -import { FileMetadata } from "../components/file-metadata/FileMetadata"; -import { Layout } from "../components/layout/Layout"; -import { BackToListButton } from "../components/file-metadata/BackToList"; -import { LoadingContainer } from "../components/common/LoadingContainer"; -import { ErrorContainer } from "../components/common/ErrorContainer"; -import { useFileMetadata } from "../hooks/useFileMetadata"; - -export const FileMetadataPage: React.FC = () => { - const { filePath } = useParams<{ filePath: string }>(); - const { metadata, loading, error } = useFileMetadata(filePath); - const pathParts = React.useMemo( - () => (filePath || "").split("/").filter(Boolean), - [filePath] - ); - - return ( - <Layout breadcrumbParts={pathParts} isLastBreadcrumbClickable={false}> - <div className="bg-gray-50 dark:bg-gray-800 shadow-md rounded-lg overflow-hidden dark:text-gray-200"> - {loading ? ( - <LoadingContainer /> - ) : error ? ( - <ErrorContainer message={error} /> - ) : ( - <> - <BackToListButton filePath={filePath || ""} /> - {metadata && filePath && ( - <FileMetadata - metadata={metadata} - filename={filePath} - className="dark:bg-gray-800 dark:text-gray-200" - /> - )} - </> - )} - </div> - </Layout> - ); -}; diff --git a/pkg/dataobj/explorer/ui/src/types/explorer.ts b/pkg/dataobj/explorer/ui/src/types/explorer.ts deleted file mode 100644 index 84d90c608bfa2..0000000000000 --- a/pkg/dataobj/explorer/ui/src/types/explorer.ts +++ /dev/null @@ -1,12 +0,0 @@ -export interface FileInfo { - name: string; - size: number; - lastModified: string; -} - -export interface ListResponse { - files: FileInfo[]; - folders: string[]; - parent: string; - current: string; -} diff --git a/pkg/dataobj/explorer/ui/src/utils/format.ts b/pkg/dataobj/explorer/ui/src/utils/format.ts deleted file mode 100644 index 348dde3359588..0000000000000 --- a/pkg/dataobj/explorer/ui/src/utils/format.ts +++ /dev/null @@ -1,9 +0,0 @@ -export function formatBytes(bytes: number): string { - if (bytes === 0) return "0 B"; - - const k = 1024; - const sizes = ["B", "KiB", "MiB", "GiB", "TiB"]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - - return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`; -} diff --git a/pkg/dataobj/explorer/ui/tailwind.config.js b/pkg/dataobj/explorer/ui/tailwind.config.js deleted file mode 100644 index f19dbe9d971ca..0000000000000 --- a/pkg/dataobj/explorer/ui/tailwind.config.js +++ /dev/null @@ -1,12 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -module.exports = { - darkMode: 'class', - content: [ - "./index.html", - "./src/**/*.{js,ts,jsx,tsx}", - ], - theme: { - extend: {}, - }, - plugins: [], -} diff --git a/pkg/dataobj/explorer/ui/vite.config.ts b/pkg/dataobj/explorer/ui/vite.config.ts deleted file mode 100644 index 456e8a1457fba..0000000000000 --- a/pkg/dataobj/explorer/ui/vite.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig } from "vite"; -import react from "@vitejs/plugin-react"; - -export default defineConfig({ - plugins: [react()], - base: "/dataobj/explorer/", - css: { - postcss: "./postcss.config.js", - }, - build: { - outDir: "../dist", - emptyOutDir: true, - cssCodeSplit: false, - }, - server: { - proxy: { - "/dataobj/explorer/api": "http://localhost:3100", - }, - }, -}); diff --git a/pkg/kafka/partitionring/partition_ring.go b/pkg/kafka/partitionring/partition_ring.go index 542a4aee80a41..c32b89a0f0236 100644 --- a/pkg/kafka/partitionring/partition_ring.go +++ b/pkg/kafka/partitionring/partition_ring.go @@ -54,7 +54,7 @@ func (cfg *Config) ToLifecyclerConfig(partitionID int32, instanceID string) ring // ExtractIngesterPartitionID returns the partition ID owner the the given ingester. func ExtractIngesterPartitionID(ingesterID string) (int32, error) { - if strings.Contains(ingesterID, "local") { + if strings.Contains(ingesterID, "local") || strings.HasSuffix(ingesterID, ".lan") { return 0, nil } diff --git a/pkg/loki/loki.go b/pkg/loki/loki.go index 7e4f5e318fea6..3fe0b0a6822b7 100644 --- a/pkg/loki/loki.go +++ b/pkg/loki/loki.go @@ -65,6 +65,7 @@ import ( "github.com/grafana/loki/v3/pkg/storage/stores/series/index" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" "github.com/grafana/loki/v3/pkg/tracing" + "github.com/grafana/loki/v3/pkg/ui" "github.com/grafana/loki/v3/pkg/util" "github.com/grafana/loki/v3/pkg/util/constants" "github.com/grafana/loki/v3/pkg/util/fakeauth" @@ -84,6 +85,7 @@ type Config struct { Server server.Config `yaml:"server,omitempty"` InternalServer internalserver.Config `yaml:"internal_server,omitempty" doc:"hidden"` + UI ui.Config `yaml:"ui,omitempty"` Distributor distributor.Config `yaml:"distributor,omitempty"` Querier querier.Config `yaml:"querier,omitempty"` QueryScheduler scheduler.Config `yaml:"query_scheduler"` @@ -192,6 +194,7 @@ func (c *Config) RegisterFlags(f *flag.FlagSet) { c.KafkaConfig.RegisterFlags(f) c.BlockBuilder.RegisterFlags(f) c.BlockScheduler.RegisterFlags(f) + c.UI.RegisterFlags(f) c.DataObj.RegisterFlags(f) } @@ -316,6 +319,10 @@ func (c *Config) Validate() error { errs = append(errs, errors.Wrap(err, "CONFIG ERROR: invalid distributor config")) } + if err := c.UI.Validate(); err != nil { + errs = append(errs, errors.Wrap(err, "CONFIG ERROR: invalid ui config")) + } + errs = append(errs, validateSchemaValues(c)...) errs = append(errs, ValidateConfigCompatibility(*c)...) errs = append(errs, validateBackendAndLegacyReadMode(c)...) @@ -360,6 +367,7 @@ type Loki struct { Server *server.Server InternalServer *server.Server + UI *ui.Service ring *ring.Ring Overrides limiter.CombinedLimits tenantConfigs *runtime.TenantConfigs @@ -712,6 +720,7 @@ func (t *Loki) setupModuleManager() error { mm.RegisterModule(BlockBuilder, t.initBlockBuilder) mm.RegisterModule(BlockScheduler, t.initBlockScheduler) mm.RegisterModule(DataObjExplorer, t.initDataObjExplorer) + mm.RegisterModule(UI, t.initUI) mm.RegisterModule(DataObjConsumer, t.initDataObjConsumer) mm.RegisterModule(All, nil) @@ -724,42 +733,43 @@ func (t *Loki) setupModuleManager() error { Ring: {RuntimeConfig, Server, MemberlistKV}, Analytics: {}, Overrides: {RuntimeConfig}, - OverridesExporter: {Overrides, Server}, + OverridesExporter: {Overrides, Server, UI}, TenantConfigs: {RuntimeConfig}, - Distributor: {Ring, Server, Overrides, TenantConfigs, PatternRingClient, PatternIngesterTee, Analytics, PartitionRing}, + UI: {Server}, + Distributor: {Ring, Server, Overrides, TenantConfigs, PatternRingClient, PatternIngesterTee, Analytics, PartitionRing, UI}, Store: {Overrides, IndexGatewayRing}, - Ingester: {Store, Server, MemberlistKV, TenantConfigs, Analytics, PartitionRing}, - Querier: {Store, Ring, Server, IngesterQuerier, PatternRingClient, Overrides, Analytics, CacheGenerationLoader, QuerySchedulerRing}, + Ingester: {Store, Server, MemberlistKV, TenantConfigs, Analytics, PartitionRing, UI}, + Querier: {Store, Ring, Server, IngesterQuerier, PatternRingClient, Overrides, Analytics, CacheGenerationLoader, QuerySchedulerRing, UI}, QueryFrontendTripperware: {Server, Overrides, TenantConfigs}, - QueryFrontend: {QueryFrontendTripperware, Analytics, CacheGenerationLoader, QuerySchedulerRing}, - QueryScheduler: {Server, Overrides, MemberlistKV, Analytics, QuerySchedulerRing}, - Ruler: {Ring, Server, RulerStorage, RuleEvaluator, Overrides, TenantConfigs, Analytics}, + QueryFrontend: {QueryFrontendTripperware, Analytics, CacheGenerationLoader, QuerySchedulerRing, UI}, + QueryScheduler: {Server, Overrides, MemberlistKV, Analytics, QuerySchedulerRing, UI}, + Ruler: {Ring, Server, RulerStorage, RuleEvaluator, Overrides, TenantConfigs, Analytics, UI}, RuleEvaluator: {Ring, Server, Store, IngesterQuerier, Overrides, TenantConfigs, Analytics}, - TableManager: {Server, Analytics}, - Compactor: {Server, Overrides, MemberlistKV, Analytics}, - IndexGateway: {Server, Store, BloomStore, IndexGatewayRing, IndexGatewayInterceptors, Analytics}, - BloomGateway: {Server, BloomStore, Analytics}, - BloomPlanner: {Server, BloomStore, Analytics, Store}, - BloomBuilder: {Server, BloomStore, Analytics, Store}, + TableManager: {Server, Analytics, UI}, + Compactor: {Server, Overrides, MemberlistKV, Analytics, UI}, + IndexGateway: {Server, Store, BloomStore, IndexGatewayRing, IndexGatewayInterceptors, Analytics, UI}, + BloomGateway: {Server, BloomStore, Analytics, UI}, + BloomPlanner: {Server, BloomStore, Analytics, Store, UI}, + BloomBuilder: {Server, BloomStore, Analytics, Store, UI}, BloomStore: {IndexGatewayRing, BloomGatewayClient}, PatternRingClient: {Server, MemberlistKV, Analytics}, PatternIngesterTee: {Server, Overrides, MemberlistKV, Analytics, PatternRingClient}, - PatternIngester: {Server, MemberlistKV, Analytics, PatternRingClient, PatternIngesterTee, Overrides}, + PatternIngester: {Server, MemberlistKV, Analytics, PatternRingClient, PatternIngesterTee, Overrides, UI}, IngesterQuerier: {Ring, PartitionRing, Overrides}, QuerySchedulerRing: {Overrides, MemberlistKV}, IndexGatewayRing: {Overrides, MemberlistKV}, PartitionRing: {MemberlistKV, Server, Ring}, MemberlistKV: {Server}, - BlockBuilder: {PartitionRing, Store, Server}, - BlockScheduler: {Server}, - DataObjExplorer: {Server}, - DataObjConsumer: {PartitionRing, Server}, + BlockBuilder: {PartitionRing, Store, Server, UI}, + BlockScheduler: {Server, UI}, + DataObjExplorer: {Server, UI}, + DataObjConsumer: {PartitionRing, Server, UI}, Read: {QueryFrontend, Querier}, Write: {Ingester, Distributor, PatternIngester}, Backend: {QueryScheduler, Ruler, Compactor, IndexGateway, BloomPlanner, BloomBuilder, BloomGateway}, - All: {QueryScheduler, QueryFrontend, Querier, Ingester, PatternIngester, Distributor, Ruler, Compactor}, + All: {QueryScheduler, QueryFrontend, Querier, Ingester, PatternIngester, Distributor, Ruler, Compactor, UI}, } if t.Cfg.Querier.PerRequestLimitsEnabled { diff --git a/pkg/loki/modules.go b/pkg/loki/modules.go index 3927a526e9faf..e7ec9d5997810 100644 --- a/pkg/loki/modules.go +++ b/pkg/loki/modules.go @@ -35,6 +35,8 @@ import ( "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/collectors/version" "github.com/prometheus/common/model" + "golang.org/x/net/http2" + "golang.org/x/net/http2/h2c" "github.com/thanos-io/objstore" @@ -89,6 +91,7 @@ import ( boltdbcompactor "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/boltdb/compactor" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" "github.com/grafana/loki/v3/pkg/storage/types" + "github.com/grafana/loki/v3/pkg/ui" "github.com/grafana/loki/v3/pkg/util/constants" "github.com/grafana/loki/v3/pkg/util/httpreq" "github.com/grafana/loki/v3/pkg/util/limiter" @@ -148,6 +151,7 @@ const ( BlockScheduler = "block-scheduler" DataObjExplorer = "dataobj-explorer" DataObjConsumer = "dataobj-consumer" + UI = "ui" All = "all" Read = "read" Write = "write" @@ -207,6 +211,7 @@ func (t *Loki) initServer() (services.Service, error) { }(t.Server.HTTPServer.Handler) t.Server.HTTPServer.Handler = middleware.Merge(serverutil.RecoveryHTTPMiddleware).Wrap(h) + t.Server.HTTPServer.Handler = h2c.NewHandler(t.Server.HTTPServer.Handler, &http2.Server{}) if t.Cfg.Server.HTTPListenPort == 0 { t.Cfg.Server.HTTPListenPort = portFromAddr(t.Server.HTTPListenAddr().String()) @@ -1533,10 +1538,11 @@ func (t *Loki) initCompactor() (services.Service, error) { t.compactor.RegisterIndexCompactor(types.BoltDBShipperType, boltdbcompactor.NewIndexCompactor()) t.compactor.RegisterIndexCompactor(types.TSDBType, tsdb.NewIndexCompactor()) - t.Server.HTTP.Path("/compactor/ring").Methods("GET", "POST").Handler(t.compactor) + prefix, compactorHandler := t.compactor.Handler() + t.Server.HTTP.PathPrefix(prefix).Handler(compactorHandler) if t.Cfg.InternalServer.Enable { - t.InternalServer.HTTP.Path("/compactor/ring").Methods("GET", "POST").Handler(t.compactor) + t.InternalServer.HTTP.PathPrefix(prefix).Handler(compactorHandler) } if t.Cfg.CompactorConfig.RetentionEnabled { @@ -1551,7 +1557,7 @@ func (t *Loki) initCompactor() (services.Service, error) { } func (t *Loki) addCompactorMiddleware(h http.HandlerFunc) http.Handler { - return t.HTTPAuthMiddleware.Wrap(deletion.TenantMiddleware(t.Overrides, h)) + return middleware.Merge(t.HTTPAuthMiddleware, deletion.TenantMiddleware(t.Overrides)).Wrap(h) } func (t *Loki) initBloomGateway() (services.Service, error) { @@ -1938,11 +1944,21 @@ func (t *Loki) initDataObjExplorer() (services.Service, error) { if err != nil { return nil, err } - - t.Server.HTTP.PathPrefix("/dataobj/explorer/").Handler(explorer.Handler()) + path, handler := explorer.Handler() + t.Server.HTTP.PathPrefix(path).Handler(handler) return explorer, nil } +func (t *Loki) initUI() (services.Service, error) { + t.Cfg.UI = t.Cfg.UI.WithAdvertisePort(t.Cfg.Server.HTTPListenPort) + svc, err := ui.NewService(t.Cfg.UI, t.Server.HTTP, log.With(util_log.Logger, "component", "ui")) + if err != nil { + return nil, err + } + t.UI = svc + return svc, nil +} + func (t *Loki) initDataObjConsumer() (services.Service, error) { if !t.Cfg.Ingester.KafkaIngestion.Enabled { return nil, nil diff --git a/pkg/ui/README.md b/pkg/ui/README.md new file mode 100644 index 0000000000000..5e08cbd94886d --- /dev/null +++ b/pkg/ui/README.md @@ -0,0 +1,243 @@ +# Loki UI Architecture in Distributed Mode + +## Overview + +Loki's UI system is designed to work seamlessly in a distributed environment where multiple Loki nodes can serve the UI and proxy requests to other nodes in the cluster. The system uses [ckit](https://github.com/grafana/ckit) for cluster membership and discovery, allowing any node to serve as an entry point for the UI while maintaining the ability to interact with all nodes in the cluster. + +## Key Components + +### 1. Node Discovery and Clustering + +- Uses `ckit` for cluster membership and discovery +- Each node advertises itself and maintains a list of peers +- Nodes can join and leave the cluster dynamically +- Periodic rejoin mechanism to handle split-brain scenarios + +### 2. UI Service Components + +- **Static UI Files**: Embedded React frontend served from each node +- **API Layer**: REST endpoints for cluster state and proxying +- **Proxy System**: Allows forwarding requests to specific nodes +- **Service Discovery**: Tracks available nodes and their services + +## Architecture Diagram + +```mermaid +graph TB + LB[Reverse Proxy /ui/] + + subgraph Cluster[Loki Cluster] + subgraph Node1[Node 1] + UI1[UI Frontend] + API1[API Server] + PROXY1[Proxy Handler] + CKIT1[ckit Node] + end + + subgraph Node2[Node 2] + UI2[UI Frontend] + API2[API Server] + PROXY2[Proxy Handler] + CKIT2[ckit Node] + end + + subgraph Node3[Node 3] + UI3[UI Frontend] + API3[API Server] + PROXY3[Proxy Handler] + CKIT3[ckit Node] + end + end + + LB --> Node1 + LB --> Node2 + LB --> Node3 + + CKIT1 --- CKIT2 + CKIT2 --- CKIT3 + CKIT3 --- CKIT1 +``` + +## API Endpoints + +All endpoints are prefixed with `/ui/` + +### Cluster Management + +- `GET /ui/api/v1/cluster/nodes` + - Returns the state of all nodes in the cluster + - Response includes node status, services, and build information + +- `GET /ui/api/v1/cluster/nodes/self/details` + - Returns detailed information about the current node + - Includes configuration, analytics, and system information + +### Proxy System + +- `GET /ui/api/v1/proxy/{nodename}/*` + - Proxies requests to specific nodes in the cluster + - Maintains original request path after the node name + +### Analytics + +- `GET /ui/api/v1/analytics` + - Returns analytics data for the node + +### Static UI + +- `GET /ui/*` + - Serves the React frontend application + - Falls back to index.html for client-side routing + +## Request Flow Examples + +### Example 1: Viewing Cluster Status + +1. User accesses `http://loki-cluster/ui/` +2. Frontend loads and makes request to `/ui/api/v1/cluster/nodes` +3. Node handling the request: + - Queries all peers using ckit + - Collects status from each node + - Returns consolidated cluster state + +```sequence +Browser->Node 1: GET /ui/api/v1/cluster/nodes +Node 1->Node 2: Fetch status +Node 1->Node 3: Fetch status +Node 2-->Node 1: Status response +Node 3-->Node 1: Status response +Node 1-->Browser: Combined cluster state +``` + +### Example 2: Accessing Node-Specific Service + +1. User requests service data from specific node +2. Frontend makes request to `/ui/api/v1/proxy/{nodename}/services` +3. Request is proxied to target node +4. Response returns directly to client + +```sequence +Browser->Node 1: GET /ui/api/v1/proxy/node2/services +Node 1->Node 2: Proxy request +Node 2-->Node 1: Service data +Node 1-->Browser: Proxied response +``` + +## Configuration + +The UI service can be configured with the following key parameters: + +```yaml +ui: + node_name: <string> # Name for this node in the cluster + advertise_addr: <string> # IP address to advertise + interface_names: <[]string> # Network interfaces to use + rejoin_interval: <duration> # How often to rejoin cluster + cluster_name: <string> # Cluster identifier + discovery: + join_peers: <[]string> # Initial peers to join +``` + +## Security Considerations + +1. The UI endpoints should be protected behind authentication +2. The `/ui/` prefix allows easy reverse proxy configuration +3. Node-to-node communication should be restricted to internal network + +## High Availability + +- Any node can serve the UI +- Nodes automatically discover each other +- Periodic rejoin handles split-brain scenarios +- Load balancer can distribute traffic across nodes + +## Best Practices + +1. Configure a reverse proxy in front of the Loki cluster +2. Use consistent node names across the cluster +3. Configure appropriate rejoin intervals based on cluster size +4. Monitor cluster state for node health +5. Use internal network for node-to-node communication + +## Concrete Example: Ring UI via Querier + +### Ring UI Overview + +The Ring UI is a critical component for understanding the state of Loki's distributed hash ring. Here's how it works when accessed through a querier node. Since each ingester maintains the complete ring state, querying a single ingester is sufficient to view the entire ring: + +### Component Interaction + +```mermaid +sequenceDiagram + participant Browser + participant Querier Node + participant Ingester + + Browser->>Querier Node: GET /ui/ + Browser->>Querier Node: GET /ui/api/v1/cluster/nodes + Querier Node-->>Browser: List of available nodes + + Note over Browser,Querier Node: User clicks on Ring view + + Browser->>Querier Node: GET /ui/api/v1/proxy/querier-1/ring + + Note over Querier Node: Querier fetches ring state + + Querier Node->>Ingester: Get ring status + Ingester-->>Querier Node: Complete ring state + + Querier Node-->>Browser: Ring state +``` + +### Request Flow Details + +1. **Initial UI Load** + + ```http + GET /ui/ + GET /ui/api/v1/cluster/nodes + ``` + + - Frontend loads and discovers available nodes + - UI shows querier node in the node list + +2. **Ring State Request** + + ```http + GET /ui/api/v1/proxy/querier-1/ring + ``` + + - Frontend requests ring state through the proxy endpoint + - Request is forwarded to the querier's ring endpoint + - Querier gets complete ring state from a single ingester + +3. **Ring Data Structure** + + ```json + { + "tokens": [ + { + "token": "123456", + "ingester": "ingester-1", + "state": "ACTIVE", + "timestamp": "2024-02-04T12:00:00Z" + }, + // ... more tokens + ], + "ingesters": { + "ingester-1": { + "state": "ACTIVE", + "tokens": ["123456", "789012"], + "address": "ingester-1:3100", + "last_heartbeat": "2024-02-04T12:00:00Z" + } + // ... more ingesters + } + } + ``` + +### Security Notes + +1. Ring access should be restricted to authorized users +2. Internal ring communication uses HTTP/2 +3. Ring state contains sensitive cluster information diff --git a/pkg/ui/cluster.go b/pkg/ui/cluster.go new file mode 100644 index 0000000000000..94501f618278a --- /dev/null +++ b/pkg/ui/cluster.go @@ -0,0 +1,351 @@ +package ui + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync" + + "github.com/grafana/ckit/peer" + "golang.org/x/sync/errgroup" + "gopkg.in/yaml.v3" + + "github.com/grafana/loki/v3/pkg/analytics" +) + +// Cluster represents a collection of cluster members. +type Cluster struct { + Members map[string]Member `json:"members"` +} + +// Member represents a node in the cluster with its current state and capabilities. +type Member struct { + Addr string `json:"addr"` + State string `json:"state"` + IsSelf bool `json:"isSelf"` + Target string `json:"target"` + Services []ServiceState `json:"services"` + Build BuildInfo `json:"build"` + Error error `json:"error,omitempty"` + Ready ReadyResponse `json:"ready,omitempty"` + + configBody string +} + +// ServiceState represents the current state of a service running on a member. +type ServiceState struct { + Service string `json:"service"` + Status string `json:"status"` +} + +// BuildInfo contains version and build information about a member. +type BuildInfo struct { + Version string `json:"version"` + Revision string `json:"revision"` + Branch string `json:"branch"` + BuildUser string `json:"buildUser"` + BuildDate string `json:"buildDate"` + GoVersion string `json:"goVersion"` +} + +// fetchClusterMembers retrieves the state of all members in the cluster. +// It uses an errgroup to fetch member states concurrently with a limit of 16 concurrent operations. +func (s *Service) fetchClusterMembers(ctx context.Context) (Cluster, error) { + var cluster Cluster + cluster.Members = make(map[string]Member) + + g, ctx := errgroup.WithContext(ctx) + g.SetLimit(16) + + // Use a mutex to protect concurrent map access + var mu sync.Mutex + + for _, p := range s.node.Peers() { + peer := p // Create new variable to avoid closure issues + g.Go(func() error { + member, err := s.fetchMemberState(ctx, peer) + if err != nil { + member.Error = err + } + mu.Lock() + cluster.Members[peer.Name] = member + mu.Unlock() + return nil + }) + } + + if err := g.Wait(); err != nil { + return Cluster{}, fmt.Errorf("fetching cluster members: %w", err) + } + return cluster, nil +} + +// fetchMemberState retrieves the complete state of a single cluster member. +func (s *Service) fetchMemberState(ctx context.Context, peer peer.Peer) (Member, error) { + member := Member{ + Addr: peer.Addr, + IsSelf: peer.Self, + State: peer.State.String(), + } + + config, err := s.fetchConfig(ctx, peer) + if err != nil { + return member, fmt.Errorf("fetching config: %w", err) + } + member.configBody = config + member.Target = parseTargetFromConfig(config) + + services, err := s.fetchServices(ctx, peer) + if err != nil { + return member, fmt.Errorf("fetching services: %w", err) + } + member.Services = services + + build, err := s.fetchBuild(ctx, peer) + if err != nil { + return member, fmt.Errorf("fetching build info: %w", err) + } + member.Build = build + + readyResp, err := s.checkNodeReadiness(ctx, peer.Name) + if err != nil { + return member, fmt.Errorf("checking node readiness: %w", err) + } + member.Ready = readyResp + + return member, nil +} + +// buildProxyPath constructs the proxy URL path for a given peer and endpoint. +func (s *Service) buildProxyPath(peer peer.Peer, endpoint string) string { + // todo support configured server prefix. + return fmt.Sprintf("http://%s/ui/api/v1/proxy/%s%s", s.localAddr, peer.Name, endpoint) +} + +// readResponseError checks the HTTP response for errors and returns an appropriate error message. +// If the response status is not OK, it reads and includes the response body in the error message. +func readResponseError(resp *http.Response, operation string) error { + if resp == nil { + return fmt.Errorf("%s: no response received", operation) + } + if resp.StatusCode != http.StatusOK { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("%s failed: %s, error reading body: %v", operation, resp.Status, err) + } + return fmt.Errorf("%s failed: %s, response: %s", operation, resp.Status, string(body)) + } + return nil +} + +// NodeDetails contains the details of a node in the cluster. +// It adds on top of Member the config, build, clusterID, clusterSeededAt, os, arch, edition and registered analytics metrics. +type NodeDetails struct { + Member + Config string `json:"config"` + ClusterID string `json:"clusterID"` + ClusterSeededAt int64 `json:"clusterSeededAt"` + OS string `json:"os"` + Arch string `json:"arch"` + Edition string `json:"edition"` + Metrics map[string]interface{} `json:"metrics"` +} + +func (s *Service) fetchSelfDetails(ctx context.Context) (NodeDetails, error) { + peer, ok := s.getSelfPeer() + if !ok { + return NodeDetails{}, fmt.Errorf("self peer not found") + } + + report, err := s.fetchAnalytics(ctx, peer) + if err != nil { + return NodeDetails{}, fmt.Errorf("fetching analytics: %w", err) + } + + member, err := s.fetchMemberState(ctx, peer) + if err != nil { + return NodeDetails{}, fmt.Errorf("fetching member state: %w", err) + } + + return NodeDetails{ + Member: member, + Config: member.configBody, + Metrics: report.Metrics, + ClusterID: report.ClusterID, + ClusterSeededAt: report.CreatedAt.UnixMilli(), + OS: report.Os, + Arch: report.Arch, + Edition: report.Edition, + }, nil +} + +func (s *Service) getSelfPeer() (peer.Peer, bool) { + for _, peer := range s.node.Peers() { + if peer.Self { + return peer, true + } + } + return peer.Peer{}, false +} + +func (s *Service) fetchAnalytics(ctx context.Context, peer peer.Peer) (analytics.Report, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.buildProxyPath(peer, "/ui/api/v1/analytics"), nil) + if err != nil { + return analytics.Report{}, fmt.Errorf("creating request: %w", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return analytics.Report{}, fmt.Errorf("sending request: %w", err) + } + + if err := readResponseError(resp, "fetch build info"); err != nil { + return analytics.Report{}, err + } + defer resp.Body.Close() + + var report analytics.Report + if err := json.NewDecoder(resp.Body).Decode(&report); err != nil { + return analytics.Report{}, fmt.Errorf("decoding response: %w", err) + } + return report, nil +} + +// fetchConfig retrieves the configuration of a cluster member. +func (s *Service) fetchConfig(ctx context.Context, peer peer.Peer) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.buildProxyPath(peer, "/config"), nil) + if err != nil { + return "", fmt.Errorf("creating request: %w", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return "", fmt.Errorf("sending request: %w", err) + } + + if err := readResponseError(resp, "fetch config"); err != nil { + return "", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("reading response: %w", err) + } + return string(body), nil +} + +// fetchServices retrieves the service states of a cluster member. +func (s *Service) fetchServices(ctx context.Context, peer peer.Peer) ([]ServiceState, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.buildProxyPath(peer, "/services"), nil) + if err != nil { + return nil, fmt.Errorf("creating request: %w", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("sending request: %w", err) + } + + if err := readResponseError(resp, "fetch services"); err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("reading response: %w", err) + } + return parseServices(string(body)) +} + +// fetchBuild retrieves the build information of a cluster member. +func (s *Service) fetchBuild(ctx context.Context, peer peer.Peer) (BuildInfo, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.buildProxyPath(peer, "/loki/api/v1/status/buildinfo"), nil) + if err != nil { + return BuildInfo{}, fmt.Errorf("creating request: %w", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return BuildInfo{}, fmt.Errorf("sending request: %w", err) + } + + if err := readResponseError(resp, "fetch build info"); err != nil { + return BuildInfo{}, err + } + defer resp.Body.Close() + + var build BuildInfo + if err := json.NewDecoder(resp.Body).Decode(&build); err != nil { + return BuildInfo{}, fmt.Errorf("decoding response: %w", err) + } + return build, nil +} + +type ReadyResponse struct { + IsReady bool `json:"isReady"` + Message string `json:"message"` +} + +func (s *Service) checkNodeReadiness(ctx context.Context, nodeName string) (ReadyResponse, error) { + peer, err := s.findPeerByName(nodeName) + if err != nil { + return ReadyResponse{}, err + } + + req, err := http.NewRequestWithContext(ctx, "GET", s.buildProxyPath(peer, "/ready"), nil) + if err != nil { + return ReadyResponse{}, err + } + + resp, err := s.client.Do(req) + if err != nil { + return ReadyResponse{}, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return ReadyResponse{}, err + } + + return ReadyResponse{ + IsReady: resp.StatusCode == http.StatusOK && strings.TrimSpace(string(body)) == "ready", + Message: string(body), + }, nil +} + +// parseTargetFromConfig extracts the target value from a YAML configuration string. +// Returns "unknown" if the config cannot be parsed or the target is not found. +func parseTargetFromConfig(config string) string { + var cfg map[string]interface{} + if err := yaml.Unmarshal([]byte(config), &cfg); err != nil { + return "unknown" + } + target, _ := cfg["target"].(string) + return target +} + +// parseServices parses a string containing service states in the format: +// service => status +// Returns a slice of ServiceState structs. +func parseServices(body string) ([]ServiceState, error) { + var services []ServiceState + lines := strings.Split(body, "\n") + for _, line := range lines { + parts := strings.SplitN(line, " => ", 2) + if len(parts) != 2 { + continue + } + services = append(services, ServiceState{ + Service: parts[0], + Status: parts[1], + }) + } + return services, nil +} diff --git a/pkg/ui/config.go b/pkg/ui/config.go new file mode 100644 index 0000000000000..1703eae62ad3c --- /dev/null +++ b/pkg/ui/config.go @@ -0,0 +1,58 @@ +package ui + +import ( + "errors" + "flag" + "fmt" + "os" + "time" + + "github.com/grafana/dskit/flagext" + "github.com/grafana/dskit/netutil" + + util_log "github.com/grafana/loki/v3/pkg/util/log" +) + +type Config struct { + NodeName string `yaml:"node_name" doc:"default=<hostname>"` // Name to use for this node in the cluster. + AdvertiseAddr string `yaml:"advertise_addr"` + InfNames []string `yaml:"interface_names" doc:"default=[<private network interfaces>]"` + RejoinInterval time.Duration `yaml:"rejoin_interval"` // How frequently to rejoin the cluster to address split brain issues. + ClusterMaxJoinPeers int `yaml:"cluster_max_join_peers"` // Number of initial peers to join from the discovered set. + ClusterName string `yaml:"cluster_name"` // Name to prevent nodes without this identifier from joining the cluster. + EnableIPv6 bool `yaml:"enable_ipv6"` + Discovery struct { + JoinPeers []string `yaml:"join_peers"` + } `yaml:"discovery"` + + AdvertisePort int `yaml:"-"` +} + +func (cfg Config) WithAdvertisePort(port int) Config { + cfg.AdvertisePort = port + return cfg +} + +func (cfg *Config) RegisterFlags(f *flag.FlagSet) { + hostname, err := os.Hostname() + if err != nil { + panic(fmt.Errorf("failed to get hostname %s", err)) + } + cfg.InfNames = netutil.PrivateNetworkInterfacesWithFallback([]string{"eth0", "en0"}, util_log.Logger) + f.Var((*flagext.StringSlice)(&cfg.InfNames), "ui.interface", "Name of network interface to read address from.") + f.StringVar(&cfg.NodeName, "ui.node-name", hostname, "Name to use for this node in the cluster.") + f.StringVar(&cfg.AdvertiseAddr, "ui.advertise-addr", "", "IP address to advertise in the cluster.") + f.DurationVar(&cfg.RejoinInterval, "ui.rejoin-interval", 15*time.Second, "How frequently to rejoin the cluster to address split brain issues.") + f.IntVar(&cfg.ClusterMaxJoinPeers, "ui.cluster-max-join-peers", 3, "Number of initial peers to join from the discovered set.") + f.StringVar(&cfg.ClusterName, "ui.cluster-name", "", "Name to prevent nodes without this identifier from joining the cluster.") + f.BoolVar(&cfg.EnableIPv6, "ui.enable-ipv6", false, "Enable using a IPv6 instance address.") + f.Var((*flagext.StringSlice)(&cfg.Discovery.JoinPeers), "ui.discovery.join-peers", "List of peers to join the cluster. Supports multiple values separated by commas. Each value can be a hostname, an IP address, or a DNS name (A/AAAA and SRV records).") +} + +func (cfg Config) Validate() error { + if cfg.NodeName == "" { + return errors.New("node name is required") + } + + return nil +} diff --git a/pkg/ui/discovery.go b/pkg/ui/discovery.go new file mode 100644 index 0000000000000..68adb17e81f2b --- /dev/null +++ b/pkg/ui/discovery.go @@ -0,0 +1,146 @@ +package ui + +import ( + "errors" + "fmt" + "math/rand/v2" + "net" + "strconv" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" +) + +func (s *Service) getBootstrapPeers() ([]string, error) { + if len(s.cfg.Discovery.JoinPeers) == 0 { + return nil, nil + } + // Use these resolvers in order to resolve the provided addresses into a form that can be used by clustering. + resolvers := []addressResolver{ + ipResolver(), + dnsAResolver(nil), + dnsSRVResolver(nil), + } + + // Get the addresses. + addresses, err := buildJoinAddresses(s.cfg, resolvers, s.logger) + if err != nil { + return nil, fmt.Errorf("static peer discovery: %w", err) + } + + // Return unique addresses. + peers := uniq(addresses) + // Here we return the entire list because we can't take a subset. + if s.cfg.ClusterMaxJoinPeers == 0 || len(peers) < s.cfg.ClusterMaxJoinPeers { + return peers, nil + } + + // We shuffle the list and return only a subset of the peers. + rand.Shuffle(len(peers), func(i, j int) { + peers[i], peers[j] = peers[j], peers[i] + }) + return peers[:s.cfg.ClusterMaxJoinPeers], nil +} + +func uniq(addresses []string) []string { + seen := make(map[string]bool) + var result []string + for _, addr := range addresses { + if !seen[addr] { + seen[addr] = true + result = append(result, addr) + } + } + return result +} + +func buildJoinAddresses(opts Config, resolvers []addressResolver, logger log.Logger) ([]string, error) { + var ( + result []string + deferredErr error + ) + + for _, addr := range opts.Discovery.JoinPeers { + // See if we have a port override, if not use the default port. + host, port, err := net.SplitHostPort(addr) + if err != nil { + host = addr + port = strconv.Itoa(opts.AdvertisePort) + } + + atLeastOneSuccess := false + for _, resolver := range resolvers { + resolved, err := resolver(host) + deferredErr = errors.Join(deferredErr, err) + for _, foundAddr := range resolved { + result = append(result, net.JoinHostPort(foundAddr, port)) + } + // we stop once we find a resolver that succeeded for given address + if len(resolved) > 0 { + atLeastOneSuccess = true + break + } + } + + if !atLeastOneSuccess { + // It is still useful to know if user provided an address that we could not resolve, even + // if another addresses resolve successfully, and we don't return an error. To keep things simple, we're + // not including more detail as it's available through debug level. + level.Warn(logger).Log("msg", "failed to resolve provided join address", "addr", addr) + } + } + + if len(result) == 0 { + return nil, fmt.Errorf("failed to find any valid join addresses: %w", deferredErr) + } + return result, nil +} + +type addressResolver func(addr string) ([]string, error) + +func ipResolver() addressResolver { + return func(addr string) ([]string, error) { + // Check if it's IP and use it if so. + ip := net.ParseIP(addr) + if ip == nil { + return nil, fmt.Errorf("could not parse as an IP or IP:port address: %q", addr) + } + return []string{ip.String()}, nil + } +} + +func dnsAResolver(ipLookup func(string) ([]net.IP, error)) addressResolver { + // Default to net.LookupIP if not provided. By default, this will look up A/AAAA records. + if ipLookup == nil { + ipLookup = net.LookupIP + } + return func(addr string) ([]string, error) { + ips, err := ipLookup(addr) + result := make([]string, 0, len(ips)) + for _, ip := range ips { + result = append(result, ip.String()) + } + if err != nil { + err = fmt.Errorf("failed to resolve %q records: %w", "A/AAAA", err) + } + return result, err + } +} + +func dnsSRVResolver(srvLookup func(service, proto, name string) (string, []*net.SRV, error)) addressResolver { + // Default to net.LookupSRV if not provided. + if srvLookup == nil { + srvLookup = net.LookupSRV + } + return func(addr string) ([]string, error) { + _, addresses, err := srvLookup("", "", addr) + result := make([]string, 0, len(addresses)) + for _, a := range addresses { + result = append(result, a.Target) + } + if err != nil { + err = fmt.Errorf("failed to resolve %q records: %w", "SRV", err) + } + return result, err + } +} diff --git a/pkg/ui/frontend/.depcheckrc.json b/pkg/ui/frontend/.depcheckrc.json new file mode 100644 index 0000000000000..3d0ff1a1bae4d --- /dev/null +++ b/pkg/ui/frontend/.depcheckrc.json @@ -0,0 +1,14 @@ +{ + "ignores": [ + "@types/node", + "autoprefixer", + "postcss", + "tailwindcss", + "tailwindcss-animate", + "@typescript-eslint/*", + "@vitejs/*", + "eslint*", + "depcheck" + ], + "ignore-patterns": ["dist", "build", ".next", "coverage"] +} diff --git a/pkg/ui/frontend/.eslintrc.json b/pkg/ui/frontend/.eslintrc.json new file mode 100644 index 0000000000000..725d88183f2e9 --- /dev/null +++ b/pkg/ui/frontend/.eslintrc.json @@ -0,0 +1,34 @@ +{ + "root": true, + "env": { + "browser": true, + "es2020": true, + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended" + ], + "ignorePatterns": [ + "dist", + ".eslintrc.json" + ], + "parser": "@typescript-eslint/parser", + "plugins": [ + "react-refresh" + ], + "rules": { + "react-refresh/only-export-components": "warn" + }, + "overrides": [ + { + "files": [ + "src/components/ui/**/*" + ], + "rules": { + "react-refresh/only-export-components": "off" + } + } + ] +} diff --git a/pkg/ui/frontend/Makefile b/pkg/ui/frontend/Makefile new file mode 100644 index 0000000000000..8e817471e5db9 --- /dev/null +++ b/pkg/ui/frontend/Makefile @@ -0,0 +1,18 @@ +.PHONY: build +build: + npm install + npm run build + +.PHONY: dev +dev: + npm run dev + +.PHONY: clean +clean: + rm -rf node_modules + rm -rf dist + +.PHONY: check-deps +check-deps: + npx depcheck + npm audit diff --git a/pkg/ui/frontend/README.md b/pkg/ui/frontend/README.md new file mode 100644 index 0000000000000..b9980ab227141 --- /dev/null +++ b/pkg/ui/frontend/README.md @@ -0,0 +1,120 @@ +# Loki UI + +The Loki UI is an operational dashboard for managing and operating Grafana Loki clusters. It provides a comprehensive set of tools for cluster administration, operational tasks, and troubleshooting. This includes node management, configuration control, performance monitoring, and diagnostic tools for investigating cluster health and log ingestion issues. + +## Tech Stack + +- **Framework**: React 18 with TypeScript +- **Routing**: React Router v6 +- **Styling**: + - Tailwind CSS for utility-first styling + - Shadcn UI (built on Radix UI) for accessible components + - Tailwind Merge for dynamic class merging + - Tailwind Animate for animations +- **State Management**: React Context + Custom Hooks +- **Data Visualization**: Recharts +- **Development**: + - Vite for build tooling and development server + - TypeScript for type safety + - ESLint for code quality + - PostCSS for CSS processing + +## Project Structure + +``` +src/ +├── components/ # React components +│ ├── ui/ # Shadcn UI components +│ │ ├── errors/ # Error handling components +│ │ └── breadcrumbs/ # Navigation breadcrumbs +│ ├── shared/ # Shared components used across pages +│ │ └── {pagename}/ # Page-specific components +│ ├── common/ # Truly reusable components +│ └── features/ # Complex feature modules +│ └── theme/ # Theme-related components and logic +├── pages/ # Page components and routes +├── layout/ # Layout components +├── hooks/ # Custom React hooks +├── contexts/ # React context providers +├── lib/ # Utility functions and constants +└── types/ # TypeScript type definitions +``` + +## Component Organization Guidelines + +1. **Page-Specific Components** + - Place in `components/{pagename}/` + - Only used by a single page + - Colocated with the page they belong to + +2. **Shared Components** + - Place in `components/shared/` + - Used across multiple pages + - Well-documented and maintainable + +3. **Common Components** + - Place in `components/common/` + - Highly reusable, pure components + - No business logic + +4. **UI Components** + - Place in `components/ui/` + - Shadcn components + - Do not modify directly + +## Development Guidelines + +1. **TypeScript** + - Use TypeScript for all new code + - Prefer interfaces over types + - Avoid enums, use const maps instead + +2. **Component Best Practices** + - Use functional components + - Keep components small and focused + - Use composition over inheritance + - Colocate related code + +3. **State Management** + - Use React Context for global state + - Custom hooks for reusable logic + - Local state for component-specific data + +4. **Styling** + - Use Tailwind CSS for styling + - Avoid inline styles + - Use CSS variables for theming + - Follow responsive design principles + +## Getting Started + +1. Install dependencies: + + ```bash + npm install + ``` + +2. Start development server: + + ```bash + npm run dev + ``` + +3. Build for production: + + ```bash + npm run build + ``` + +4. Lint code: + + ```bash + npm run lint + ``` + +## Contributing + +1. Follow the folder structure +2. Write clean, maintainable code +3. Add proper TypeScript types +4. Document complex logic diff --git a/pkg/ui/frontend/components.json b/pkg/ui/frontend/components.json new file mode 100644 index 0000000000000..1d282e6408443 --- /dev/null +++ b/pkg/ui/frontend/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.js", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} \ No newline at end of file diff --git a/pkg/ui/frontend/dist/assets/data-viz-BuFFX-vG.js b/pkg/ui/frontend/dist/assets/data-viz-BuFFX-vG.js new file mode 100644 index 0000000000000..7b7076251de55 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/data-viz-BuFFX-vG.js @@ -0,0 +1,72 @@ +import{c as J}from"./ui-utils-BNSC_Jv-.js";import{e as yi,g as ie,r as L,b as P}from"./react-core-D_V7s-9r.js";var mg=Array.isArray,Be=mg,bg=typeof yi=="object"&&yi&&yi.Object===Object&&yi,Ip=bg,xg=Ip,wg=typeof self=="object"&&self&&self.Object===Object&&self,Og=xg||wg||Function("return this")(),st=Og,Ag=st,Pg=Ag.Symbol,ai=Pg,Rs=ai,kp=Object.prototype,Sg=kp.hasOwnProperty,_g=kp.toString,un=Rs?Rs.toStringTag:void 0;function $g(e){var t=Sg.call(e,un),r=e[un];try{e[un]=void 0;var n=!0}catch{}var i=_g.call(e);return n&&(t?e[un]=r:delete e[un]),i}var Tg=$g,Eg=Object.prototype,jg=Eg.toString;function Mg(e){return jg.call(e)}var Cg=Mg,Ls=ai,Ig=Tg,kg=Cg,Ng="[object Null]",Dg="[object Undefined]",Bs=Ls?Ls.toStringTag:void 0;function Rg(e){return e==null?e===void 0?Dg:Ng:Bs&&Bs in Object(e)?Ig(e):kg(e)}var Pt=Rg;function Lg(e){return e!=null&&typeof e=="object"}var St=Lg,Bg=Pt,Fg=St,Wg="[object Symbol]";function zg(e){return typeof e=="symbol"||Fg(e)&&Bg(e)==Wg}var Kr=zg,Ug=Be,qg=Kr,Hg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Gg=/^\w*$/;function Kg(e,t){if(Ug(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||qg(e)?!0:Gg.test(e)||!Hg.test(e)||t!=null&&e in Object(t)}var Sc=Kg;function Xg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var kt=Xg;const Xr=ie(kt);var Vg=Pt,Yg=kt,Zg="[object AsyncFunction]",Jg="[object Function]",Qg="[object GeneratorFunction]",em="[object Proxy]";function tm(e){if(!Yg(e))return!1;var t=Vg(e);return t==Jg||t==Qg||t==Zg||t==em}var _c=tm;const V=ie(_c);var rm=st,nm=rm["__core-js_shared__"],im=nm,Po=im,Fs=function(){var e=/[^.]+$/.exec(Po&&Po.keys&&Po.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function am(e){return!!Fs&&Fs in e}var om=am,um=Function.prototype,cm=um.toString;function sm(e){if(e!=null){try{return cm.call(e)}catch{}try{return e+""}catch{}}return""}var Np=sm,lm=_c,fm=om,dm=kt,pm=Np,hm=/[\\^$.*+?()[\]{}|]/g,ym=/^\[object .+?Constructor\]$/,vm=Function.prototype,gm=Object.prototype,mm=vm.toString,bm=gm.hasOwnProperty,xm=RegExp("^"+mm.call(bm).replace(hm,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wm(e){if(!dm(e)||fm(e))return!1;var t=lm(e)?xm:ym;return t.test(pm(e))}var Om=wm;function Am(e,t){return e==null?void 0:e[t]}var Pm=Am,Sm=Om,_m=Pm;function $m(e,t){var r=_m(e,t);return Sm(r)?r:void 0}var or=$m,Tm=or,Em=Tm(Object,"create"),Ea=Em,Ws=Ea;function jm(){this.__data__=Ws?Ws(null):{},this.size=0}var Mm=jm;function Cm(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Im=Cm,km=Ea,Nm="__lodash_hash_undefined__",Dm=Object.prototype,Rm=Dm.hasOwnProperty;function Lm(e){var t=this.__data__;if(km){var r=t[e];return r===Nm?void 0:r}return Rm.call(t,e)?t[e]:void 0}var Bm=Lm,Fm=Ea,Wm=Object.prototype,zm=Wm.hasOwnProperty;function Um(e){var t=this.__data__;return Fm?t[e]!==void 0:zm.call(t,e)}var qm=Um,Hm=Ea,Gm="__lodash_hash_undefined__";function Km(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Hm&&t===void 0?Gm:t,this}var Xm=Km,Vm=Mm,Ym=Im,Zm=Bm,Jm=qm,Qm=Xm;function Vr(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Vr.prototype.clear=Vm;Vr.prototype.delete=Ym;Vr.prototype.get=Zm;Vr.prototype.has=Jm;Vr.prototype.set=Qm;var eb=Vr;function tb(){this.__data__=[],this.size=0}var rb=tb;function nb(e,t){return e===t||e!==e&&t!==t}var $c=nb,ib=$c;function ab(e,t){for(var r=e.length;r--;)if(ib(e[r][0],t))return r;return-1}var ja=ab,ob=ja,ub=Array.prototype,cb=ub.splice;function sb(e){var t=this.__data__,r=ob(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():cb.call(t,r,1),--this.size,!0}var lb=sb,fb=ja;function db(e){var t=this.__data__,r=fb(t,e);return r<0?void 0:t[r][1]}var pb=db,hb=ja;function yb(e){return hb(this.__data__,e)>-1}var vb=yb,gb=ja;function mb(e,t){var r=this.__data__,n=gb(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var bb=mb,xb=rb,wb=lb,Ob=pb,Ab=vb,Pb=bb;function Yr(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Yr.prototype.clear=xb;Yr.prototype.delete=wb;Yr.prototype.get=Ob;Yr.prototype.has=Ab;Yr.prototype.set=Pb;var Ma=Yr,Sb=or,_b=st,$b=Sb(_b,"Map"),Tc=$b,zs=eb,Tb=Ma,Eb=Tc;function jb(){this.size=0,this.__data__={hash:new zs,map:new(Eb||Tb),string:new zs}}var Mb=jb;function Cb(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Ib=Cb,kb=Ib;function Nb(e,t){var r=e.__data__;return kb(t)?r[typeof t=="string"?"string":"hash"]:r.map}var Ca=Nb,Db=Ca;function Rb(e){var t=Db(this,e).delete(e);return this.size-=t?1:0,t}var Lb=Rb,Bb=Ca;function Fb(e){return Bb(this,e).get(e)}var Wb=Fb,zb=Ca;function Ub(e){return zb(this,e).has(e)}var qb=Ub,Hb=Ca;function Gb(e,t){var r=Hb(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Kb=Gb,Xb=Mb,Vb=Lb,Yb=Wb,Zb=qb,Jb=Kb;function Zr(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Zr.prototype.clear=Xb;Zr.prototype.delete=Vb;Zr.prototype.get=Yb;Zr.prototype.has=Zb;Zr.prototype.set=Jb;var Ec=Zr,Dp=Ec,Qb="Expected a function";function jc(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Qb);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(jc.Cache||Dp),r}jc.Cache=Dp;var Rp=jc;const e0=ie(Rp);var t0=Rp,r0=500;function n0(e){var t=t0(e,function(n){return r.size===r0&&r.clear(),n}),r=t.cache;return t}var i0=n0,a0=i0,o0=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,u0=/\\(\\)?/g,c0=a0(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(o0,function(r,n,i,a){t.push(i?a.replace(u0,"$1"):n||r)}),t}),s0=c0;function l0(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}var Mc=l0,Us=ai,f0=Mc,d0=Be,p0=Kr,qs=Us?Us.prototype:void 0,Hs=qs?qs.toString:void 0;function Lp(e){if(typeof e=="string")return e;if(d0(e))return f0(e,Lp)+"";if(p0(e))return Hs?Hs.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var h0=Lp,y0=h0;function v0(e){return e==null?"":y0(e)}var Bp=v0,g0=Be,m0=Sc,b0=s0,x0=Bp;function w0(e,t){return g0(e)?e:m0(e,t)?[e]:b0(x0(e))}var Fp=w0,O0=Kr;function A0(e){if(typeof e=="string"||O0(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var Ia=A0,P0=Fp,S0=Ia;function _0(e,t){t=P0(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[S0(t[r++])];return r&&r==n?e:void 0}var Cc=_0,$0=Cc;function T0(e,t,r){var n=e==null?void 0:$0(e,t);return n===void 0?r:n}var Wp=T0;const qe=ie(Wp);function E0(e){return e==null}var j0=E0;const Q=ie(j0);var M0=Pt,C0=Be,I0=St,k0="[object String]";function N0(e){return typeof e=="string"||!C0(e)&&I0(e)&&M0(e)==k0}var D0=N0;const oi=ie(D0);var zp={exports:{}},ae={};/** + * @license React + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ic=Symbol.for("react.element"),kc=Symbol.for("react.portal"),ka=Symbol.for("react.fragment"),Na=Symbol.for("react.strict_mode"),Da=Symbol.for("react.profiler"),Ra=Symbol.for("react.provider"),La=Symbol.for("react.context"),R0=Symbol.for("react.server_context"),Ba=Symbol.for("react.forward_ref"),Fa=Symbol.for("react.suspense"),Wa=Symbol.for("react.suspense_list"),za=Symbol.for("react.memo"),Ua=Symbol.for("react.lazy"),L0=Symbol.for("react.offscreen"),Up;Up=Symbol.for("react.module.reference");function Ze(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Ic:switch(e=e.type,e){case ka:case Da:case Na:case Fa:case Wa:return e;default:switch(e=e&&e.$$typeof,e){case R0:case La:case Ba:case Ua:case za:case Ra:return e;default:return t}}case kc:return t}}}ae.ContextConsumer=La;ae.ContextProvider=Ra;ae.Element=Ic;ae.ForwardRef=Ba;ae.Fragment=ka;ae.Lazy=Ua;ae.Memo=za;ae.Portal=kc;ae.Profiler=Da;ae.StrictMode=Na;ae.Suspense=Fa;ae.SuspenseList=Wa;ae.isAsyncMode=function(){return!1};ae.isConcurrentMode=function(){return!1};ae.isContextConsumer=function(e){return Ze(e)===La};ae.isContextProvider=function(e){return Ze(e)===Ra};ae.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Ic};ae.isForwardRef=function(e){return Ze(e)===Ba};ae.isFragment=function(e){return Ze(e)===ka};ae.isLazy=function(e){return Ze(e)===Ua};ae.isMemo=function(e){return Ze(e)===za};ae.isPortal=function(e){return Ze(e)===kc};ae.isProfiler=function(e){return Ze(e)===Da};ae.isStrictMode=function(e){return Ze(e)===Na};ae.isSuspense=function(e){return Ze(e)===Fa};ae.isSuspenseList=function(e){return Ze(e)===Wa};ae.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===ka||e===Da||e===Na||e===Fa||e===Wa||e===L0||typeof e=="object"&&e!==null&&(e.$$typeof===Ua||e.$$typeof===za||e.$$typeof===Ra||e.$$typeof===La||e.$$typeof===Ba||e.$$typeof===Up||e.getModuleId!==void 0)};ae.typeOf=Ze;zp.exports=ae;var B0=zp.exports,F0=Pt,W0=St,z0="[object Number]";function U0(e){return typeof e=="number"||W0(e)&&F0(e)==z0}var qp=U0;const q0=ie(qp);var H0=qp;function G0(e){return H0(e)&&e!=+e}var K0=G0;const ui=ie(K0);var Ie=function(t){return t===0?0:t>0?1:-1},Vt=function(t){return oi(t)&&t.indexOf("%")===t.length-1},R=function(t){return q0(t)&&!ui(t)},Ae=function(t){return R(t)||oi(t)},X0=0,ci=function(t){var r=++X0;return"".concat(t||"").concat(r)},ke=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!R(t)&&!oi(t))return n;var a;if(Vt(t)){var o=t.indexOf("%");a=r*parseFloat(t.slice(0,o))/100}else a=+t;return ui(a)&&(a=n),i&&a>r&&(a=r),a},jt=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},V0=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},i=0;i<r;i++)if(!n[t[i]])n[t[i]]=!0;else return!0;return!1},Tt=function(t,r){return R(t)&&R(r)?function(n){return t+n*(r-t)}:function(){return r}};function Jo(e,t,r){return!e||!e.length?null:e.find(function(n){return n&&(typeof t=="function"?t(n):qe(n,t))===r})}function br(e,t){for(var r in e)if({}.hasOwnProperty.call(e,r)&&(!{}.hasOwnProperty.call(t,r)||e[r]!==t[r]))return!1;for(var n in t)if({}.hasOwnProperty.call(t,n)&&!{}.hasOwnProperty.call(e,n))return!1;return!0}function Qo(e){"@babel/helpers - typeof";return Qo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qo(e)}var Y0=["viewBox","children"],Z0=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],Gs=["points","pathLength"],So={svg:Y0,polygon:Gs,polyline:Gs},Nc=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"],Mi=function(t,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(L.isValidElement(t)&&(n=t.props),!Xr(n))return null;var i={};return Object.keys(n).forEach(function(a){Nc.includes(a)&&(i[a]=r||function(o){return n[a](n,o)})}),i},J0=function(t,r,n){return function(i){return t(r,n,i),null}},tr=function(t,r,n){if(!Xr(t)||Qo(t)!=="object")return null;var i=null;return Object.keys(t).forEach(function(a){var o=t[a];Nc.includes(a)&&typeof o=="function"&&(i||(i={}),i[a]=J0(o,r,n))}),i},Q0=["children"],ex=["children"];function Ks(e,t){if(e==null)return{};var r=tx(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function tx(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var Xs={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},gt=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Vs=null,_o=null,Dc=function e(t){if(t===Vs&&Array.isArray(_o))return _o;var r=[];return L.Children.forEach(t,function(n){Q(n)||(B0.isFragment(n)?r=r.concat(e(n.props.children)):r.push(n))}),_o=r,Vs=t,r};function Ve(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(i){return gt(i)}):n=[gt(t)],Dc(e).forEach(function(i){var a=qe(i,"type.displayName")||qe(i,"type.name");n.indexOf(a)!==-1&&r.push(i)}),r}function ze(e,t){var r=Ve(e,t);return r[0]}var Ys=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,i=r.height;return!(!R(n)||n<=0||!R(i)||i<=0)},rx=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],nx=function(t){return t&&t.type&&oi(t.type)&&rx.indexOf(t.type)>=0},ix=function(t,r,n,i){var a,o=(a=So==null?void 0:So[i])!==null&&a!==void 0?a:[];return!V(t)&&(i&&o.includes(r)||Z0.includes(r))||n&&Nc.includes(r)},X=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var i=t;if(L.isValidElement(t)&&(i=t.props),!Xr(i))return null;var a={};return Object.keys(i).forEach(function(o){var u;ix((u=i)===null||u===void 0?void 0:u[o],o,r,n)&&(a[o]=i[o])}),a},eu=function e(t,r){if(t===r)return!0;var n=L.Children.count(t);if(n!==L.Children.count(r))return!1;if(n===0)return!0;if(n===1)return Zs(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var i=0;i<n;i++){var a=t[i],o=r[i];if(Array.isArray(a)||Array.isArray(o)){if(!e(a,o))return!1}else if(!Zs(a,o))return!1}return!0},Zs=function(t,r){if(Q(t)&&Q(r))return!0;if(!Q(t)&&!Q(r)){var n=t.props||{},i=n.children,a=Ks(n,Q0),o=r.props||{},u=o.children,c=Ks(o,ex);return i&&u?br(a,c)&&eu(i,u):!i&&!u?br(a,c):!1}return!1},Js=function(t,r){var n=[],i={};return Dc(t).forEach(function(a,o){if(nx(a))n.push(a);else if(a){var u=gt(a.type),c=r[u]||{},s=c.handler,f=c.once;if(s&&(!f||!i[u])){var l=s(a,u,o);n.push(l),i[u]=!0}}}),n},ax=function(t){var r=t&&t.type;return r&&Xs[r]?Xs[r]:null},ox=function(t,r){return Dc(r).indexOf(t)},ux=["children","width","height","viewBox","className","style","title","desc"];function tu(){return tu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},tu.apply(this,arguments)}function cx(e,t){if(e==null)return{};var r=sx(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function sx(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function ru(e){var t=e.children,r=e.width,n=e.height,i=e.viewBox,a=e.className,o=e.style,u=e.title,c=e.desc,s=cx(e,ux),f=i||{width:r,height:n,x:0,y:0},l=J("recharts-surface",a);return P.createElement("svg",tu({},X(s,!0,"svg"),{className:l,width:r,height:n,style:o,viewBox:"".concat(f.x," ").concat(f.y," ").concat(f.width," ").concat(f.height)}),P.createElement("title",null,u),P.createElement("desc",null,c),t)}var lx=["children","className"];function nu(){return nu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},nu.apply(this,arguments)}function fx(e,t){if(e==null)return{};var r=dx(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function dx(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var ne=P.forwardRef(function(e,t){var r=e.children,n=e.className,i=fx(e,lx),a=J("recharts-layer",n);return P.createElement("g",nu({className:a},X(i,!0),{ref:t}),r)}),nt=function(t,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),a=2;a<n;a++)i[a-2]=arguments[a]};function px(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),r=r>i?i:r,r<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(i);++n<i;)a[n]=e[n+t];return a}var hx=px,yx=hx;function vx(e,t,r){var n=e.length;return r=r===void 0?n:r,!t&&r>=n?e:yx(e,t,r)}var gx=vx,mx="\\ud800-\\udfff",bx="\\u0300-\\u036f",xx="\\ufe20-\\ufe2f",wx="\\u20d0-\\u20ff",Ox=bx+xx+wx,Ax="\\ufe0e\\ufe0f",Px="\\u200d",Sx=RegExp("["+Px+mx+Ox+Ax+"]");function _x(e){return Sx.test(e)}var Hp=_x;function $x(e){return e.split("")}var Tx=$x,Gp="\\ud800-\\udfff",Ex="\\u0300-\\u036f",jx="\\ufe20-\\ufe2f",Mx="\\u20d0-\\u20ff",Cx=Ex+jx+Mx,Ix="\\ufe0e\\ufe0f",kx="["+Gp+"]",iu="["+Cx+"]",au="\\ud83c[\\udffb-\\udfff]",Nx="(?:"+iu+"|"+au+")",Kp="[^"+Gp+"]",Xp="(?:\\ud83c[\\udde6-\\uddff]){2}",Vp="[\\ud800-\\udbff][\\udc00-\\udfff]",Dx="\\u200d",Yp=Nx+"?",Zp="["+Ix+"]?",Rx="(?:"+Dx+"(?:"+[Kp,Xp,Vp].join("|")+")"+Zp+Yp+")*",Lx=Zp+Yp+Rx,Bx="(?:"+[Kp+iu+"?",iu,Xp,Vp,kx].join("|")+")",Fx=RegExp(au+"(?="+au+")|"+Bx+Lx,"g");function Wx(e){return e.match(Fx)||[]}var zx=Wx,Ux=Tx,qx=Hp,Hx=zx;function Gx(e){return qx(e)?Hx(e):Ux(e)}var Kx=Gx,Xx=gx,Vx=Hp,Yx=Kx,Zx=Bp;function Jx(e){return function(t){t=Zx(t);var r=Vx(t)?Yx(t):void 0,n=r?r[0]:t.charAt(0),i=r?Xx(r,1).join(""):t.slice(1);return n[e]()+i}}var Qx=Jx,ew=Qx,tw=ew("toUpperCase"),rw=tw;const qa=ie(rw);function se(e){return function(){return e}}const Jp=Math.cos,Ci=Math.sin,it=Math.sqrt,Ii=Math.PI,Ha=2*Ii,ou=Math.PI,uu=2*ou,Ht=1e-6,nw=uu-Ht;function Qp(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=arguments[t]+e[t]}function iw(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return Qp;const r=10**t;return function(n){this._+=n[0];for(let i=1,a=n.length;i<a;++i)this._+=Math.round(arguments[i]*r)/r+n[i]}}class aw{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?Qp:iw(t)}moveTo(t,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,r){this._append`L${this._x1=+t},${this._y1=+r}`}quadraticCurveTo(t,r,n,i){this._append`Q${+t},${+r},${this._x1=+n},${this._y1=+i}`}bezierCurveTo(t,r,n,i,a,o){this._append`C${+t},${+r},${+n},${+i},${this._x1=+a},${this._y1=+o}`}arcTo(t,r,n,i,a){if(t=+t,r=+r,n=+n,i=+i,a=+a,a<0)throw new Error(`negative radius: ${a}`);let o=this._x1,u=this._y1,c=n-t,s=i-r,f=o-t,l=u-r,d=f*f+l*l;if(this._x1===null)this._append`M${this._x1=t},${this._y1=r}`;else if(d>Ht)if(!(Math.abs(l*c-s*f)>Ht)||!a)this._append`L${this._x1=t},${this._y1=r}`;else{let p=n-o,y=i-u,h=c*c+s*s,v=p*p+y*y,b=Math.sqrt(h),w=Math.sqrt(d),x=a*Math.tan((ou-Math.acos((h+d-v)/(2*b*w)))/2),A=x/w,g=x/b;Math.abs(A-1)>Ht&&this._append`L${t+A*f},${r+A*l}`,this._append`A${a},${a},0,0,${+(l*p>f*y)},${this._x1=t+g*c},${this._y1=r+g*s}`}}arc(t,r,n,i,a,o){if(t=+t,r=+r,n=+n,o=!!o,n<0)throw new Error(`negative radius: ${n}`);let u=n*Math.cos(i),c=n*Math.sin(i),s=t+u,f=r+c,l=1^o,d=o?i-a:a-i;this._x1===null?this._append`M${s},${f}`:(Math.abs(this._x1-s)>Ht||Math.abs(this._y1-f)>Ht)&&this._append`L${s},${f}`,n&&(d<0&&(d=d%uu+uu),d>nw?this._append`A${n},${n},0,1,${l},${t-u},${r-c}A${n},${n},0,1,${l},${this._x1=s},${this._y1=f}`:d>Ht&&this._append`A${n},${n},0,${+(d>=ou)},${l},${this._x1=t+n*Math.cos(a)},${this._y1=r+n*Math.sin(a)}`)}rect(t,r,n,i){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function Rc(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new aw(t)}function Lc(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function eh(e){this._context=e}eh.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function Ga(e){return new eh(e)}function th(e){return e[0]}function rh(e){return e[1]}function nh(e,t){var r=se(!0),n=null,i=Ga,a=null,o=Rc(u);e=typeof e=="function"?e:e===void 0?th:se(e),t=typeof t=="function"?t:t===void 0?rh:se(t);function u(c){var s,f=(c=Lc(c)).length,l,d=!1,p;for(n==null&&(a=i(p=o())),s=0;s<=f;++s)!(s<f&&r(l=c[s],s,c))===d&&((d=!d)?a.lineStart():a.lineEnd()),d&&a.point(+e(l,s,c),+t(l,s,c));if(p)return a=null,p+""||null}return u.x=function(c){return arguments.length?(e=typeof c=="function"?c:se(+c),u):e},u.y=function(c){return arguments.length?(t=typeof c=="function"?c:se(+c),u):t},u.defined=function(c){return arguments.length?(r=typeof c=="function"?c:se(!!c),u):r},u.curve=function(c){return arguments.length?(i=c,n!=null&&(a=i(n)),u):i},u.context=function(c){return arguments.length?(c==null?n=a=null:a=i(n=c),u):n},u}function vi(e,t,r){var n=null,i=se(!0),a=null,o=Ga,u=null,c=Rc(s);e=typeof e=="function"?e:e===void 0?th:se(+e),t=typeof t=="function"?t:se(t===void 0?0:+t),r=typeof r=="function"?r:r===void 0?rh:se(+r);function s(l){var d,p,y,h=(l=Lc(l)).length,v,b=!1,w,x=new Array(h),A=new Array(h);for(a==null&&(u=o(w=c())),d=0;d<=h;++d){if(!(d<h&&i(v=l[d],d,l))===b)if(b=!b)p=d,u.areaStart(),u.lineStart();else{for(u.lineEnd(),u.lineStart(),y=d-1;y>=p;--y)u.point(x[y],A[y]);u.lineEnd(),u.areaEnd()}b&&(x[d]=+e(v,d,l),A[d]=+t(v,d,l),u.point(n?+n(v,d,l):x[d],r?+r(v,d,l):A[d]))}if(w)return u=null,w+""||null}function f(){return nh().defined(i).curve(o).context(a)}return s.x=function(l){return arguments.length?(e=typeof l=="function"?l:se(+l),n=null,s):e},s.x0=function(l){return arguments.length?(e=typeof l=="function"?l:se(+l),s):e},s.x1=function(l){return arguments.length?(n=l==null?null:typeof l=="function"?l:se(+l),s):n},s.y=function(l){return arguments.length?(t=typeof l=="function"?l:se(+l),r=null,s):t},s.y0=function(l){return arguments.length?(t=typeof l=="function"?l:se(+l),s):t},s.y1=function(l){return arguments.length?(r=l==null?null:typeof l=="function"?l:se(+l),s):r},s.lineX0=s.lineY0=function(){return f().x(e).y(t)},s.lineY1=function(){return f().x(e).y(r)},s.lineX1=function(){return f().x(n).y(t)},s.defined=function(l){return arguments.length?(i=typeof l=="function"?l:se(!!l),s):i},s.curve=function(l){return arguments.length?(o=l,a!=null&&(u=o(a)),s):o},s.context=function(l){return arguments.length?(l==null?a=u=null:u=o(a=l),s):a},s}class ih{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function ow(e){return new ih(e,!0)}function uw(e){return new ih(e,!1)}const Bc={draw(e,t){const r=it(t/Ii);e.moveTo(r,0),e.arc(0,0,r,0,Ha)}},cw={draw(e,t){const r=it(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},ah=it(1/3),sw=ah*2,lw={draw(e,t){const r=it(t/sw),n=r*ah;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},fw={draw(e,t){const r=it(t),n=-r/2;e.rect(n,n,r,r)}},dw=.8908130915292852,oh=Ci(Ii/10)/Ci(7*Ii/10),pw=Ci(Ha/10)*oh,hw=-Jp(Ha/10)*oh,yw={draw(e,t){const r=it(t*dw),n=pw*r,i=hw*r;e.moveTo(0,-r),e.lineTo(n,i);for(let a=1;a<5;++a){const o=Ha*a/5,u=Jp(o),c=Ci(o);e.lineTo(c*r,-u*r),e.lineTo(u*n-c*i,c*n+u*i)}e.closePath()}},$o=it(3),vw={draw(e,t){const r=-it(t/($o*3));e.moveTo(0,r*2),e.lineTo(-$o*r,-r),e.lineTo($o*r,-r),e.closePath()}},He=-.5,Ge=it(3)/2,cu=1/it(12),gw=(cu/2+1)*3,mw={draw(e,t){const r=it(t/gw),n=r/2,i=r*cu,a=n,o=r*cu+r,u=-a,c=o;e.moveTo(n,i),e.lineTo(a,o),e.lineTo(u,c),e.lineTo(He*n-Ge*i,Ge*n+He*i),e.lineTo(He*a-Ge*o,Ge*a+He*o),e.lineTo(He*u-Ge*c,Ge*u+He*c),e.lineTo(He*n+Ge*i,He*i-Ge*n),e.lineTo(He*a+Ge*o,He*o-Ge*a),e.lineTo(He*u+Ge*c,He*c-Ge*u),e.closePath()}};function bw(e,t){let r=null,n=Rc(i);e=typeof e=="function"?e:se(e||Bc),t=typeof t=="function"?t:se(t===void 0?64:+t);function i(){let a;if(r||(r=a=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),a)return r=null,a+""||null}return i.type=function(a){return arguments.length?(e=typeof a=="function"?a:se(a),i):e},i.size=function(a){return arguments.length?(t=typeof a=="function"?a:se(+a),i):t},i.context=function(a){return arguments.length?(r=a??null,i):r},i}function ki(){}function Ni(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function uh(e){this._context=e}uh.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Ni(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Ni(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function xw(e){return new uh(e)}function ch(e){this._context=e}ch.prototype={areaStart:ki,areaEnd:ki,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:Ni(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ww(e){return new ch(e)}function sh(e){this._context=e}sh.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:Ni(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function Ow(e){return new sh(e)}function lh(e){this._context=e}lh.prototype={areaStart:ki,areaEnd:ki,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function Aw(e){return new lh(e)}function Qs(e){return e<0?-1:1}function el(e,t,r){var n=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(n||i<0&&-0),o=(r-e._y1)/(i||n<0&&-0),u=(a*i+o*n)/(n+i);return(Qs(a)+Qs(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(u))||0}function tl(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function To(e,t,r){var n=e._x0,i=e._y0,a=e._x1,o=e._y1,u=(a-n)/3;e._context.bezierCurveTo(n+u,i+u*t,a-u,o-u*r,a,o)}function Di(e){this._context=e}Di.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:To(this,this._t0,tl(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,To(this,tl(this,r=el(this,e,t)),r);break;default:To(this,this._t0,r=el(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function fh(e){this._context=new dh(e)}(fh.prototype=Object.create(Di.prototype)).point=function(e,t){Di.prototype.point.call(this,t,e)};function dh(e){this._context=e}dh.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,i,a){this._context.bezierCurveTo(t,e,n,r,a,i)}};function Pw(e){return new Di(e)}function Sw(e){return new fh(e)}function ph(e){this._context=e}ph.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=rl(e),i=rl(t),a=0,o=1;o<r;++a,++o)this._context.bezierCurveTo(n[0][a],i[0][a],n[1][a],i[1][a],e[o],t[o]);(this._line||this._line!==0&&r===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function rl(e){var t,r=e.length-1,n,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=e[0]+2*e[1],t=1;t<r-1;++t)i[t]=1,a[t]=4,o[t]=4*e[t]+2*e[t+1];for(i[r-1]=2,a[r-1]=7,o[r-1]=8*e[r-1]+e[r],t=1;t<r;++t)n=i[t]/a[t-1],a[t]-=n,o[t]-=n*o[t-1];for(i[r-1]=o[r-1]/a[r-1],t=r-2;t>=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[r-1]=(e[r]+i[r-1])/2,t=0;t<r-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function _w(e){return new ph(e)}function Ka(e,t){this._context=e,this._t=t}Ka.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function $w(e){return new Ka(e,.5)}function Tw(e){return new Ka(e,0)}function Ew(e){return new Ka(e,1)}function Ar(e,t){if((o=e.length)>1)for(var r=1,n,i,a=e[t[0]],o,u=a.length;r<o;++r)for(i=a,a=e[t[r]],n=0;n<u;++n)a[n][1]+=a[n][0]=isNaN(i[n][1])?i[n][0]:i[n][1]}function su(e){for(var t=e.length,r=new Array(t);--t>=0;)r[t]=t;return r}function jw(e,t){return e[t]}function Mw(e){const t=[];return t.key=e,t}function Cw(){var e=se([]),t=su,r=Ar,n=jw;function i(a){var o=Array.from(e.apply(this,arguments),Mw),u,c=o.length,s=-1,f;for(const l of a)for(u=0,++s;u<c;++u)(o[u][s]=[0,+n(l,o[u].key,s,a)]).data=l;for(u=0,f=Lc(t(o));u<c;++u)o[f[u]].index=u;return r(o,f),o}return i.keys=function(a){return arguments.length?(e=typeof a=="function"?a:se(Array.from(a)),i):e},i.value=function(a){return arguments.length?(n=typeof a=="function"?a:se(+a),i):n},i.order=function(a){return arguments.length?(t=a==null?su:typeof a=="function"?a:se(Array.from(a)),i):t},i.offset=function(a){return arguments.length?(r=a??Ar,i):r},i}function Iw(e,t){if((n=e.length)>0){for(var r,n,i=0,a=e[0].length,o;i<a;++i){for(o=r=0;r<n;++r)o+=e[r][i][1]||0;if(o)for(r=0;r<n;++r)e[r][i][1]/=o}Ar(e,t)}}function kw(e,t){if((i=e.length)>0){for(var r=0,n=e[t[0]],i,a=n.length;r<a;++r){for(var o=0,u=0;o<i;++o)u+=e[o][r][1]||0;n[r][1]+=n[r][0]=-u/2}Ar(e,t)}}function Nw(e,t){if(!(!((o=e.length)>0)||!((a=(i=e[t[0]]).length)>0))){for(var r=0,n=1,i,a,o;n<a;++n){for(var u=0,c=0,s=0;u<o;++u){for(var f=e[t[u]],l=f[n][1]||0,d=f[n-1][1]||0,p=(l-d)/2,y=0;y<u;++y){var h=e[t[y]],v=h[n][1]||0,b=h[n-1][1]||0;p+=v-b}c+=l,s+=p*l}i[n-1][1]+=i[n-1][0]=r,c&&(r-=s/c)}i[n-1][1]+=i[n-1][0]=r,Ar(e,t)}}function Pn(e){"@babel/helpers - typeof";return Pn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pn(e)}var Dw=["type","size","sizeType"];function lu(){return lu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},lu.apply(this,arguments)}function nl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function il(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?nl(Object(r),!0).forEach(function(n){Rw(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):nl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Rw(e,t,r){return t=Lw(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Lw(e){var t=Bw(e,"string");return Pn(t)=="symbol"?t:t+""}function Bw(e,t){if(Pn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Pn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fw(e,t){if(e==null)return{};var r=Ww(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Ww(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var hh={symbolCircle:Bc,symbolCross:cw,symbolDiamond:lw,symbolSquare:fw,symbolStar:yw,symbolTriangle:vw,symbolWye:mw},zw=Math.PI/180,Uw=function(t){var r="symbol".concat(qa(t));return hh[r]||Bc},qw=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var i=18*zw;return 1.25*t*t*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},Hw=function(t,r){hh["symbol".concat(qa(t))]=r},Fc=function(t){var r=t.type,n=r===void 0?"circle":r,i=t.size,a=i===void 0?64:i,o=t.sizeType,u=o===void 0?"area":o,c=Fw(t,Dw),s=il(il({},c),{},{type:n,size:a,sizeType:u}),f=function(){var v=Uw(n),b=bw().type(v).size(qw(a,u,n));return b()},l=s.className,d=s.cx,p=s.cy,y=X(s,!0);return d===+d&&p===+p&&a===+a?P.createElement("path",lu({},y,{className:J("recharts-symbols",l),transform:"translate(".concat(d,", ").concat(p,")"),d:f()})):null};Fc.registerSymbol=Hw;function Pr(e){"@babel/helpers - typeof";return Pr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pr(e)}function fu(){return fu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},fu.apply(this,arguments)}function al(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Gw(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?al(Object(r),!0).forEach(function(n){Sn(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):al(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Kw(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Xw(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,vh(n.key),n)}}function Vw(e,t,r){return Xw(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Yw(e,t,r){return t=Ri(t),Zw(e,yh()?Reflect.construct(t,r||[],Ri(e).constructor):t.apply(e,r))}function Zw(e,t){if(t&&(Pr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Jw(e)}function Jw(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function yh(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(yh=function(){return!!e})()}function Ri(e){return Ri=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ri(e)}function Qw(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&du(e,t)}function du(e,t){return du=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},du(e,t)}function Sn(e,t,r){return t=vh(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function vh(e){var t=eO(e,"string");return Pr(t)=="symbol"?t:t+""}function eO(e,t){if(Pr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Pr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Qe=32,Wc=function(e){function t(){return Kw(this,t),Yw(this,t,arguments)}return Qw(t,e),Vw(t,[{key:"renderIcon",value:function(n){var i=this.props.inactiveColor,a=Qe/2,o=Qe/6,u=Qe/3,c=n.inactive?i:n.color;if(n.type==="plainline")return P.createElement("line",{strokeWidth:4,fill:"none",stroke:c,strokeDasharray:n.payload.strokeDasharray,x1:0,y1:a,x2:Qe,y2:a,className:"recharts-legend-icon"});if(n.type==="line")return P.createElement("path",{strokeWidth:4,fill:"none",stroke:c,d:"M0,".concat(a,"h").concat(u,` + A`).concat(o,",").concat(o,",0,1,1,").concat(2*u,",").concat(a,` + H`).concat(Qe,"M").concat(2*u,",").concat(a,` + A`).concat(o,",").concat(o,",0,1,1,").concat(u,",").concat(a),className:"recharts-legend-icon"});if(n.type==="rect")return P.createElement("path",{stroke:"none",fill:c,d:"M0,".concat(Qe/8,"h").concat(Qe,"v").concat(Qe*3/4,"h").concat(-32,"z"),className:"recharts-legend-icon"});if(P.isValidElement(n.legendIcon)){var s=Gw({},n);return delete s.legendIcon,P.cloneElement(n.legendIcon,s)}return P.createElement(Fc,{fill:c,cx:a,cy:a,size:Qe,sizeType:"diameter",type:n.type})}},{key:"renderItems",value:function(){var n=this,i=this.props,a=i.payload,o=i.iconSize,u=i.layout,c=i.formatter,s=i.inactiveColor,f={x:0,y:0,width:Qe,height:Qe},l={display:u==="horizontal"?"inline-block":"block",marginRight:10},d={display:"inline-block",verticalAlign:"middle",marginRight:4};return a.map(function(p,y){var h=p.formatter||c,v=J(Sn(Sn({"recharts-legend-item":!0},"legend-item-".concat(y),!0),"inactive",p.inactive));if(p.type==="none")return null;var b=V(p.value)?null:p.value;nt(!V(p.value),`The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: <Bar name="Name of my Data"/>`);var w=p.inactive?s:p.color;return P.createElement("li",fu({className:v,style:l,key:"legend-item-".concat(y)},tr(n.props,p,y)),P.createElement(ru,{width:o,height:o,viewBox:f,style:d},n.renderIcon(p)),P.createElement("span",{className:"recharts-legend-item-text",style:{color:w}},h?h(b,p,y):b))})}},{key:"render",value:function(){var n=this.props,i=n.payload,a=n.layout,o=n.align;if(!i||!i.length)return null;var u={padding:0,margin:0,textAlign:a==="horizontal"?o:"left"};return P.createElement("ul",{className:"recharts-default-legend",style:u},this.renderItems())}}])}(L.PureComponent);Sn(Wc,"displayName","Legend");Sn(Wc,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var tO=Ma;function rO(){this.__data__=new tO,this.size=0}var nO=rO;function iO(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var aO=iO;function oO(e){return this.__data__.get(e)}var uO=oO;function cO(e){return this.__data__.has(e)}var sO=cO,lO=Ma,fO=Tc,dO=Ec,pO=200;function hO(e,t){var r=this.__data__;if(r instanceof lO){var n=r.__data__;if(!fO||n.length<pO-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new dO(n)}return r.set(e,t),this.size=r.size,this}var yO=hO,vO=Ma,gO=nO,mO=aO,bO=uO,xO=sO,wO=yO;function Jr(e){var t=this.__data__=new vO(e);this.size=t.size}Jr.prototype.clear=gO;Jr.prototype.delete=mO;Jr.prototype.get=bO;Jr.prototype.has=xO;Jr.prototype.set=wO;var gh=Jr,OO="__lodash_hash_undefined__";function AO(e){return this.__data__.set(e,OO),this}var PO=AO;function SO(e){return this.__data__.has(e)}var _O=SO,$O=Ec,TO=PO,EO=_O;function Li(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new $O;++t<r;)this.add(e[t])}Li.prototype.add=Li.prototype.push=TO;Li.prototype.has=EO;var mh=Li;function jO(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var bh=jO;function MO(e,t){return e.has(t)}var xh=MO,CO=mh,IO=bh,kO=xh,NO=1,DO=2;function RO(e,t,r,n,i,a){var o=r&NO,u=e.length,c=t.length;if(u!=c&&!(o&&c>u))return!1;var s=a.get(e),f=a.get(t);if(s&&f)return s==t&&f==e;var l=-1,d=!0,p=r&DO?new CO:void 0;for(a.set(e,t),a.set(t,e);++l<u;){var y=e[l],h=t[l];if(n)var v=o?n(h,y,l,t,e,a):n(y,h,l,e,t,a);if(v!==void 0){if(v)continue;d=!1;break}if(p){if(!IO(t,function(b,w){if(!kO(p,w)&&(y===b||i(y,b,r,n,a)))return p.push(w)})){d=!1;break}}else if(!(y===h||i(y,h,r,n,a))){d=!1;break}}return a.delete(e),a.delete(t),d}var wh=RO,LO=st,BO=LO.Uint8Array,FO=BO;function WO(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}var zO=WO;function UO(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var zc=UO,ol=ai,ul=FO,qO=$c,HO=wh,GO=zO,KO=zc,XO=1,VO=2,YO="[object Boolean]",ZO="[object Date]",JO="[object Error]",QO="[object Map]",e1="[object Number]",t1="[object RegExp]",r1="[object Set]",n1="[object String]",i1="[object Symbol]",a1="[object ArrayBuffer]",o1="[object DataView]",cl=ol?ol.prototype:void 0,Eo=cl?cl.valueOf:void 0;function u1(e,t,r,n,i,a,o){switch(r){case o1:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case a1:return!(e.byteLength!=t.byteLength||!a(new ul(e),new ul(t)));case YO:case ZO:case e1:return qO(+e,+t);case JO:return e.name==t.name&&e.message==t.message;case t1:case n1:return e==t+"";case QO:var u=GO;case r1:var c=n&XO;if(u||(u=KO),e.size!=t.size&&!c)return!1;var s=o.get(e);if(s)return s==t;n|=VO,o.set(e,t);var f=HO(u(e),u(t),n,i,a,o);return o.delete(e),f;case i1:if(Eo)return Eo.call(e)==Eo.call(t)}return!1}var c1=u1;function s1(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}var Oh=s1,l1=Oh,f1=Be;function d1(e,t,r){var n=t(e);return f1(e)?n:l1(n,r(e))}var p1=d1;function h1(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}var y1=h1;function v1(){return[]}var g1=v1,m1=y1,b1=g1,x1=Object.prototype,w1=x1.propertyIsEnumerable,sl=Object.getOwnPropertySymbols,O1=sl?function(e){return e==null?[]:(e=Object(e),m1(sl(e),function(t){return w1.call(e,t)}))}:b1,A1=O1;function P1(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var S1=P1,_1=Pt,$1=St,T1="[object Arguments]";function E1(e){return $1(e)&&_1(e)==T1}var j1=E1,ll=j1,M1=St,Ah=Object.prototype,C1=Ah.hasOwnProperty,I1=Ah.propertyIsEnumerable,k1=ll(function(){return arguments}())?ll:function(e){return M1(e)&&C1.call(e,"callee")&&!I1.call(e,"callee")},Uc=k1,Bi={exports:{}};function N1(){return!1}var D1=N1;Bi.exports;(function(e,t){var r=st,n=D1,i=t&&!t.nodeType&&t,a=i&&!0&&e&&!e.nodeType&&e,o=a&&a.exports===i,u=o?r.Buffer:void 0,c=u?u.isBuffer:void 0,s=c||n;e.exports=s})(Bi,Bi.exports);var Ph=Bi.exports,R1=9007199254740991,L1=/^(?:0|[1-9]\d*)$/;function B1(e,t){var r=typeof e;return t=t??R1,!!t&&(r=="number"||r!="symbol"&&L1.test(e))&&e>-1&&e%1==0&&e<t}var qc=B1,F1=9007199254740991;function W1(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=F1}var Hc=W1,z1=Pt,U1=Hc,q1=St,H1="[object Arguments]",G1="[object Array]",K1="[object Boolean]",X1="[object Date]",V1="[object Error]",Y1="[object Function]",Z1="[object Map]",J1="[object Number]",Q1="[object Object]",eA="[object RegExp]",tA="[object Set]",rA="[object String]",nA="[object WeakMap]",iA="[object ArrayBuffer]",aA="[object DataView]",oA="[object Float32Array]",uA="[object Float64Array]",cA="[object Int8Array]",sA="[object Int16Array]",lA="[object Int32Array]",fA="[object Uint8Array]",dA="[object Uint8ClampedArray]",pA="[object Uint16Array]",hA="[object Uint32Array]",de={};de[oA]=de[uA]=de[cA]=de[sA]=de[lA]=de[fA]=de[dA]=de[pA]=de[hA]=!0;de[H1]=de[G1]=de[iA]=de[K1]=de[aA]=de[X1]=de[V1]=de[Y1]=de[Z1]=de[J1]=de[Q1]=de[eA]=de[tA]=de[rA]=de[nA]=!1;function yA(e){return q1(e)&&U1(e.length)&&!!de[z1(e)]}var vA=yA;function gA(e){return function(t){return e(t)}}var Sh=gA,Fi={exports:{}};Fi.exports;(function(e,t){var r=Ip,n=t&&!t.nodeType&&t,i=n&&!0&&e&&!e.nodeType&&e,a=i&&i.exports===n,o=a&&r.process,u=function(){try{var c=i&&i.require&&i.require("util").types;return c||o&&o.binding&&o.binding("util")}catch{}}();e.exports=u})(Fi,Fi.exports);var mA=Fi.exports,bA=vA,xA=Sh,fl=mA,dl=fl&&fl.isTypedArray,wA=dl?xA(dl):bA,_h=wA,OA=S1,AA=Uc,PA=Be,SA=Ph,_A=qc,$A=_h,TA=Object.prototype,EA=TA.hasOwnProperty;function jA(e,t){var r=PA(e),n=!r&&AA(e),i=!r&&!n&&SA(e),a=!r&&!n&&!i&&$A(e),o=r||n||i||a,u=o?OA(e.length,String):[],c=u.length;for(var s in e)(t||EA.call(e,s))&&!(o&&(s=="length"||i&&(s=="offset"||s=="parent")||a&&(s=="buffer"||s=="byteLength"||s=="byteOffset")||_A(s,c)))&&u.push(s);return u}var MA=jA,CA=Object.prototype;function IA(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||CA;return e===r}var kA=IA;function NA(e,t){return function(r){return e(t(r))}}var $h=NA,DA=$h,RA=DA(Object.keys,Object),LA=RA,BA=kA,FA=LA,WA=Object.prototype,zA=WA.hasOwnProperty;function UA(e){if(!BA(e))return FA(e);var t=[];for(var r in Object(e))zA.call(e,r)&&r!="constructor"&&t.push(r);return t}var qA=UA,HA=_c,GA=Hc;function KA(e){return e!=null&&GA(e.length)&&!HA(e)}var si=KA,XA=MA,VA=qA,YA=si;function ZA(e){return YA(e)?XA(e):VA(e)}var Xa=ZA,JA=p1,QA=A1,eP=Xa;function tP(e){return JA(e,eP,QA)}var rP=tP,pl=rP,nP=1,iP=Object.prototype,aP=iP.hasOwnProperty;function oP(e,t,r,n,i,a){var o=r&nP,u=pl(e),c=u.length,s=pl(t),f=s.length;if(c!=f&&!o)return!1;for(var l=c;l--;){var d=u[l];if(!(o?d in t:aP.call(t,d)))return!1}var p=a.get(e),y=a.get(t);if(p&&y)return p==t&&y==e;var h=!0;a.set(e,t),a.set(t,e);for(var v=o;++l<c;){d=u[l];var b=e[d],w=t[d];if(n)var x=o?n(w,b,d,t,e,a):n(b,w,d,e,t,a);if(!(x===void 0?b===w||i(b,w,r,n,a):x)){h=!1;break}v||(v=d=="constructor")}if(h&&!v){var A=e.constructor,g=t.constructor;A!=g&&"constructor"in e&&"constructor"in t&&!(typeof A=="function"&&A instanceof A&&typeof g=="function"&&g instanceof g)&&(h=!1)}return a.delete(e),a.delete(t),h}var uP=oP,cP=or,sP=st,lP=cP(sP,"DataView"),fP=lP,dP=or,pP=st,hP=dP(pP,"Promise"),yP=hP,vP=or,gP=st,mP=vP(gP,"Set"),Th=mP,bP=or,xP=st,wP=bP(xP,"WeakMap"),OP=wP,pu=fP,hu=Tc,yu=yP,vu=Th,gu=OP,Eh=Pt,Qr=Np,hl="[object Map]",AP="[object Object]",yl="[object Promise]",vl="[object Set]",gl="[object WeakMap]",ml="[object DataView]",PP=Qr(pu),SP=Qr(hu),_P=Qr(yu),$P=Qr(vu),TP=Qr(gu),Gt=Eh;(pu&&Gt(new pu(new ArrayBuffer(1)))!=ml||hu&&Gt(new hu)!=hl||yu&&Gt(yu.resolve())!=yl||vu&&Gt(new vu)!=vl||gu&&Gt(new gu)!=gl)&&(Gt=function(e){var t=Eh(e),r=t==AP?e.constructor:void 0,n=r?Qr(r):"";if(n)switch(n){case PP:return ml;case SP:return hl;case _P:return yl;case $P:return vl;case TP:return gl}return t});var EP=Gt,jo=gh,jP=wh,MP=c1,CP=uP,bl=EP,xl=Be,wl=Ph,IP=_h,kP=1,Ol="[object Arguments]",Al="[object Array]",gi="[object Object]",NP=Object.prototype,Pl=NP.hasOwnProperty;function DP(e,t,r,n,i,a){var o=xl(e),u=xl(t),c=o?Al:bl(e),s=u?Al:bl(t);c=c==Ol?gi:c,s=s==Ol?gi:s;var f=c==gi,l=s==gi,d=c==s;if(d&&wl(e)){if(!wl(t))return!1;o=!0,f=!1}if(d&&!f)return a||(a=new jo),o||IP(e)?jP(e,t,r,n,i,a):MP(e,t,c,r,n,i,a);if(!(r&kP)){var p=f&&Pl.call(e,"__wrapped__"),y=l&&Pl.call(t,"__wrapped__");if(p||y){var h=p?e.value():e,v=y?t.value():t;return a||(a=new jo),i(h,v,r,n,a)}}return d?(a||(a=new jo),CP(e,t,r,n,i,a)):!1}var RP=DP,LP=RP,Sl=St;function jh(e,t,r,n,i){return e===t?!0:e==null||t==null||!Sl(e)&&!Sl(t)?e!==e&&t!==t:LP(e,t,r,n,jh,i)}var Gc=jh,BP=gh,FP=Gc,WP=1,zP=2;function UP(e,t,r,n){var i=r.length,a=i,o=!n;if(e==null)return!a;for(e=Object(e);i--;){var u=r[i];if(o&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++i<a;){u=r[i];var c=u[0],s=e[c],f=u[1];if(o&&u[2]){if(s===void 0&&!(c in e))return!1}else{var l=new BP;if(n)var d=n(s,f,c,e,t,l);if(!(d===void 0?FP(f,s,WP|zP,n,l):d))return!1}}return!0}var qP=UP,HP=kt;function GP(e){return e===e&&!HP(e)}var Mh=GP,KP=Mh,XP=Xa;function VP(e){for(var t=XP(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,KP(i)]}return t}var YP=VP;function ZP(e,t){return function(r){return r==null?!1:r[e]===t&&(t!==void 0||e in Object(r))}}var Ch=ZP,JP=qP,QP=YP,eS=Ch;function tS(e){var t=QP(e);return t.length==1&&t[0][2]?eS(t[0][0],t[0][1]):function(r){return r===e||JP(r,e,t)}}var rS=tS;function nS(e,t){return e!=null&&t in Object(e)}var iS=nS,aS=Fp,oS=Uc,uS=Be,cS=qc,sS=Hc,lS=Ia;function fS(e,t,r){t=aS(t,e);for(var n=-1,i=t.length,a=!1;++n<i;){var o=lS(t[n]);if(!(a=e!=null&&r(e,o)))break;e=e[o]}return a||++n!=i?a:(i=e==null?0:e.length,!!i&&sS(i)&&cS(o,i)&&(uS(e)||oS(e)))}var dS=fS,pS=iS,hS=dS;function yS(e,t){return e!=null&&hS(e,t,pS)}var vS=yS,gS=Gc,mS=Wp,bS=vS,xS=Sc,wS=Mh,OS=Ch,AS=Ia,PS=1,SS=2;function _S(e,t){return xS(e)&&wS(t)?OS(AS(e),t):function(r){var n=mS(r,e);return n===void 0&&n===t?bS(r,e):gS(t,n,PS|SS)}}var $S=_S;function TS(e){return e}var en=TS;function ES(e){return function(t){return t==null?void 0:t[e]}}var jS=ES,MS=Cc;function CS(e){return function(t){return MS(t,e)}}var IS=CS,kS=jS,NS=IS,DS=Sc,RS=Ia;function LS(e){return DS(e)?kS(RS(e)):NS(e)}var BS=LS,FS=rS,WS=$S,zS=en,US=Be,qS=BS;function HS(e){return typeof e=="function"?e:e==null?zS:typeof e=="object"?US(e)?WS(e[0],e[1]):FS(e):qS(e)}var lt=HS;function GS(e,t,r,n){for(var i=e.length,a=r+(n?1:-1);n?a--:++a<i;)if(t(e[a],a,e))return a;return-1}var Ih=GS;function KS(e){return e!==e}var XS=KS;function VS(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1}var YS=VS,ZS=Ih,JS=XS,QS=YS;function e_(e,t,r){return t===t?QS(e,t,r):ZS(e,JS,r)}var t_=e_,r_=t_;function n_(e,t){var r=e==null?0:e.length;return!!r&&r_(e,t,0)>-1}var i_=n_;function a_(e,t,r){for(var n=-1,i=e==null?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1}var o_=a_;function u_(){}var c_=u_,Mo=Th,s_=c_,l_=zc,f_=1/0,d_=Mo&&1/l_(new Mo([,-0]))[1]==f_?function(e){return new Mo(e)}:s_,p_=d_,h_=mh,y_=i_,v_=o_,g_=xh,m_=p_,b_=zc,x_=200;function w_(e,t,r){var n=-1,i=y_,a=e.length,o=!0,u=[],c=u;if(r)o=!1,i=v_;else if(a>=x_){var s=t?null:m_(e);if(s)return b_(s);o=!1,i=g_,c=new h_}else c=t?[]:u;e:for(;++n<a;){var f=e[n],l=t?t(f):f;if(f=r||f!==0?f:0,o&&l===l){for(var d=c.length;d--;)if(c[d]===l)continue e;t&&c.push(l),u.push(f)}else i(c,l,r)||(c!==u&&c.push(l),u.push(f))}return u}var O_=w_,A_=lt,P_=O_;function S_(e,t){return e&&e.length?P_(e,A_(t)):[]}var __=S_;const _l=ie(__);function kh(e,t,r){return t===!0?_l(e,r):V(t)?_l(e,t):e}function Sr(e){"@babel/helpers - typeof";return Sr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Sr(e)}var $_=["ref"];function $l(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ft(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$l(Object(r),!0).forEach(function(n){Va(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$l(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function T_(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Tl(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Dh(n.key),n)}}function E_(e,t,r){return Tl(e.prototype,t),Tl(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function j_(e,t,r){return t=Wi(t),M_(e,Nh()?Reflect.construct(t,r,Wi(e).constructor):t.apply(e,r))}function M_(e,t){if(t&&(Sr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return C_(e)}function C_(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Nh(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Nh=function(){return!!e})()}function Wi(e){return Wi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Wi(e)}function I_(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&mu(e,t)}function mu(e,t){return mu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},mu(e,t)}function Va(e,t,r){return t=Dh(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Dh(e){var t=k_(e,"string");return Sr(t)=="symbol"?t:t+""}function k_(e,t){if(Sr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Sr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function N_(e,t){if(e==null)return{};var r=D_(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function D_(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function R_(e){return e.value}function L_(e,t){if(P.isValidElement(e))return P.cloneElement(e,t);if(typeof e=="function")return P.createElement(e,t);t.ref;var r=N_(t,$_);return P.createElement(Wc,r)}var El=1,xr=function(e){function t(){var r;T_(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=j_(this,t,[].concat(i)),Va(r,"lastBoundingBox",{width:-1,height:-1}),r}return I_(t,e),E_(t,[{key:"componentDidMount",value:function(){this.updateBBox()}},{key:"componentDidUpdate",value:function(){this.updateBBox()}},{key:"getBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();return n.height=this.wrapperNode.offsetHeight,n.width=this.wrapperNode.offsetWidth,n}return null}},{key:"updateBBox",value:function(){var n=this.props.onBBoxUpdate,i=this.getBBox();i?(Math.abs(i.width-this.lastBoundingBox.width)>El||Math.abs(i.height-this.lastBoundingBox.height)>El)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?ft({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,a=i.layout,o=i.align,u=i.verticalAlign,c=i.margin,s=i.chartWidth,f=i.chartHeight,l,d;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(o==="center"&&a==="vertical"){var p=this.getBBoxSnapshot();l={left:((s||0)-p.width)/2}}else l=o==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(u==="middle"){var y=this.getBBoxSnapshot();d={top:((f||0)-y.height)/2}}else d=u==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return ft(ft({},l),d)}},{key:"render",value:function(){var n=this,i=this.props,a=i.content,o=i.width,u=i.height,c=i.wrapperStyle,s=i.payloadUniqBy,f=i.payload,l=ft(ft({position:"absolute",width:o||"auto",height:u||"auto"},this.getDefaultPosition(c)),c);return P.createElement("div",{className:"recharts-legend-wrapper",style:l,ref:function(p){n.wrapperNode=p}},L_(a,ft(ft({},this.props),{},{payload:kh(f,s,R_)})))}}],[{key:"getWithHeight",value:function(n,i){var a=ft(ft({},this.defaultProps),n.props),o=a.layout;return o==="vertical"&&R(n.props.height)?{height:n.props.height}:o==="horizontal"?{width:n.props.width||i}:null}}])}(L.PureComponent);Va(xr,"displayName","Legend");Va(xr,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var jl=ai,B_=Uc,F_=Be,Ml=jl?jl.isConcatSpreadable:void 0;function W_(e){return F_(e)||B_(e)||!!(Ml&&e&&e[Ml])}var z_=W_,U_=Oh,q_=z_;function Rh(e,t,r,n,i){var a=-1,o=e.length;for(r||(r=q_),i||(i=[]);++a<o;){var u=e[a];t>0&&r(u)?t>1?Rh(u,t-1,r,n,i):U_(i,u):n||(i[i.length]=u)}return i}var Lh=Rh;function H_(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),u=o.length;u--;){var c=o[e?u:++i];if(r(a[c],c,a)===!1)break}return t}}var G_=H_,K_=G_,X_=K_(),V_=X_,Y_=V_,Z_=Xa;function J_(e,t){return e&&Y_(e,t,Z_)}var Bh=J_,Q_=si;function e$(e,t){return function(r,n){if(r==null)return r;if(!Q_(r))return e(r,n);for(var i=r.length,a=t?i:-1,o=Object(r);(t?a--:++a<i)&&n(o[a],a,o)!==!1;);return r}}var t$=e$,r$=Bh,n$=t$,i$=n$(r$),Kc=i$,a$=Kc,o$=si;function u$(e,t){var r=-1,n=o$(e)?Array(e.length):[];return a$(e,function(i,a,o){n[++r]=t(i,a,o)}),n}var Fh=u$;function c$(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var s$=c$,Cl=Kr;function l$(e,t){if(e!==t){var r=e!==void 0,n=e===null,i=e===e,a=Cl(e),o=t!==void 0,u=t===null,c=t===t,s=Cl(t);if(!u&&!s&&!a&&e>t||a&&o&&c&&!u&&!s||n&&o&&c||!r&&c||!i)return 1;if(!n&&!a&&!s&&e<t||s&&r&&i&&!n&&!a||u&&r&&i||!o&&i||!c)return-1}return 0}var f$=l$,d$=f$;function p$(e,t,r){for(var n=-1,i=e.criteria,a=t.criteria,o=i.length,u=r.length;++n<o;){var c=d$(i[n],a[n]);if(c){if(n>=u)return c;var s=r[n];return c*(s=="desc"?-1:1)}}return e.index-t.index}var h$=p$,Co=Mc,y$=Cc,v$=lt,g$=Fh,m$=s$,b$=Sh,x$=h$,w$=en,O$=Be;function A$(e,t,r){t.length?t=Co(t,function(a){return O$(a)?function(o){return y$(o,a.length===1?a[0]:a)}:a}):t=[w$];var n=-1;t=Co(t,b$(v$));var i=g$(e,function(a,o,u){var c=Co(t,function(s){return s(a)});return{criteria:c,index:++n,value:a}});return m$(i,function(a,o){return x$(a,o,r)})}var P$=A$;function S$(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var _$=S$,$$=_$,Il=Math.max;function T$(e,t,r){return t=Il(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=Il(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var u=Array(t+1);++i<t;)u[i]=n[i];return u[t]=r(o),$$(e,this,u)}}var E$=T$;function j$(e){return function(){return e}}var M$=j$,C$=or,I$=function(){try{var e=C$(Object,"defineProperty");return e({},"",{}),e}catch{}}(),Wh=I$,k$=M$,kl=Wh,N$=en,D$=kl?function(e,t){return kl(e,"toString",{configurable:!0,enumerable:!1,value:k$(t),writable:!0})}:N$,R$=D$,L$=800,B$=16,F$=Date.now;function W$(e){var t=0,r=0;return function(){var n=F$(),i=B$-(n-r);if(r=n,i>0){if(++t>=L$)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var z$=W$,U$=R$,q$=z$,H$=q$(U$),G$=H$,K$=en,X$=E$,V$=G$;function Y$(e,t){return V$(X$(e,t,K$),e+"")}var Z$=Y$,J$=$c,Q$=si,eT=qc,tT=kt;function rT(e,t,r){if(!tT(r))return!1;var n=typeof t;return(n=="number"?Q$(r)&&eT(t,r.length):n=="string"&&t in r)?J$(r[t],e):!1}var Ya=rT,nT=Lh,iT=P$,aT=Z$,Nl=Ya,oT=aT(function(e,t){if(e==null)return[];var r=t.length;return r>1&&Nl(e,t[0],t[1])?t=[]:r>2&&Nl(t[0],t[1],t[2])&&(t=[t[0]]),iT(e,nT(t,1),[])}),uT=oT;const Xc=ie(uT);function _n(e){"@babel/helpers - typeof";return _n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_n(e)}function bu(){return bu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},bu.apply(this,arguments)}function cT(e,t){return dT(e)||fT(e,t)||lT(e,t)||sT()}function sT(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function lT(e,t){if(e){if(typeof e=="string")return Dl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Dl(e,t)}}function Dl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function fT(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function dT(e){if(Array.isArray(e))return e}function Rl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Io(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Rl(Object(r),!0).forEach(function(n){pT(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Rl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function pT(e,t,r){return t=hT(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hT(e){var t=yT(e,"string");return _n(t)=="symbol"?t:t+""}function yT(e,t){if(_n(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(_n(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vT(e){return Array.isArray(e)&&Ae(e[0])&&Ae(e[1])?e.join(" ~ "):e}var gT=function(t){var r=t.separator,n=r===void 0?" : ":r,i=t.contentStyle,a=i===void 0?{}:i,o=t.itemStyle,u=o===void 0?{}:o,c=t.labelStyle,s=c===void 0?{}:c,f=t.payload,l=t.formatter,d=t.itemSorter,p=t.wrapperClassName,y=t.labelClassName,h=t.label,v=t.labelFormatter,b=t.accessibilityLayer,w=b===void 0?!1:b,x=function(){if(f&&f.length){var T={padding:0,margin:0},C=(d?Xc(f,d):f).map(function(I,M){if(I.type==="none")return null;var k=Io({display:"block",paddingTop:4,paddingBottom:4,color:I.color||"#000"},u),D=I.formatter||l||vT,B=I.value,F=I.name,q=B,G=F;if(q!=null&&G!=null){var z=D(B,F,I,M,f);if(Array.isArray(z)){var K=cT(z,2);q=K[0],G=K[1]}else q=z}return P.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(M),style:k},Ae(G)?P.createElement("span",{className:"recharts-tooltip-item-name"},G):null,Ae(G)?P.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,P.createElement("span",{className:"recharts-tooltip-item-value"},q),P.createElement("span",{className:"recharts-tooltip-item-unit"},I.unit||""))});return P.createElement("ul",{className:"recharts-tooltip-item-list",style:T},C)}return null},A=Io({margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},a),g=Io({margin:0},s),m=!Q(h),O=m?h:"",S=J("recharts-default-tooltip",p),_=J("recharts-tooltip-label",y);m&&v&&f!==void 0&&f!==null&&(O=v(h,f));var E=w?{role:"status","aria-live":"assertive"}:{};return P.createElement("div",bu({className:S,style:A},E),P.createElement("p",{className:_,style:g},P.isValidElement(O)?O:"".concat(O)),x())};function $n(e){"@babel/helpers - typeof";return $n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$n(e)}function mi(e,t,r){return t=mT(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function mT(e){var t=bT(e,"string");return $n(t)=="symbol"?t:t+""}function bT(e,t){if($n(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if($n(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var cn="recharts-tooltip-wrapper",xT={visibility:"hidden"};function wT(e){var t=e.coordinate,r=e.translateX,n=e.translateY;return J(cn,mi(mi(mi(mi({},"".concat(cn,"-right"),R(r)&&t&&R(t.x)&&r>=t.x),"".concat(cn,"-left"),R(r)&&t&&R(t.x)&&r<t.x),"".concat(cn,"-bottom"),R(n)&&t&&R(t.y)&&n>=t.y),"".concat(cn,"-top"),R(n)&&t&&R(t.y)&&n<t.y))}function Ll(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.key,i=e.offsetTopLeft,a=e.position,o=e.reverseDirection,u=e.tooltipDimension,c=e.viewBox,s=e.viewBoxDimension;if(a&&R(a[n]))return a[n];var f=r[n]-u-i,l=r[n]+i;if(t[n])return o[n]?f:l;if(o[n]){var d=f,p=c[n];return d<p?Math.max(l,c[n]):Math.max(f,c[n])}var y=l+u,h=c[n]+s;return y>h?Math.max(f,c[n]):Math.max(l,c[n])}function OT(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function AT(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTopLeft,i=e.position,a=e.reverseDirection,o=e.tooltipBox,u=e.useTranslate3d,c=e.viewBox,s,f,l;return o.height>0&&o.width>0&&r?(f=Ll({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.width,viewBox:c,viewBoxDimension:c.width}),l=Ll({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.height,viewBox:c,viewBoxDimension:c.height}),s=OT({translateX:f,translateY:l,useTranslate3d:u})):s=xT,{cssProperties:s,cssClasses:wT({translateX:f,translateY:l,coordinate:r})}}function _r(e){"@babel/helpers - typeof";return _r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_r(e)}function Bl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Fl(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Bl(Object(r),!0).forEach(function(n){wu(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Bl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function PT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ST(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Uh(n.key),n)}}function _T(e,t,r){return ST(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function $T(e,t,r){return t=zi(t),TT(e,zh()?Reflect.construct(t,r,zi(e).constructor):t.apply(e,r))}function TT(e,t){if(t&&(_r(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ET(e)}function ET(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function zh(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(zh=function(){return!!e})()}function zi(e){return zi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},zi(e)}function jT(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&xu(e,t)}function xu(e,t){return xu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},xu(e,t)}function wu(e,t,r){return t=Uh(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Uh(e){var t=MT(e,"string");return _r(t)=="symbol"?t:t+""}function MT(e,t){if(_r(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(_r(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Wl=1,CT=function(e){function t(){var r;PT(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=$T(this,t,[].concat(i)),wu(r,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0},lastBoundingBox:{width:-1,height:-1}}),wu(r,"handleKeyDown",function(o){if(o.key==="Escape"){var u,c,s,f;r.setState({dismissed:!0,dismissedAtCoordinate:{x:(u=(c=r.props.coordinate)===null||c===void 0?void 0:c.x)!==null&&u!==void 0?u:0,y:(s=(f=r.props.coordinate)===null||f===void 0?void 0:f.y)!==null&&s!==void 0?s:0}})}}),r}return jT(t,e),_T(t,[{key:"updateBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();(Math.abs(n.width-this.state.lastBoundingBox.width)>Wl||Math.abs(n.height-this.state.lastBoundingBox.height)>Wl)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,a=i.active,o=i.allowEscapeViewBox,u=i.animationDuration,c=i.animationEasing,s=i.children,f=i.coordinate,l=i.hasPayload,d=i.isAnimationActive,p=i.offset,y=i.position,h=i.reverseDirection,v=i.useTranslate3d,b=i.viewBox,w=i.wrapperStyle,x=AT({allowEscapeViewBox:o,coordinate:f,offsetTopLeft:p,position:y,reverseDirection:h,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:b}),A=x.cssClasses,g=x.cssProperties,m=Fl(Fl({transition:d&&a?"transform ".concat(u,"ms ").concat(c):void 0},g),{},{pointerEvents:"none",visibility:!this.state.dismissed&&a&&l?"visible":"hidden",position:"absolute",top:0,left:0},w);return P.createElement("div",{tabIndex:-1,className:A,style:m,ref:function(S){n.wrapperNode=S}},s)}}])}(L.PureComponent),IT=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},mt={isSsr:IT(),get:function(t){return mt[t]},set:function(t,r){if(typeof t=="string")mt[t]=r;else{var n=Object.keys(t);n&&n.length&&n.forEach(function(i){mt[i]=t[i]})}}};function $r(e){"@babel/helpers - typeof";return $r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$r(e)}function zl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ul(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?zl(Object(r),!0).forEach(function(n){Vc(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):zl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function kT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function NT(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Hh(n.key),n)}}function DT(e,t,r){return NT(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function RT(e,t,r){return t=Ui(t),LT(e,qh()?Reflect.construct(t,r||[],Ui(e).constructor):t.apply(e,r))}function LT(e,t){if(t&&($r(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return BT(e)}function BT(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function qh(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(qh=function(){return!!e})()}function Ui(e){return Ui=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ui(e)}function FT(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ou(e,t)}function Ou(e,t){return Ou=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Ou(e,t)}function Vc(e,t,r){return t=Hh(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Hh(e){var t=WT(e,"string");return $r(t)=="symbol"?t:t+""}function WT(e,t){if($r(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if($r(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zT(e){return e.dataKey}function UT(e,t){return P.isValidElement(e)?P.cloneElement(e,t):typeof e=="function"?P.createElement(e,t):P.createElement(gT,t)}var dt=function(e){function t(){return kT(this,t),RT(this,t,arguments)}return FT(t,e),DT(t,[{key:"render",value:function(){var n=this,i=this.props,a=i.active,o=i.allowEscapeViewBox,u=i.animationDuration,c=i.animationEasing,s=i.content,f=i.coordinate,l=i.filterNull,d=i.isAnimationActive,p=i.offset,y=i.payload,h=i.payloadUniqBy,v=i.position,b=i.reverseDirection,w=i.useTranslate3d,x=i.viewBox,A=i.wrapperStyle,g=y??[];l&&g.length&&(g=kh(y.filter(function(O){return O.value!=null&&(O.hide!==!0||n.props.includeHidden)}),h,zT));var m=g.length>0;return P.createElement(CT,{allowEscapeViewBox:o,animationDuration:u,animationEasing:c,isAnimationActive:d,active:a,coordinate:f,hasPayload:m,offset:p,position:v,reverseDirection:b,useTranslate3d:w,viewBox:x,wrapperStyle:A},UT(s,Ul(Ul({},this.props),{},{payload:g})))}}])}(L.PureComponent);Vc(dt,"displayName","Tooltip");Vc(dt,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!mt.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var qT=st,HT=function(){return qT.Date.now()},GT=HT,KT=/\s/;function XT(e){for(var t=e.length;t--&&KT.test(e.charAt(t)););return t}var VT=XT,YT=VT,ZT=/^\s+/;function JT(e){return e&&e.slice(0,YT(e)+1).replace(ZT,"")}var QT=JT,eE=QT,ql=kt,tE=Kr,Hl=NaN,rE=/^[-+]0x[0-9a-f]+$/i,nE=/^0b[01]+$/i,iE=/^0o[0-7]+$/i,aE=parseInt;function oE(e){if(typeof e=="number")return e;if(tE(e))return Hl;if(ql(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=ql(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=eE(e);var r=nE.test(e);return r||iE.test(e)?aE(e.slice(2),r?2:8):rE.test(e)?Hl:+e}var Gh=oE,uE=kt,ko=GT,Gl=Gh,cE="Expected a function",sE=Math.max,lE=Math.min;function fE(e,t,r){var n,i,a,o,u,c,s=0,f=!1,l=!1,d=!0;if(typeof e!="function")throw new TypeError(cE);t=Gl(t)||0,uE(r)&&(f=!!r.leading,l="maxWait"in r,a=l?sE(Gl(r.maxWait)||0,t):a,d="trailing"in r?!!r.trailing:d);function p(m){var O=n,S=i;return n=i=void 0,s=m,o=e.apply(S,O),o}function y(m){return s=m,u=setTimeout(b,t),f?p(m):o}function h(m){var O=m-c,S=m-s,_=t-O;return l?lE(_,a-S):_}function v(m){var O=m-c,S=m-s;return c===void 0||O>=t||O<0||l&&S>=a}function b(){var m=ko();if(v(m))return w(m);u=setTimeout(b,h(m))}function w(m){return u=void 0,d&&n?p(m):(n=i=void 0,o)}function x(){u!==void 0&&clearTimeout(u),s=0,n=c=i=u=void 0}function A(){return u===void 0?o:w(ko())}function g(){var m=ko(),O=v(m);if(n=arguments,i=this,c=m,O){if(u===void 0)return y(c);if(l)return clearTimeout(u),u=setTimeout(b,t),p(c)}return u===void 0&&(u=setTimeout(b,t)),o}return g.cancel=x,g.flush=A,g}var Kh=fE;const DW=ie(Kh);var dE=Kh,pE=kt,hE="Expected a function";function yE(e,t,r){var n=!0,i=!0;if(typeof e!="function")throw new TypeError(hE);return pE(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),dE(e,t,{leading:n,maxWait:t,trailing:i})}var vE=yE;const Xh=ie(vE);function Tn(e){"@babel/helpers - typeof";return Tn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Tn(e)}function Kl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function bi(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Kl(Object(r),!0).forEach(function(n){gE(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Kl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function gE(e,t,r){return t=mE(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function mE(e){var t=bE(e,"string");return Tn(t)=="symbol"?t:t+""}function bE(e,t){if(Tn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Tn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function xE(e,t){return PE(e)||AE(e,t)||OE(e,t)||wE()}function wE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OE(e,t){if(e){if(typeof e=="string")return Xl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Xl(e,t)}}function Xl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function AE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function PE(e){if(Array.isArray(e))return e}var RW=L.forwardRef(function(e,t){var r=e.aspect,n=e.initialDimension,i=n===void 0?{width:-1,height:-1}:n,a=e.width,o=a===void 0?"100%":a,u=e.height,c=u===void 0?"100%":u,s=e.minWidth,f=s===void 0?0:s,l=e.minHeight,d=e.maxHeight,p=e.children,y=e.debounce,h=y===void 0?0:y,v=e.id,b=e.className,w=e.onResize,x=e.style,A=x===void 0?{}:x,g=L.useRef(null),m=L.useRef();m.current=w,L.useImperativeHandle(t,function(){return Object.defineProperty(g.current,"current",{get:function(){return console.warn("The usage of ref.current.current is deprecated and will no longer be supported."),g.current},configurable:!0})});var O=L.useState({containerWidth:i.width,containerHeight:i.height}),S=xE(O,2),_=S[0],E=S[1],$=L.useCallback(function(C,I){E(function(M){var k=Math.round(C),D=Math.round(I);return M.containerWidth===k&&M.containerHeight===D?M:{containerWidth:k,containerHeight:D}})},[]);L.useEffect(function(){var C=function(F){var q,G=F[0].contentRect,z=G.width,K=G.height;$(z,K),(q=m.current)===null||q===void 0||q.call(m,z,K)};h>0&&(C=Xh(C,h,{trailing:!0,leading:!1}));var I=new ResizeObserver(C),M=g.current.getBoundingClientRect(),k=M.width,D=M.height;return $(k,D),I.observe(g.current),function(){I.disconnect()}},[$,h]);var T=L.useMemo(function(){var C=_.containerWidth,I=_.containerHeight;if(C<0||I<0)return null;nt(Vt(o)||Vt(c),`The width(%s) and height(%s) are both fixed numbers, + maybe you don't need to use a ResponsiveContainer.`,o,c),nt(!r||r>0,"The aspect(%s) must be greater than zero.",r);var M=Vt(o)?C:o,k=Vt(c)?I:c;r&&r>0&&(M?k=M/r:k&&(M=k*r),d&&k>d&&(k=d)),nt(M>0||k>0,`The width(%s) and height(%s) of chart should be greater than 0, + please check the style of container, or the props width(%s) and height(%s), + or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the + height and width.`,M,k,o,c,f,l,r);var D=!Array.isArray(p)&&gt(p.type).endsWith("Chart");return P.Children.map(p,function(B){return P.isValidElement(B)?L.cloneElement(B,bi({width:M,height:k},D?{style:bi({height:"100%",width:"100%",maxHeight:k,maxWidth:M},B.props.style)}:{})):B})},[r,p,c,d,l,f,_,o]);return P.createElement("div",{id:v?"".concat(v):void 0,className:J("recharts-responsive-container",b),style:bi(bi({},A),{},{width:o,height:c,minWidth:f,minHeight:l,maxHeight:d}),ref:g},T)}),Yc=function(t){return null};Yc.displayName="Cell";function En(e){"@babel/helpers - typeof";return En=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},En(e)}function Vl(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Au(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Vl(Object(r),!0).forEach(function(n){SE(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vl(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function SE(e,t,r){return t=_E(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _E(e){var t=$E(e,"string");return En(t)=="symbol"?t:t+""}function $E(e,t){if(En(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(En(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var fr={widthCache:{},cacheCount:0},TE=2e3,EE={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},Yl="recharts_measurement_span";function jE(e){var t=Au({},e);return Object.keys(t).forEach(function(r){t[r]||delete t[r]}),t}var mn=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||mt.isSsr)return{width:0,height:0};var n=jE(r),i=JSON.stringify({text:t,copyStyle:n});if(fr.widthCache[i])return fr.widthCache[i];try{var a=document.getElementById(Yl);a||(a=document.createElement("span"),a.setAttribute("id",Yl),a.setAttribute("aria-hidden","true"),document.body.appendChild(a));var o=Au(Au({},EE),n);Object.assign(a.style,o),a.textContent="".concat(t);var u=a.getBoundingClientRect(),c={width:u.width,height:u.height};return fr.widthCache[i]=c,++fr.cacheCount>TE&&(fr.cacheCount=0,fr.widthCache={}),c}catch{return{width:0,height:0}}},ME=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function jn(e){"@babel/helpers - typeof";return jn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},jn(e)}function qi(e,t){return NE(e)||kE(e,t)||IE(e,t)||CE()}function CE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function IE(e,t){if(e){if(typeof e=="string")return Zl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Zl(e,t)}}function Zl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function kE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function NE(e){if(Array.isArray(e))return e}function DE(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Jl(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,LE(n.key),n)}}function RE(e,t,r){return Jl(e.prototype,t),Jl(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function LE(e){var t=BE(e,"string");return jn(t)=="symbol"?t:t+""}function BE(e,t){if(jn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(jn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Ql=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,ef=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,FE=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,WE=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,Vh={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},zE=Object.keys(Vh),hr="NaN";function UE(e,t){return e*Vh[t]}var xi=function(){function e(t,r){DE(this,e),this.num=t,this.unit=r,this.num=t,this.unit=r,Number.isNaN(t)&&(this.unit=""),r!==""&&!FE.test(r)&&(this.num=NaN,this.unit=""),zE.includes(r)&&(this.num=UE(t,r),this.unit="px")}return RE(e,[{key:"add",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num+r.num,this.unit)}},{key:"subtract",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num-r.num,this.unit)}},{key:"multiply",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num*r.num,this.unit||r.unit)}},{key:"divide",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num/r.num,this.unit||r.unit)}},{key:"toString",value:function(){return"".concat(this.num).concat(this.unit)}},{key:"isNaN",value:function(){return Number.isNaN(this.num)}}],[{key:"parse",value:function(r){var n,i=(n=WE.exec(r))!==null&&n!==void 0?n:[],a=qi(i,3),o=a[1],u=a[2];return new e(parseFloat(o),u??"")}}])}();function Yh(e){if(e.includes(hr))return hr;for(var t=e;t.includes("*")||t.includes("/");){var r,n=(r=Ql.exec(t))!==null&&r!==void 0?r:[],i=qi(n,4),a=i[1],o=i[2],u=i[3],c=xi.parse(a??""),s=xi.parse(u??""),f=o==="*"?c.multiply(s):c.divide(s);if(f.isNaN())return hr;t=t.replace(Ql,f.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var l,d=(l=ef.exec(t))!==null&&l!==void 0?l:[],p=qi(d,4),y=p[1],h=p[2],v=p[3],b=xi.parse(y??""),w=xi.parse(v??""),x=h==="+"?b.add(w):b.subtract(w);if(x.isNaN())return hr;t=t.replace(ef,x.toString())}return t}var tf=/\(([^()]*)\)/;function qE(e){for(var t=e;t.includes("(");){var r=tf.exec(t),n=qi(r,2),i=n[1];t=t.replace(tf,Yh(i))}return t}function HE(e){var t=e.replace(/\s+/g,"");return t=qE(t),t=Yh(t),t}function GE(e){try{return HE(e)}catch{return hr}}function No(e){var t=GE(e.slice(5,-1));return t===hr?"":t}var KE=["x","y","lineHeight","capHeight","scaleToFit","textAnchor","verticalAnchor","fill"],XE=["dx","dy","angle","className","breakAll"];function Pu(){return Pu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Pu.apply(this,arguments)}function rf(e,t){if(e==null)return{};var r=VE(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function VE(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function nf(e,t){return QE(e)||JE(e,t)||ZE(e,t)||YE()}function YE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ZE(e,t){if(e){if(typeof e=="string")return af(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return af(e,t)}}function af(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function JE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function QE(e){if(Array.isArray(e))return e}var Zh=/[ \f\n\r\t\v\u2028\u2029]+/,Jh=function(t){var r=t.children,n=t.breakAll,i=t.style;try{var a=[];Q(r)||(n?a=r.toString().split(""):a=r.toString().split(Zh));var o=a.map(function(c){return{word:c,width:mn(c,i).width}}),u=n?0:mn(" ",i).width;return{wordsWithComputedWidth:o,spaceWidth:u}}catch{return null}},ej=function(t,r,n,i,a){var o=t.maxLines,u=t.children,c=t.style,s=t.breakAll,f=R(o),l=u,d=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return M.reduce(function(k,D){var B=D.word,F=D.width,q=k[k.length-1];if(q&&(i==null||a||q.width+F+n<Number(i)))q.words.push(B),q.width+=F+n;else{var G={words:[B],width:F};k.push(G)}return k},[])},p=d(r),y=function(M){return M.reduce(function(k,D){return k.width>D.width?k:D})};if(!f)return p;for(var h="…",v=function(M){var k=l.slice(0,M),D=Jh({breakAll:s,style:c,children:k+h}).wordsWithComputedWidth,B=d(D),F=B.length>o||y(B).width>Number(i);return[F,B]},b=0,w=l.length-1,x=0,A;b<=w&&x<=l.length-1;){var g=Math.floor((b+w)/2),m=g-1,O=v(m),S=nf(O,2),_=S[0],E=S[1],$=v(g),T=nf($,1),C=T[0];if(!_&&!C&&(b=g+1),_&&C&&(w=g-1),!_&&C){A=E;break}x++}return A||p},of=function(t){var r=Q(t)?[]:t.toString().split(Zh);return[{words:r}]},tj=function(t){var r=t.width,n=t.scaleToFit,i=t.children,a=t.style,o=t.breakAll,u=t.maxLines;if((r||n)&&!mt.isSsr){var c,s,f=Jh({breakAll:o,children:i,style:a});if(f){var l=f.wordsWithComputedWidth,d=f.spaceWidth;c=l,s=d}else return of(i);return ej({breakAll:o,children:i,maxLines:u,style:a},c,s,r,n)}return of(i)},uf="#808080",rr=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.lineHeight,u=o===void 0?"1em":o,c=t.capHeight,s=c===void 0?"0.71em":c,f=t.scaleToFit,l=f===void 0?!1:f,d=t.textAnchor,p=d===void 0?"start":d,y=t.verticalAnchor,h=y===void 0?"end":y,v=t.fill,b=v===void 0?uf:v,w=rf(t,KE),x=L.useMemo(function(){return tj({breakAll:w.breakAll,children:w.children,maxLines:w.maxLines,scaleToFit:l,style:w.style,width:w.width})},[w.breakAll,w.children,w.maxLines,l,w.style,w.width]),A=w.dx,g=w.dy,m=w.angle,O=w.className,S=w.breakAll,_=rf(w,XE);if(!Ae(n)||!Ae(a))return null;var E=n+(R(A)?A:0),$=a+(R(g)?g:0),T;switch(h){case"start":T=No("calc(".concat(s,")"));break;case"middle":T=No("calc(".concat((x.length-1)/2," * -").concat(u," + (").concat(s," / 2))"));break;default:T=No("calc(".concat(x.length-1," * -").concat(u,")"));break}var C=[];if(l){var I=x[0].width,M=w.width;C.push("scale(".concat((R(M)?M/I:1)/I,")"))}return m&&C.push("rotate(".concat(m,", ").concat(E,", ").concat($,")")),C.length&&(_.transform=C.join(" ")),P.createElement("text",Pu({},X(_,!0),{x:E,y:$,className:J("recharts-text",O),textAnchor:p,fill:b.includes("url")?uf:b}),x.map(function(k,D){var B=k.words.join(S?"":" ");return P.createElement("tspan",{x:E,dy:D===0?T:u,key:"".concat(B,"-").concat(D)},B)}))};function Ct(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function rj(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Zc(e){let t,r,n;e.length!==2?(t=Ct,r=(u,c)=>Ct(e(u),c),n=(u,c)=>e(u)-c):(t=e===Ct||e===rj?e:nj,r=e,n=e);function i(u,c,s=0,f=u.length){if(s<f){if(t(c,c)!==0)return f;do{const l=s+f>>>1;r(u[l],c)<0?s=l+1:f=l}while(s<f)}return s}function a(u,c,s=0,f=u.length){if(s<f){if(t(c,c)!==0)return f;do{const l=s+f>>>1;r(u[l],c)<=0?s=l+1:f=l}while(s<f)}return s}function o(u,c,s=0,f=u.length){const l=i(u,c,s,f-1);return l>s&&n(u[l-1],c)>-n(u[l],c)?l-1:l}return{left:i,center:o,right:a}}function nj(){return 0}function Qh(e){return e===null?NaN:+e}function*ij(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const aj=Zc(Ct),li=aj.right;Zc(Qh).center;class cf extends Map{constructor(t,r=cj){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,i]of t)this.set(n,i)}get(t){return super.get(sf(this,t))}has(t){return super.has(sf(this,t))}set(t,r){return super.set(oj(this,t),r)}delete(t){return super.delete(uj(this,t))}}function sf({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function oj({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function uj({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function cj(e){return e!==null&&typeof e=="object"?e.valueOf():e}function sj(e=Ct){if(e===Ct)return ey;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function ey(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(e<t?-1:e>t?1:0)}const lj=Math.sqrt(50),fj=Math.sqrt(10),dj=Math.sqrt(2);function Hi(e,t,r){const n=(t-e)/Math.max(0,r),i=Math.floor(Math.log10(n)),a=n/Math.pow(10,i),o=a>=lj?10:a>=fj?5:a>=dj?2:1;let u,c,s;return i<0?(s=Math.pow(10,-i)/o,u=Math.round(e*s),c=Math.round(t*s),u/s<e&&++u,c/s>t&&--c,s=-s):(s=Math.pow(10,i)*o,u=Math.round(e/s),c=Math.round(t/s),u*s<e&&++u,c*s>t&&--c),c<u&&.5<=r&&r<2?Hi(e,t,r*2):[u,c,s]}function Su(e,t,r){if(t=+t,e=+e,r=+r,!(r>0))return[];if(e===t)return[e];const n=t<e,[i,a,o]=n?Hi(t,e,r):Hi(e,t,r);if(!(a>=i))return[];const u=a-i+1,c=new Array(u);if(n)if(o<0)for(let s=0;s<u;++s)c[s]=(a-s)/-o;else for(let s=0;s<u;++s)c[s]=(a-s)*o;else if(o<0)for(let s=0;s<u;++s)c[s]=(i+s)/-o;else for(let s=0;s<u;++s)c[s]=(i+s)*o;return c}function _u(e,t,r){return t=+t,e=+e,r=+r,Hi(e,t,r)[2]}function $u(e,t,r){t=+t,e=+e,r=+r;const n=t<e,i=n?_u(t,e,r):_u(e,t,r);return(n?-1:1)*(i<0?1/-i:i)}function lf(e,t){let r;for(const n of e)n!=null&&(r<n||r===void 0&&n>=n)&&(r=n);return r}function ff(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function ty(e,t,r=0,n=1/0,i){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(i=i===void 0?ey:sj(i);n>r;){if(n-r>600){const c=n-r+1,s=t-r+1,f=Math.log(c),l=.5*Math.exp(2*f/3),d=.5*Math.sqrt(f*l*(c-l)/c)*(s-c/2<0?-1:1),p=Math.max(r,Math.floor(t-s*l/c+d)),y=Math.min(n,Math.floor(t+(c-s)*l/c+d));ty(e,t,p,y,i)}const a=e[t];let o=r,u=n;for(sn(e,r,t),i(e[n],a)>0&&sn(e,r,n);o<u;){for(sn(e,o,u),++o,--u;i(e[o],a)<0;)++o;for(;i(e[u],a)>0;)--u}i(e[r],a)===0?sn(e,r,u):(++u,sn(e,u,n)),u<=t&&(r=u+1),t<=u&&(n=u-1)}return e}function sn(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function pj(e,t,r){if(e=Float64Array.from(ij(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return ff(e);if(t>=1)return lf(e);var n,i=(n-1)*t,a=Math.floor(i),o=lf(ty(e,a).subarray(0,a+1)),u=ff(e.subarray(a+1));return o+(u-o)*(i-a)}}function hj(e,t,r=Qh){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,i=(n-1)*t,a=Math.floor(i),o=+r(e[a],a,e),u=+r(e[a+1],a+1,e);return o+(u-o)*(i-a)}}function yj(e,t,r){e=+e,t=+t,r=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((t-e)/r))|0,a=new Array(i);++n<i;)a[n]=e+n*r;return a}function Je(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}function _t(e,t){switch(arguments.length){case 0:break;case 1:{typeof e=="function"?this.interpolator(e):this.range(e);break}default:{this.domain(e),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}const Tu=Symbol("implicit");function Jc(){var e=new cf,t=[],r=[],n=Tu;function i(a){let o=e.get(a);if(o===void 0){if(n!==Tu)return n;e.set(a,o=t.push(a)-1)}return r[o%r.length]}return i.domain=function(a){if(!arguments.length)return t.slice();t=[],e=new cf;for(const o of a)e.has(o)||e.set(o,t.push(o)-1);return i},i.range=function(a){return arguments.length?(r=Array.from(a),i):r.slice()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return Jc(t,r).unknown(n)},Je.apply(i,arguments),i}function Mn(){var e=Jc().unknown(void 0),t=e.domain,r=e.range,n=0,i=1,a,o,u=!1,c=0,s=0,f=.5;delete e.unknown;function l(){var d=t().length,p=i<n,y=p?i:n,h=p?n:i;a=(h-y)/Math.max(1,d-c+s*2),u&&(a=Math.floor(a)),y+=(h-y-a*(d-c))*f,o=a*(1-c),u&&(y=Math.round(y),o=Math.round(o));var v=yj(d).map(function(b){return y+a*b});return r(p?v.reverse():v)}return e.domain=function(d){return arguments.length?(t(d),l()):t()},e.range=function(d){return arguments.length?([n,i]=d,n=+n,i=+i,l()):[n,i]},e.rangeRound=function(d){return[n,i]=d,n=+n,i=+i,u=!0,l()},e.bandwidth=function(){return o},e.step=function(){return a},e.round=function(d){return arguments.length?(u=!!d,l()):u},e.padding=function(d){return arguments.length?(c=Math.min(1,s=+d),l()):c},e.paddingInner=function(d){return arguments.length?(c=Math.min(1,d),l()):c},e.paddingOuter=function(d){return arguments.length?(s=+d,l()):s},e.align=function(d){return arguments.length?(f=Math.max(0,Math.min(1,d)),l()):f},e.copy=function(){return Mn(t(),[n,i]).round(u).paddingInner(c).paddingOuter(s).align(f)},Je.apply(l(),arguments)}function ry(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return ry(t())},e}function bn(){return ry(Mn.apply(null,arguments).paddingInner(1))}function Qc(e,t,r){e.prototype=t.prototype=r,r.constructor=e}function ny(e,t){var r=Object.create(e.prototype);for(var n in t)r[n]=t[n];return r}function fi(){}var Cn=.7,Gi=1/Cn,wr="\\s*([+-]?\\d+)\\s*",In="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ot="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",vj=/^#([0-9a-f]{3,8})$/,gj=new RegExp(`^rgb\\(${wr},${wr},${wr}\\)$`),mj=new RegExp(`^rgb\\(${ot},${ot},${ot}\\)$`),bj=new RegExp(`^rgba\\(${wr},${wr},${wr},${In}\\)$`),xj=new RegExp(`^rgba\\(${ot},${ot},${ot},${In}\\)$`),wj=new RegExp(`^hsl\\(${In},${ot},${ot}\\)$`),Oj=new RegExp(`^hsla\\(${In},${ot},${ot},${In}\\)$`),df={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Qc(fi,kn,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:pf,formatHex:pf,formatHex8:Aj,formatHsl:Pj,formatRgb:hf,toString:hf});function pf(){return this.rgb().formatHex()}function Aj(){return this.rgb().formatHex8()}function Pj(){return iy(this).formatHsl()}function hf(){return this.rgb().formatRgb()}function kn(e){var t,r;return e=(e+"").trim().toLowerCase(),(t=vj.exec(e))?(r=t[1].length,t=parseInt(t[1],16),r===6?yf(t):r===3?new Le(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?wi(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?wi(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=gj.exec(e))?new Le(t[1],t[2],t[3],1):(t=mj.exec(e))?new Le(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=bj.exec(e))?wi(t[1],t[2],t[3],t[4]):(t=xj.exec(e))?wi(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=wj.exec(e))?mf(t[1],t[2]/100,t[3]/100,1):(t=Oj.exec(e))?mf(t[1],t[2]/100,t[3]/100,t[4]):df.hasOwnProperty(e)?yf(df[e]):e==="transparent"?new Le(NaN,NaN,NaN,0):null}function yf(e){return new Le(e>>16&255,e>>8&255,e&255,1)}function wi(e,t,r,n){return n<=0&&(e=t=r=NaN),new Le(e,t,r,n)}function Sj(e){return e instanceof fi||(e=kn(e)),e?(e=e.rgb(),new Le(e.r,e.g,e.b,e.opacity)):new Le}function Eu(e,t,r,n){return arguments.length===1?Sj(e):new Le(e,t,r,n??1)}function Le(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}Qc(Le,Eu,ny(fi,{brighter(e){return e=e==null?Gi:Math.pow(Gi,e),new Le(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Cn:Math.pow(Cn,e),new Le(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Le(Qt(this.r),Qt(this.g),Qt(this.b),Ki(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:vf,formatHex:vf,formatHex8:_j,formatRgb:gf,toString:gf}));function vf(){return`#${Yt(this.r)}${Yt(this.g)}${Yt(this.b)}`}function _j(){return`#${Yt(this.r)}${Yt(this.g)}${Yt(this.b)}${Yt((isNaN(this.opacity)?1:this.opacity)*255)}`}function gf(){const e=Ki(this.opacity);return`${e===1?"rgb(":"rgba("}${Qt(this.r)}, ${Qt(this.g)}, ${Qt(this.b)}${e===1?")":`, ${e})`}`}function Ki(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Qt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Yt(e){return e=Qt(e),(e<16?"0":"")+e.toString(16)}function mf(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new rt(e,t,r,n)}function iy(e){if(e instanceof rt)return new rt(e.h,e.s,e.l,e.opacity);if(e instanceof fi||(e=kn(e)),!e)return new rt;if(e instanceof rt)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,i=Math.min(t,r,n),a=Math.max(t,r,n),o=NaN,u=a-i,c=(a+i)/2;return u?(t===a?o=(r-n)/u+(r<n)*6:r===a?o=(n-t)/u+2:o=(t-r)/u+4,u/=c<.5?a+i:2-a-i,o*=60):u=c>0&&c<1?0:o,new rt(o,u,c,e.opacity)}function $j(e,t,r,n){return arguments.length===1?iy(e):new rt(e,t,r,n??1)}function rt(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}Qc(rt,$j,ny(fi,{brighter(e){return e=e==null?Gi:Math.pow(Gi,e),new rt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Cn:Math.pow(Cn,e),new rt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,i=2*r-n;return new Le(Do(e>=240?e-240:e+120,i,n),Do(e,i,n),Do(e<120?e+240:e-120,i,n),this.opacity)},clamp(){return new rt(bf(this.h),Oi(this.s),Oi(this.l),Ki(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Ki(this.opacity);return`${e===1?"hsl(":"hsla("}${bf(this.h)}, ${Oi(this.s)*100}%, ${Oi(this.l)*100}%${e===1?")":`, ${e})`}`}}));function bf(e){return e=(e||0)%360,e<0?e+360:e}function Oi(e){return Math.max(0,Math.min(1,e||0))}function Do(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const es=e=>()=>e;function Tj(e,t){return function(r){return e+r*t}}function Ej(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function jj(e){return(e=+e)==1?ay:function(t,r){return r-t?Ej(t,r,e):es(isNaN(t)?r:t)}}function ay(e,t){var r=t-e;return r?Tj(e,r):es(isNaN(e)?t:e)}const xf=function e(t){var r=jj(t);function n(i,a){var o=r((i=Eu(i)).r,(a=Eu(a)).r),u=r(i.g,a.g),c=r(i.b,a.b),s=ay(i.opacity,a.opacity);return function(f){return i.r=o(f),i.g=u(f),i.b=c(f),i.opacity=s(f),i+""}}return n.gamma=e,n}(1);function Mj(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),i;return function(a){for(i=0;i<r;++i)n[i]=e[i]*(1-a)+t[i]*a;return n}}function Cj(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ij(e,t){var r=t?t.length:0,n=e?Math.min(r,e.length):0,i=new Array(n),a=new Array(r),o;for(o=0;o<n;++o)i[o]=tn(e[o],t[o]);for(;o<r;++o)a[o]=t[o];return function(u){for(o=0;o<n;++o)a[o]=i[o](u);return a}}function kj(e,t){var r=new Date;return e=+e,t=+t,function(n){return r.setTime(e*(1-n)+t*n),r}}function Xi(e,t){return e=+e,t=+t,function(r){return e*(1-r)+t*r}}function Nj(e,t){var r={},n={},i;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(i in t)i in e?r[i]=tn(e[i],t[i]):n[i]=t[i];return function(a){for(i in r)n[i]=r[i](a);return n}}var ju=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ro=new RegExp(ju.source,"g");function Dj(e){return function(){return e}}function Rj(e){return function(t){return e(t)+""}}function Lj(e,t){var r=ju.lastIndex=Ro.lastIndex=0,n,i,a,o=-1,u=[],c=[];for(e=e+"",t=t+"";(n=ju.exec(e))&&(i=Ro.exec(t));)(a=i.index)>r&&(a=t.slice(r,a),u[o]?u[o]+=a:u[++o]=a),(n=n[0])===(i=i[0])?u[o]?u[o]+=i:u[++o]=i:(u[++o]=null,c.push({i:o,x:Xi(n,i)})),r=Ro.lastIndex;return r<t.length&&(a=t.slice(r),u[o]?u[o]+=a:u[++o]=a),u.length<2?c[0]?Rj(c[0].x):Dj(t):(t=c.length,function(s){for(var f=0,l;f<t;++f)u[(l=c[f]).i]=l.x(s);return u.join("")})}function tn(e,t){var r=typeof t,n;return t==null||r==="boolean"?es(t):(r==="number"?Xi:r==="string"?(n=kn(t))?(t=n,xf):Lj:t instanceof kn?xf:t instanceof Date?kj:Cj(t)?Mj:Array.isArray(t)?Ij:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Nj:Xi)(e,t)}function ts(e,t){return e=+e,t=+t,function(r){return Math.round(e*(1-r)+t*r)}}function Bj(e,t){t===void 0&&(t=e,e=tn);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r<n;)a[r]=e(i,i=t[++r]);return function(o){var u=Math.max(0,Math.min(n-1,Math.floor(o*=n)));return a[u](o-u)}}function Fj(e){return function(){return e}}function Vi(e){return+e}var wf=[0,1];function Ne(e){return e}function Mu(e,t){return(t-=e=+e)?function(r){return(r-e)/t}:Fj(isNaN(t)?NaN:.5)}function Wj(e,t){var r;return e>t&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function zj(e,t,r){var n=e[0],i=e[1],a=t[0],o=t[1];return i<n?(n=Mu(i,n),a=r(o,a)):(n=Mu(n,i),a=r(a,o)),function(u){return a(n(u))}}function Uj(e,t,r){var n=Math.min(e.length,t.length)-1,i=new Array(n),a=new Array(n),o=-1;for(e[n]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++o<n;)i[o]=Mu(e[o],e[o+1]),a[o]=r(t[o],t[o+1]);return function(u){var c=li(e,u,1,n)-1;return a[c](i[c](u))}}function di(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Za(){var e=wf,t=wf,r=tn,n,i,a,o=Ne,u,c,s;function f(){var d=Math.min(e.length,t.length);return o!==Ne&&(o=Wj(e[0],e[d-1])),u=d>2?Uj:zj,c=s=null,l}function l(d){return d==null||isNaN(d=+d)?a:(c||(c=u(e.map(n),t,r)))(n(o(d)))}return l.invert=function(d){return o(i((s||(s=u(t,e.map(n),Xi)))(d)))},l.domain=function(d){return arguments.length?(e=Array.from(d,Vi),f()):e.slice()},l.range=function(d){return arguments.length?(t=Array.from(d),f()):t.slice()},l.rangeRound=function(d){return t=Array.from(d),r=ts,f()},l.clamp=function(d){return arguments.length?(o=d?!0:Ne,f()):o!==Ne},l.interpolate=function(d){return arguments.length?(r=d,f()):r},l.unknown=function(d){return arguments.length?(a=d,l):a},function(d,p){return n=d,i=p,f()}}function rs(){return Za()(Ne,Ne)}function qj(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Yi(e,t){if((r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var r,n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function Tr(e){return e=Yi(Math.abs(e)),e?e[1]:NaN}function Hj(e,t){return function(r,n){for(var i=r.length,a=[],o=0,u=e[0],c=0;i>0&&u>0&&(c+u+1>n&&(u=Math.max(1,n-c)),a.push(r.substring(i-=u,i+u)),!((c+=u+1)>n));)u=e[o=(o+1)%e.length];return a.reverse().join(t)}}function Gj(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var Kj=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Nn(e){if(!(t=Kj.exec(e)))throw new Error("invalid format: "+e);var t;return new ns({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Nn.prototype=ns.prototype;function ns(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}ns.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function Xj(e){e:for(var t=e.length,r=1,n=-1,i;r<t;++r)switch(e[r]){case".":n=i=r;break;case"0":n===0&&(n=r),i=r;break;default:if(!+e[r])break e;n>0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(i+1):e}var oy;function Vj(e,t){var r=Yi(e,t);if(!r)return e+"";var n=r[0],i=r[1],a=i-(oy=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=n.length;return a===o?n:a>o?n+new Array(a-o+1).join("0"):a>0?n.slice(0,a)+"."+n.slice(a):"0."+new Array(1-a).join("0")+Yi(e,Math.max(0,t+a-1))[0]}function Of(e,t){var r=Yi(e,t);if(!r)return e+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const Af={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:qj,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>Of(e*100,t),r:Of,s:Vj,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function Pf(e){return e}var Sf=Array.prototype.map,_f=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Yj(e){var t=e.grouping===void 0||e.thousands===void 0?Pf:Hj(Sf.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":e.decimal+"",a=e.numerals===void 0?Pf:Gj(Sf.call(e.numerals,String)),o=e.percent===void 0?"%":e.percent+"",u=e.minus===void 0?"−":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function s(l){l=Nn(l);var d=l.fill,p=l.align,y=l.sign,h=l.symbol,v=l.zero,b=l.width,w=l.comma,x=l.precision,A=l.trim,g=l.type;g==="n"?(w=!0,g="g"):Af[g]||(x===void 0&&(x=12),A=!0,g="g"),(v||d==="0"&&p==="=")&&(v=!0,d="0",p="=");var m=h==="$"?r:h==="#"&&/[boxX]/.test(g)?"0"+g.toLowerCase():"",O=h==="$"?n:/[%p]/.test(g)?o:"",S=Af[g],_=/[defgprs%]/.test(g);x=x===void 0?6:/[gprs]/.test(g)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function E($){var T=m,C=O,I,M,k;if(g==="c")C=S($)+C,$="";else{$=+$;var D=$<0||1/$<0;if($=isNaN($)?c:S(Math.abs($),x),A&&($=Xj($)),D&&+$==0&&y!=="+"&&(D=!1),T=(D?y==="("?y:u:y==="-"||y==="("?"":y)+T,C=(g==="s"?_f[8+oy/3]:"")+C+(D&&y==="("?")":""),_){for(I=-1,M=$.length;++I<M;)if(k=$.charCodeAt(I),48>k||k>57){C=(k===46?i+$.slice(I+1):$.slice(I))+C,$=$.slice(0,I);break}}}w&&!v&&($=t($,1/0));var B=T.length+$.length+C.length,F=B<b?new Array(b-B+1).join(d):"";switch(w&&v&&($=t(F+$,F.length?b-C.length:1/0),F=""),p){case"<":$=T+$+C+F;break;case"=":$=T+F+$+C;break;case"^":$=F.slice(0,B=F.length>>1)+T+$+C+F.slice(B);break;default:$=F+T+$+C;break}return a($)}return E.toString=function(){return l+""},E}function f(l,d){var p=s((l=Nn(l),l.type="f",l)),y=Math.max(-8,Math.min(8,Math.floor(Tr(d)/3)))*3,h=Math.pow(10,-y),v=_f[8+y/3];return function(b){return p(h*b)+v}}return{format:s,formatPrefix:f}}var Ai,is,uy;Zj({thousands:",",grouping:[3],currency:["$",""]});function Zj(e){return Ai=Yj(e),is=Ai.format,uy=Ai.formatPrefix,Ai}function Jj(e){return Math.max(0,-Tr(Math.abs(e)))}function Qj(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Tr(t)/3)))*3-Tr(Math.abs(e)))}function eM(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Tr(t)-Tr(e))+1}function cy(e,t,r,n){var i=$u(e,t,r),a;switch(n=Nn(n??",f"),n.type){case"s":{var o=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(a=Qj(i,o))&&(n.precision=a),uy(n,o)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(a=eM(i,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=a-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(a=Jj(i))&&(n.precision=a-(n.type==="%")*2);break}}return is(n)}function Nt(e){var t=e.domain;return e.ticks=function(r){var n=t();return Su(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var i=t();return cy(i[0],i[i.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),i=0,a=n.length-1,o=n[i],u=n[a],c,s,f=10;for(u<o&&(s=o,o=u,u=s,s=i,i=a,a=s);f-- >0;){if(s=_u(o,u,r),s===c)return n[i]=o,n[a]=u,t(n);if(s>0)o=Math.floor(o/s)*s,u=Math.ceil(u/s)*s;else if(s<0)o=Math.ceil(o*s)/s,u=Math.floor(u*s)/s;else break;c=s}return e},e}function Zi(){var e=rs();return e.copy=function(){return di(e,Zi())},Je.apply(e,arguments),Nt(e)}function sy(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,Vi),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return sy(e).unknown(t)},e=arguments.length?Array.from(e,Vi):[0,1],Nt(r)}function ly(e,t){e=e.slice();var r=0,n=e.length-1,i=e[r],a=e[n],o;return a<i&&(o=r,r=n,n=o,o=i,i=a,a=o),e[r]=t.floor(i),e[n]=t.ceil(a),e}function $f(e){return Math.log(e)}function Tf(e){return Math.exp(e)}function tM(e){return-Math.log(-e)}function rM(e){return-Math.exp(-e)}function nM(e){return isFinite(e)?+("1e"+e):e<0?0:e}function iM(e){return e===10?nM:e===Math.E?Math.exp:t=>Math.pow(e,t)}function aM(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function Ef(e){return(t,r)=>-e(-t,r)}function as(e){const t=e($f,Tf),r=t.domain;let n=10,i,a;function o(){return i=aM(n),a=iM(n),r()[0]<0?(i=Ef(i),a=Ef(a),e(tM,rM)):e($f,Tf),t}return t.base=function(u){return arguments.length?(n=+u,o()):n},t.domain=function(u){return arguments.length?(r(u),o()):r()},t.ticks=u=>{const c=r();let s=c[0],f=c[c.length-1];const l=f<s;l&&([s,f]=[f,s]);let d=i(s),p=i(f),y,h;const v=u==null?10:+u;let b=[];if(!(n%1)&&p-d<v){if(d=Math.floor(d),p=Math.ceil(p),s>0){for(;d<=p;++d)for(y=1;y<n;++y)if(h=d<0?y/a(-d):y*a(d),!(h<s)){if(h>f)break;b.push(h)}}else for(;d<=p;++d)for(y=n-1;y>=1;--y)if(h=d>0?y/a(-d):y*a(d),!(h<s)){if(h>f)break;b.push(h)}b.length*2<v&&(b=Su(s,f,v))}else b=Su(d,p,Math.min(p-d,v)).map(a);return l?b.reverse():b},t.tickFormat=(u,c)=>{if(u==null&&(u=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=Nn(c)).precision==null&&(c.trim=!0),c=is(c)),u===1/0)return c;const s=Math.max(1,n*u/t.ticks().length);return f=>{let l=f/a(Math.round(i(f)));return l*n<n-.5&&(l*=n),l<=s?c(f):""}},t.nice=()=>r(ly(r(),{floor:u=>a(Math.floor(i(u))),ceil:u=>a(Math.ceil(i(u)))})),t}function fy(){const e=as(Za()).domain([1,10]);return e.copy=()=>di(e,fy()).base(e.base()),Je.apply(e,arguments),e}function jf(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function Mf(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function os(e){var t=1,r=e(jf(t),Mf(t));return r.constant=function(n){return arguments.length?e(jf(t=+n),Mf(t)):t},Nt(r)}function dy(){var e=os(Za());return e.copy=function(){return di(e,dy()).constant(e.constant())},Je.apply(e,arguments)}function Cf(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function oM(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function uM(e){return e<0?-e*e:e*e}function us(e){var t=e(Ne,Ne),r=1;function n(){return r===1?e(Ne,Ne):r===.5?e(oM,uM):e(Cf(r),Cf(1/r))}return t.exponent=function(i){return arguments.length?(r=+i,n()):r},Nt(t)}function cs(){var e=us(Za());return e.copy=function(){return di(e,cs()).exponent(e.exponent())},Je.apply(e,arguments),e}function cM(){return cs.apply(null,arguments).exponent(.5)}function If(e){return Math.sign(e)*e*e}function sM(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function py(){var e=rs(),t=[0,1],r=!1,n;function i(a){var o=sM(e(a));return isNaN(o)?n:r?Math.round(o):o}return i.invert=function(a){return e.invert(If(a))},i.domain=function(a){return arguments.length?(e.domain(a),i):e.domain()},i.range=function(a){return arguments.length?(e.range((t=Array.from(a,Vi)).map(If)),i):t.slice()},i.rangeRound=function(a){return i.range(a).round(!0)},i.round=function(a){return arguments.length?(r=!!a,i):r},i.clamp=function(a){return arguments.length?(e.clamp(a),i):e.clamp()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return py(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},Je.apply(i,arguments),Nt(i)}function hy(){var e=[],t=[],r=[],n;function i(){var o=0,u=Math.max(1,t.length);for(r=new Array(u-1);++o<u;)r[o-1]=hj(e,o/u);return a}function a(o){return o==null||isNaN(o=+o)?n:t[li(r,o)]}return a.invertExtent=function(o){var u=t.indexOf(o);return u<0?[NaN,NaN]:[u>0?r[u-1]:e[0],u<r.length?r[u]:e[e.length-1]]},a.domain=function(o){if(!arguments.length)return e.slice();e=[];for(let u of o)u!=null&&!isNaN(u=+u)&&e.push(u);return e.sort(Ct),i()},a.range=function(o){return arguments.length?(t=Array.from(o),i()):t.slice()},a.unknown=function(o){return arguments.length?(n=o,a):n},a.quantiles=function(){return r.slice()},a.copy=function(){return hy().domain(e).range(t).unknown(n)},Je.apply(a,arguments)}function yy(){var e=0,t=1,r=1,n=[.5],i=[0,1],a;function o(c){return c!=null&&c<=c?i[li(n,c,0,r)]:a}function u(){var c=-1;for(n=new Array(r);++c<r;)n[c]=((c+1)*t-(c-r)*e)/(r+1);return o}return o.domain=function(c){return arguments.length?([e,t]=c,e=+e,t=+t,u()):[e,t]},o.range=function(c){return arguments.length?(r=(i=Array.from(c)).length-1,u()):i.slice()},o.invertExtent=function(c){var s=i.indexOf(c);return s<0?[NaN,NaN]:s<1?[e,n[0]]:s>=r?[n[r-1],t]:[n[s-1],n[s]]},o.unknown=function(c){return arguments.length&&(a=c),o},o.thresholds=function(){return n.slice()},o.copy=function(){return yy().domain([e,t]).range(i).unknown(a)},Je.apply(Nt(o),arguments)}function vy(){var e=[.5],t=[0,1],r,n=1;function i(a){return a!=null&&a<=a?t[li(e,a,0,n)]:r}return i.domain=function(a){return arguments.length?(e=Array.from(a),n=Math.min(e.length,t.length-1),i):e.slice()},i.range=function(a){return arguments.length?(t=Array.from(a),n=Math.min(e.length,t.length-1),i):t.slice()},i.invertExtent=function(a){var o=t.indexOf(a);return[e[o-1],e[o]]},i.unknown=function(a){return arguments.length?(r=a,i):r},i.copy=function(){return vy().domain(e).range(t).unknown(r)},Je.apply(i,arguments)}const Lo=new Date,Bo=new Date;function Pe(e,t,r,n){function i(a){return e(a=arguments.length===0?new Date:new Date(+a)),a}return i.floor=a=>(e(a=new Date(+a)),a),i.ceil=a=>(e(a=new Date(a-1)),t(a,1),e(a),a),i.round=a=>{const o=i(a),u=i.ceil(a);return a-o<u-a?o:u},i.offset=(a,o)=>(t(a=new Date(+a),o==null?1:Math.floor(o)),a),i.range=(a,o,u)=>{const c=[];if(a=i.ceil(a),u=u==null?1:Math.floor(u),!(a<o)||!(u>0))return c;let s;do c.push(s=new Date(+a)),t(a,u),e(a);while(s<a&&a<o);return c},i.filter=a=>Pe(o=>{if(o>=o)for(;e(o),!a(o);)o.setTime(o-1)},(o,u)=>{if(o>=o)if(u<0)for(;++u<=0;)for(;t(o,-1),!a(o););else for(;--u>=0;)for(;t(o,1),!a(o););}),r&&(i.count=(a,o)=>(Lo.setTime(+a),Bo.setTime(+o),e(Lo),e(Bo),Math.floor(r(Lo,Bo))),i.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(n?o=>n(o)%a===0:o=>i.count(0,o)%a===0):i)),i}const Ji=Pe(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);Ji.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?Pe(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):Ji);Ji.range;const ht=1e3,Xe=ht*60,yt=Xe*60,xt=yt*24,ss=xt*7,kf=xt*30,Fo=xt*365,Zt=Pe(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*ht)},(e,t)=>(t-e)/ht,e=>e.getUTCSeconds());Zt.range;const ls=Pe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ht)},(e,t)=>{e.setTime(+e+t*Xe)},(e,t)=>(t-e)/Xe,e=>e.getMinutes());ls.range;const fs=Pe(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Xe)},(e,t)=>(t-e)/Xe,e=>e.getUTCMinutes());fs.range;const ds=Pe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ht-e.getMinutes()*Xe)},(e,t)=>{e.setTime(+e+t*yt)},(e,t)=>(t-e)/yt,e=>e.getHours());ds.range;const ps=Pe(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*yt)},(e,t)=>(t-e)/yt,e=>e.getUTCHours());ps.range;const pi=Pe(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Xe)/xt,e=>e.getDate()-1);pi.range;const Ja=Pe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/xt,e=>e.getUTCDate()-1);Ja.range;const gy=Pe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/xt,e=>Math.floor(e/xt));gy.range;function ur(e){return Pe(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Xe)/ss)}const Qa=ur(0),Qi=ur(1),lM=ur(2),fM=ur(3),Er=ur(4),dM=ur(5),pM=ur(6);Qa.range;Qi.range;lM.range;fM.range;Er.range;dM.range;pM.range;function cr(e){return Pe(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/ss)}const eo=cr(0),ea=cr(1),hM=cr(2),yM=cr(3),jr=cr(4),vM=cr(5),gM=cr(6);eo.range;ea.range;hM.range;yM.range;jr.range;vM.range;gM.range;const hs=Pe(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());hs.range;const ys=Pe(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());ys.range;const wt=Pe(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());wt.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Pe(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});wt.range;const Ot=Pe(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());Ot.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Pe(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});Ot.range;function my(e,t,r,n,i,a){const o=[[Zt,1,ht],[Zt,5,5*ht],[Zt,15,15*ht],[Zt,30,30*ht],[a,1,Xe],[a,5,5*Xe],[a,15,15*Xe],[a,30,30*Xe],[i,1,yt],[i,3,3*yt],[i,6,6*yt],[i,12,12*yt],[n,1,xt],[n,2,2*xt],[r,1,ss],[t,1,kf],[t,3,3*kf],[e,1,Fo]];function u(s,f,l){const d=f<s;d&&([s,f]=[f,s]);const p=l&&typeof l.range=="function"?l:c(s,f,l),y=p?p.range(s,+f+1):[];return d?y.reverse():y}function c(s,f,l){const d=Math.abs(f-s)/l,p=Zc(([,,v])=>v).right(o,d);if(p===o.length)return e.every($u(s/Fo,f/Fo,l));if(p===0)return Ji.every(Math.max($u(s,f,l),1));const[y,h]=o[d/o[p-1][2]<o[p][2]/d?p-1:p];return y.every(h)}return[u,c]}const[mM,bM]=my(Ot,ys,eo,gy,ps,fs),[xM,wM]=my(wt,hs,Qa,pi,ds,ls);function Wo(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function zo(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function ln(e,t,r){return{y:e,m:t,d:r,H:0,M:0,S:0,L:0}}function OM(e){var t=e.dateTime,r=e.date,n=e.time,i=e.periods,a=e.days,o=e.shortDays,u=e.months,c=e.shortMonths,s=fn(i),f=dn(i),l=fn(a),d=dn(a),p=fn(o),y=dn(o),h=fn(u),v=dn(u),b=fn(c),w=dn(c),x={a:D,A:B,b:F,B:q,c:null,d:Ff,e:Ff,f:HM,g:tC,G:nC,H:zM,I:UM,j:qM,L:by,m:GM,M:KM,p:G,q:z,Q:Uf,s:qf,S:XM,u:VM,U:YM,V:ZM,w:JM,W:QM,x:null,X:null,y:eC,Y:rC,Z:iC,"%":zf},A={a:K,A:fe,b:ge,B:Fe,c:null,d:Wf,e:Wf,f:cC,g:mC,G:xC,H:aC,I:oC,j:uC,L:wy,m:sC,M:lC,p:Bt,q:De,Q:Uf,s:qf,S:fC,u:dC,U:pC,V:hC,w:yC,W:vC,x:null,X:null,y:gC,Y:bC,Z:wC,"%":zf},g={a:E,A:$,b:T,B:C,c:I,d:Lf,e:Lf,f:LM,g:Rf,G:Df,H:Bf,I:Bf,j:kM,L:RM,m:IM,M:NM,p:_,q:CM,Q:FM,s:WM,S:DM,u:$M,U:TM,V:EM,w:_M,W:jM,x:M,X:k,y:Rf,Y:Df,Z:MM,"%":BM};x.x=m(r,x),x.X=m(n,x),x.c=m(t,x),A.x=m(r,A),A.X=m(n,A),A.c=m(t,A);function m(W,Y){return function(Z){var N=[],ye=-1,ee=0,xe=W.length,we,Re,$t;for(Z instanceof Date||(Z=new Date(+Z));++ye<xe;)W.charCodeAt(ye)===37&&(N.push(W.slice(ee,ye)),(Re=Nf[we=W.charAt(++ye)])!=null?we=W.charAt(++ye):Re=we==="e"?" ":"0",($t=Y[we])&&(we=$t(Z,Re)),N.push(we),ee=ye+1);return N.push(W.slice(ee,ye)),N.join("")}}function O(W,Y){return function(Z){var N=ln(1900,void 0,1),ye=S(N,W,Z+="",0),ee,xe;if(ye!=Z.length)return null;if("Q"in N)return new Date(N.Q);if("s"in N)return new Date(N.s*1e3+("L"in N?N.L:0));if(Y&&!("Z"in N)&&(N.Z=0),"p"in N&&(N.H=N.H%12+N.p*12),N.m===void 0&&(N.m="q"in N?N.q:0),"V"in N){if(N.V<1||N.V>53)return null;"w"in N||(N.w=1),"Z"in N?(ee=zo(ln(N.y,0,1)),xe=ee.getUTCDay(),ee=xe>4||xe===0?ea.ceil(ee):ea(ee),ee=Ja.offset(ee,(N.V-1)*7),N.y=ee.getUTCFullYear(),N.m=ee.getUTCMonth(),N.d=ee.getUTCDate()+(N.w+6)%7):(ee=Wo(ln(N.y,0,1)),xe=ee.getDay(),ee=xe>4||xe===0?Qi.ceil(ee):Qi(ee),ee=pi.offset(ee,(N.V-1)*7),N.y=ee.getFullYear(),N.m=ee.getMonth(),N.d=ee.getDate()+(N.w+6)%7)}else("W"in N||"U"in N)&&("w"in N||(N.w="u"in N?N.u%7:"W"in N?1:0),xe="Z"in N?zo(ln(N.y,0,1)).getUTCDay():Wo(ln(N.y,0,1)).getDay(),N.m=0,N.d="W"in N?(N.w+6)%7+N.W*7-(xe+5)%7:N.w+N.U*7-(xe+6)%7);return"Z"in N?(N.H+=N.Z/100|0,N.M+=N.Z%100,zo(N)):Wo(N)}}function S(W,Y,Z,N){for(var ye=0,ee=Y.length,xe=Z.length,we,Re;ye<ee;){if(N>=xe)return-1;if(we=Y.charCodeAt(ye++),we===37){if(we=Y.charAt(ye++),Re=g[we in Nf?Y.charAt(ye++):we],!Re||(N=Re(W,Z,N))<0)return-1}else if(we!=Z.charCodeAt(N++))return-1}return N}function _(W,Y,Z){var N=s.exec(Y.slice(Z));return N?(W.p=f.get(N[0].toLowerCase()),Z+N[0].length):-1}function E(W,Y,Z){var N=p.exec(Y.slice(Z));return N?(W.w=y.get(N[0].toLowerCase()),Z+N[0].length):-1}function $(W,Y,Z){var N=l.exec(Y.slice(Z));return N?(W.w=d.get(N[0].toLowerCase()),Z+N[0].length):-1}function T(W,Y,Z){var N=b.exec(Y.slice(Z));return N?(W.m=w.get(N[0].toLowerCase()),Z+N[0].length):-1}function C(W,Y,Z){var N=h.exec(Y.slice(Z));return N?(W.m=v.get(N[0].toLowerCase()),Z+N[0].length):-1}function I(W,Y,Z){return S(W,t,Y,Z)}function M(W,Y,Z){return S(W,r,Y,Z)}function k(W,Y,Z){return S(W,n,Y,Z)}function D(W){return o[W.getDay()]}function B(W){return a[W.getDay()]}function F(W){return c[W.getMonth()]}function q(W){return u[W.getMonth()]}function G(W){return i[+(W.getHours()>=12)]}function z(W){return 1+~~(W.getMonth()/3)}function K(W){return o[W.getUTCDay()]}function fe(W){return a[W.getUTCDay()]}function ge(W){return c[W.getUTCMonth()]}function Fe(W){return u[W.getUTCMonth()]}function Bt(W){return i[+(W.getUTCHours()>=12)]}function De(W){return 1+~~(W.getUTCMonth()/3)}return{format:function(W){var Y=m(W+="",x);return Y.toString=function(){return W},Y},parse:function(W){var Y=O(W+="",!1);return Y.toString=function(){return W},Y},utcFormat:function(W){var Y=m(W+="",A);return Y.toString=function(){return W},Y},utcParse:function(W){var Y=O(W+="",!0);return Y.toString=function(){return W},Y}}}var Nf={"-":"",_:" ",0:"0"},$e=/^\s*\d+/,AM=/^%/,PM=/[\\^$*+?|[\]().{}]/g;function te(e,t,r){var n=e<0?"-":"",i=(n?-e:e)+"",a=i.length;return n+(a<r?new Array(r-a+1).join(t)+i:i)}function SM(e){return e.replace(PM,"\\$&")}function fn(e){return new RegExp("^(?:"+e.map(SM).join("|")+")","i")}function dn(e){return new Map(e.map((t,r)=>[t.toLowerCase(),r]))}function _M(e,t,r){var n=$e.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function $M(e,t,r){var n=$e.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function TM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function EM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function jM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function Df(e,t,r){var n=$e.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function Rf(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function MM(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function CM(e,t,r){var n=$e.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function IM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function Lf(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function kM(e,t,r){var n=$e.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function Bf(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function NM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function DM(e,t,r){var n=$e.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function RM(e,t,r){var n=$e.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function LM(e,t,r){var n=$e.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function BM(e,t,r){var n=AM.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function FM(e,t,r){var n=$e.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function WM(e,t,r){var n=$e.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function Ff(e,t){return te(e.getDate(),t,2)}function zM(e,t){return te(e.getHours(),t,2)}function UM(e,t){return te(e.getHours()%12||12,t,2)}function qM(e,t){return te(1+pi.count(wt(e),e),t,3)}function by(e,t){return te(e.getMilliseconds(),t,3)}function HM(e,t){return by(e,t)+"000"}function GM(e,t){return te(e.getMonth()+1,t,2)}function KM(e,t){return te(e.getMinutes(),t,2)}function XM(e,t){return te(e.getSeconds(),t,2)}function VM(e){var t=e.getDay();return t===0?7:t}function YM(e,t){return te(Qa.count(wt(e)-1,e),t,2)}function xy(e){var t=e.getDay();return t>=4||t===0?Er(e):Er.ceil(e)}function ZM(e,t){return e=xy(e),te(Er.count(wt(e),e)+(wt(e).getDay()===4),t,2)}function JM(e){return e.getDay()}function QM(e,t){return te(Qi.count(wt(e)-1,e),t,2)}function eC(e,t){return te(e.getFullYear()%100,t,2)}function tC(e,t){return e=xy(e),te(e.getFullYear()%100,t,2)}function rC(e,t){return te(e.getFullYear()%1e4,t,4)}function nC(e,t){var r=e.getDay();return e=r>=4||r===0?Er(e):Er.ceil(e),te(e.getFullYear()%1e4,t,4)}function iC(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+te(t/60|0,"0",2)+te(t%60,"0",2)}function Wf(e,t){return te(e.getUTCDate(),t,2)}function aC(e,t){return te(e.getUTCHours(),t,2)}function oC(e,t){return te(e.getUTCHours()%12||12,t,2)}function uC(e,t){return te(1+Ja.count(Ot(e),e),t,3)}function wy(e,t){return te(e.getUTCMilliseconds(),t,3)}function cC(e,t){return wy(e,t)+"000"}function sC(e,t){return te(e.getUTCMonth()+1,t,2)}function lC(e,t){return te(e.getUTCMinutes(),t,2)}function fC(e,t){return te(e.getUTCSeconds(),t,2)}function dC(e){var t=e.getUTCDay();return t===0?7:t}function pC(e,t){return te(eo.count(Ot(e)-1,e),t,2)}function Oy(e){var t=e.getUTCDay();return t>=4||t===0?jr(e):jr.ceil(e)}function hC(e,t){return e=Oy(e),te(jr.count(Ot(e),e)+(Ot(e).getUTCDay()===4),t,2)}function yC(e){return e.getUTCDay()}function vC(e,t){return te(ea.count(Ot(e)-1,e),t,2)}function gC(e,t){return te(e.getUTCFullYear()%100,t,2)}function mC(e,t){return e=Oy(e),te(e.getUTCFullYear()%100,t,2)}function bC(e,t){return te(e.getUTCFullYear()%1e4,t,4)}function xC(e,t){var r=e.getUTCDay();return e=r>=4||r===0?jr(e):jr.ceil(e),te(e.getUTCFullYear()%1e4,t,4)}function wC(){return"+0000"}function zf(){return"%"}function Uf(e){return+e}function qf(e){return Math.floor(+e/1e3)}var dr,Ay,Py;OC({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function OC(e){return dr=OM(e),Ay=dr.format,dr.parse,Py=dr.utcFormat,dr.utcParse,dr}function AC(e){return new Date(e)}function PC(e){return e instanceof Date?+e:+new Date(+e)}function vs(e,t,r,n,i,a,o,u,c,s){var f=rs(),l=f.invert,d=f.domain,p=s(".%L"),y=s(":%S"),h=s("%I:%M"),v=s("%I %p"),b=s("%a %d"),w=s("%b %d"),x=s("%B"),A=s("%Y");function g(m){return(c(m)<m?p:u(m)<m?y:o(m)<m?h:a(m)<m?v:n(m)<m?i(m)<m?b:w:r(m)<m?x:A)(m)}return f.invert=function(m){return new Date(l(m))},f.domain=function(m){return arguments.length?d(Array.from(m,PC)):d().map(AC)},f.ticks=function(m){var O=d();return e(O[0],O[O.length-1],m??10)},f.tickFormat=function(m,O){return O==null?g:s(O)},f.nice=function(m){var O=d();return(!m||typeof m.range!="function")&&(m=t(O[0],O[O.length-1],m??10)),m?d(ly(O,m)):f},f.copy=function(){return di(f,vs(e,t,r,n,i,a,o,u,c,s))},f}function SC(){return Je.apply(vs(xM,wM,wt,hs,Qa,pi,ds,ls,Zt,Ay).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function _C(){return Je.apply(vs(mM,bM,Ot,ys,eo,Ja,ps,fs,Zt,Py).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function to(){var e=0,t=1,r,n,i,a,o=Ne,u=!1,c;function s(l){return l==null||isNaN(l=+l)?c:o(i===0?.5:(l=(a(l)-r)*i,u?Math.max(0,Math.min(1,l)):l))}s.domain=function(l){return arguments.length?([e,t]=l,r=a(e=+e),n=a(t=+t),i=r===n?0:1/(n-r),s):[e,t]},s.clamp=function(l){return arguments.length?(u=!!l,s):u},s.interpolator=function(l){return arguments.length?(o=l,s):o};function f(l){return function(d){var p,y;return arguments.length?([p,y]=d,o=l(p,y),s):[o(0),o(1)]}}return s.range=f(tn),s.rangeRound=f(ts),s.unknown=function(l){return arguments.length?(c=l,s):c},function(l){return a=l,r=l(e),n=l(t),i=r===n?0:1/(n-r),s}}function Dt(e,t){return t.domain(e.domain()).interpolator(e.interpolator()).clamp(e.clamp()).unknown(e.unknown())}function Sy(){var e=Nt(to()(Ne));return e.copy=function(){return Dt(e,Sy())},_t.apply(e,arguments)}function _y(){var e=as(to()).domain([1,10]);return e.copy=function(){return Dt(e,_y()).base(e.base())},_t.apply(e,arguments)}function $y(){var e=os(to());return e.copy=function(){return Dt(e,$y()).constant(e.constant())},_t.apply(e,arguments)}function gs(){var e=us(to());return e.copy=function(){return Dt(e,gs()).exponent(e.exponent())},_t.apply(e,arguments)}function $C(){return gs.apply(null,arguments).exponent(.5)}function Ty(){var e=[],t=Ne;function r(n){if(n!=null&&!isNaN(n=+n))return t((li(e,n,1)-1)/(e.length-1))}return r.domain=function(n){if(!arguments.length)return e.slice();e=[];for(let i of n)i!=null&&!isNaN(i=+i)&&e.push(i);return e.sort(Ct),r},r.interpolator=function(n){return arguments.length?(t=n,r):t},r.range=function(){return e.map((n,i)=>t(i/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,a)=>pj(e,a/n))},r.copy=function(){return Ty(t).domain(e)},_t.apply(r,arguments)}function ro(){var e=0,t=.5,r=1,n=1,i,a,o,u,c,s=Ne,f,l=!1,d;function p(h){return isNaN(h=+h)?d:(h=.5+((h=+f(h))-a)*(n*h<n*a?u:c),s(l?Math.max(0,Math.min(1,h)):h))}p.domain=function(h){return arguments.length?([e,t,r]=h,i=f(e=+e),a=f(t=+t),o=f(r=+r),u=i===a?0:.5/(a-i),c=a===o?0:.5/(o-a),n=a<i?-1:1,p):[e,t,r]},p.clamp=function(h){return arguments.length?(l=!!h,p):l},p.interpolator=function(h){return arguments.length?(s=h,p):s};function y(h){return function(v){var b,w,x;return arguments.length?([b,w,x]=v,s=Bj(h,[b,w,x]),p):[s(0),s(.5),s(1)]}}return p.range=y(tn),p.rangeRound=y(ts),p.unknown=function(h){return arguments.length?(d=h,p):d},function(h){return f=h,i=h(e),a=h(t),o=h(r),u=i===a?0:.5/(a-i),c=a===o?0:.5/(o-a),n=a<i?-1:1,p}}function Ey(){var e=Nt(ro()(Ne));return e.copy=function(){return Dt(e,Ey())},_t.apply(e,arguments)}function jy(){var e=as(ro()).domain([.1,1,10]);return e.copy=function(){return Dt(e,jy()).base(e.base())},_t.apply(e,arguments)}function My(){var e=os(ro());return e.copy=function(){return Dt(e,My()).constant(e.constant())},_t.apply(e,arguments)}function ms(){var e=us(ro());return e.copy=function(){return Dt(e,ms()).exponent(e.exponent())},_t.apply(e,arguments)}function TC(){return ms.apply(null,arguments).exponent(.5)}const Hf=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:Mn,scaleDiverging:Ey,scaleDivergingLog:jy,scaleDivergingPow:ms,scaleDivergingSqrt:TC,scaleDivergingSymlog:My,scaleIdentity:sy,scaleImplicit:Tu,scaleLinear:Zi,scaleLog:fy,scaleOrdinal:Jc,scalePoint:bn,scalePow:cs,scaleQuantile:hy,scaleQuantize:yy,scaleRadial:py,scaleSequential:Sy,scaleSequentialLog:_y,scaleSequentialPow:gs,scaleSequentialQuantile:Ty,scaleSequentialSqrt:$C,scaleSequentialSymlog:$y,scaleSqrt:cM,scaleSymlog:dy,scaleThreshold:vy,scaleTime:SC,scaleUtc:_C,tickFormat:cy},Symbol.toStringTag,{value:"Module"}));var EC=Kr;function jC(e,t,r){for(var n=-1,i=e.length;++n<i;){var a=e[n],o=t(a);if(o!=null&&(u===void 0?o===o&&!EC(o):r(o,u)))var u=o,c=a}return c}var no=jC;function MC(e,t){return e>t}var Cy=MC,CC=no,IC=Cy,kC=en;function NC(e){return e&&e.length?CC(e,kC,IC):void 0}var DC=NC;const io=ie(DC);function RC(e,t){return e<t}var Iy=RC,LC=no,BC=Iy,FC=en;function WC(e){return e&&e.length?LC(e,FC,BC):void 0}var zC=WC;const ao=ie(zC);var UC=Mc,qC=lt,HC=Fh,GC=Be;function KC(e,t){var r=GC(e)?UC:HC;return r(e,qC(t))}var XC=KC,VC=Lh,YC=XC;function ZC(e,t){return VC(YC(e,t),1)}var JC=ZC;const QC=ie(JC);var eI=Gc;function tI(e,t){return eI(e,t)}var rI=tI;const oo=ie(rI);var rn=1e9,nI={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},xs,he=!0,Ye="[DecimalError] ",er=Ye+"Invalid argument: ",bs=Ye+"Exponent out of range: ",nn=Math.floor,Kt=Math.pow,iI=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ue,Se=1e7,pe=7,ky=9007199254740991,ta=nn(ky/pe),U={};U.absoluteValue=U.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};U.comparedTo=U.cmp=function(e){var t,r,n,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(n=a.d.length,i=e.d.length,t=0,r=n<i?n:i;t<r;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return n===i?0:n>i^a.s<0?1:-1};U.decimalPlaces=U.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*pe;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};U.dividedBy=U.div=function(e){return bt(this,new this.constructor(e))};U.dividedToIntegerBy=U.idiv=function(e){var t=this,r=t.constructor;return ue(bt(t,new r(e),0,1),r.precision)};U.equals=U.eq=function(e){return!this.cmp(e)};U.exponent=function(){return be(this)};U.greaterThan=U.gt=function(e){return this.cmp(e)>0};U.greaterThanOrEqualTo=U.gte=function(e){return this.cmp(e)>=0};U.isInteger=U.isint=function(){return this.e>this.d.length-2};U.isNegative=U.isneg=function(){return this.s<0};U.isPositive=U.ispos=function(){return this.s>0};U.isZero=function(){return this.s===0};U.lessThan=U.lt=function(e){return this.cmp(e)<0};U.lessThanOrEqualTo=U.lte=function(e){return this.cmp(e)<1};U.logarithm=U.log=function(e){var t,r=this,n=r.constructor,i=n.precision,a=i+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(Ue))throw Error(Ye+"NaN");if(r.s<1)throw Error(Ye+(r.s?"NaN":"-Infinity"));return r.eq(Ue)?new n(0):(he=!1,t=bt(Dn(r,a),Dn(e,a),a),he=!0,ue(t,i))};U.minus=U.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?Ry(t,e):Ny(t,(e.s=-e.s,e))};U.modulo=U.mod=function(e){var t,r=this,n=r.constructor,i=n.precision;if(e=new n(e),!e.s)throw Error(Ye+"NaN");return r.s?(he=!1,t=bt(r,e,0,1).times(e),he=!0,r.minus(t)):ue(new n(r),i)};U.naturalExponential=U.exp=function(){return Dy(this)};U.naturalLogarithm=U.ln=function(){return Dn(this)};U.negated=U.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};U.plus=U.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?Ny(t,e):Ry(t,(e.s=-e.s,e))};U.precision=U.sd=function(e){var t,r,n,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(er+e);if(t=be(i)+1,n=i.d.length-1,r=n*pe+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};U.squareRoot=U.sqrt=function(){var e,t,r,n,i,a,o,u=this,c=u.constructor;if(u.s<1){if(!u.s)return new c(0);throw Error(Ye+"NaN")}for(e=be(u),he=!1,i=Math.sqrt(+u),i==0||i==1/0?(t=at(u.d),(t.length+e)%2==0&&(t+="0"),i=Math.sqrt(t),e=nn((e+1)/2)-(e<0||e%2),i==1/0?t="5e"+e:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new c(t)):n=new c(i.toString()),r=c.precision,i=o=r+3;;)if(a=n,n=a.plus(bt(u,a,o+2)).times(.5),at(a.d).slice(0,o)===(t=at(n.d)).slice(0,o)){if(t=t.slice(o-3,o+1),i==o&&t=="4999"){if(ue(a,r+1,0),a.times(a).eq(u)){n=a;break}}else if(t!="9999")break;o+=4}return he=!0,ue(n,r)};U.times=U.mul=function(e){var t,r,n,i,a,o,u,c,s,f=this,l=f.constructor,d=f.d,p=(e=new l(e)).d;if(!f.s||!e.s)return new l(0);for(e.s*=f.s,r=f.e+e.e,c=d.length,s=p.length,c<s&&(a=d,d=p,p=a,o=c,c=s,s=o),a=[],o=c+s,n=o;n--;)a.push(0);for(n=s;--n>=0;){for(t=0,i=c+n;i>n;)u=a[i]+p[n]*d[i-n-1]+t,a[i--]=u%Se|0,t=u/Se|0;a[i]=(a[i]+t)%Se|0}for(;!a[--o];)a.pop();return t?++r:a.shift(),e.d=a,e.e=r,he?ue(e,l.precision):e};U.toDecimalPlaces=U.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(ct(e,0,rn),t===void 0?t=n.rounding:ct(t,0,8),ue(r,e+be(r)+1,t))};U.toExponential=function(e,t){var r,n=this,i=n.constructor;return e===void 0?r=nr(n,!0):(ct(e,0,rn),t===void 0?t=i.rounding:ct(t,0,8),n=ue(new i(n),e+1,t),r=nr(n,!0,e+1)),r};U.toFixed=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?nr(i):(ct(e,0,rn),t===void 0?t=a.rounding:ct(t,0,8),n=ue(new a(i),e+be(i)+1,t),r=nr(n.abs(),!1,e+be(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};U.toInteger=U.toint=function(){var e=this,t=e.constructor;return ue(new t(e),be(e)+1,t.rounding)};U.toNumber=function(){return+this};U.toPower=U.pow=function(e){var t,r,n,i,a,o,u=this,c=u.constructor,s=12,f=+(e=new c(e));if(!e.s)return new c(Ue);if(u=new c(u),!u.s){if(e.s<1)throw Error(Ye+"Infinity");return u}if(u.eq(Ue))return u;if(n=c.precision,e.eq(Ue))return ue(u,n);if(t=e.e,r=e.d.length-1,o=t>=r,a=u.s,o){if((r=f<0?-f:f)<=ky){for(i=new c(Ue),t=Math.ceil(n/pe+4),he=!1;r%2&&(i=i.times(u),Kf(i.d,t)),r=nn(r/2),r!==0;)u=u.times(u),Kf(u.d,t);return he=!0,e.s<0?new c(Ue).div(i):ue(i,n)}}else if(a<0)throw Error(Ye+"NaN");return a=a<0&&e.d[Math.max(t,r)]&1?-1:1,u.s=1,he=!1,i=e.times(Dn(u,n+s)),he=!0,i=Dy(i),i.s=a,i};U.toPrecision=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?(r=be(i),n=nr(i,r<=a.toExpNeg||r>=a.toExpPos)):(ct(e,1,rn),t===void 0?t=a.rounding:ct(t,0,8),i=ue(new a(i),e,t),r=be(i),n=nr(i,e<=r||r<=a.toExpNeg,e)),n};U.toSignificantDigits=U.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(ct(e,1,rn),t===void 0?t=n.rounding:ct(t,0,8)),ue(new n(r),e,t)};U.toString=U.valueOf=U.val=U.toJSON=U[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=be(e),r=e.constructor;return nr(e,t<=r.toExpNeg||t>=r.toExpPos)};function Ny(e,t){var r,n,i,a,o,u,c,s,f=e.constructor,l=f.precision;if(!e.s||!t.s)return t.s||(t=new f(e)),he?ue(t,l):t;if(c=e.d,s=t.d,o=e.e,i=t.e,c=c.slice(),a=o-i,a){for(a<0?(n=c,a=-a,u=s.length):(n=s,i=o,u=c.length),o=Math.ceil(l/pe),u=o>u?o+1:u+1,a>u&&(a=u,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for(u=c.length,a=s.length,u-a<0&&(a=u,n=s,s=c,c=n),r=0;a;)r=(c[--a]=c[a]+s[a]+r)/Se|0,c[a]%=Se;for(r&&(c.unshift(r),++i),u=c.length;c[--u]==0;)c.pop();return t.d=c,t.e=i,he?ue(t,l):t}function ct(e,t,r){if(e!==~~e||e<t||e>r)throw Error(er+e)}function at(e){var t,r,n,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)n=e[t]+"",r=pe-n.length,r&&(a+=Et(r)),a+=n;o=e[t],n=o+"",r=pe-n.length,r&&(a+=Et(r))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}var bt=function(){function e(n,i){var a,o=0,u=n.length;for(n=n.slice();u--;)a=n[u]*i+o,n[u]=a%Se|0,o=a/Se|0;return o&&n.unshift(o),n}function t(n,i,a,o){var u,c;if(a!=o)c=a>o?1:-1;else for(u=c=0;u<a;u++)if(n[u]!=i[u]){c=n[u]>i[u]?1:-1;break}return c}function r(n,i,a){for(var o=0;a--;)n[a]-=o,o=n[a]<i[a]?1:0,n[a]=o*Se+n[a]-i[a];for(;!n[0]&&n.length>1;)n.shift()}return function(n,i,a,o){var u,c,s,f,l,d,p,y,h,v,b,w,x,A,g,m,O,S,_=n.constructor,E=n.s==i.s?1:-1,$=n.d,T=i.d;if(!n.s)return new _(n);if(!i.s)throw Error(Ye+"Division by zero");for(c=n.e-i.e,O=T.length,g=$.length,p=new _(E),y=p.d=[],s=0;T[s]==($[s]||0);)++s;if(T[s]>($[s]||0)&&--c,a==null?w=a=_.precision:o?w=a+(be(n)-be(i))+1:w=a,w<0)return new _(0);if(w=w/pe+2|0,s=0,O==1)for(f=0,T=T[0],w++;(s<g||f)&&w--;s++)x=f*Se+($[s]||0),y[s]=x/T|0,f=x%T|0;else{for(f=Se/(T[0]+1)|0,f>1&&(T=e(T,f),$=e($,f),O=T.length,g=$.length),A=O,h=$.slice(0,O),v=h.length;v<O;)h[v++]=0;S=T.slice(),S.unshift(0),m=T[0],T[1]>=Se/2&&++m;do f=0,u=t(T,h,O,v),u<0?(b=h[0],O!=v&&(b=b*Se+(h[1]||0)),f=b/m|0,f>1?(f>=Se&&(f=Se-1),l=e(T,f),d=l.length,v=h.length,u=t(l,h,d,v),u==1&&(f--,r(l,O<d?S:T,d))):(f==0&&(u=f=1),l=T.slice()),d=l.length,d<v&&l.unshift(0),r(h,l,v),u==-1&&(v=h.length,u=t(T,h,O,v),u<1&&(f++,r(h,O<v?S:T,v))),v=h.length):u===0&&(f++,h=[0]),y[s++]=f,u&&h[0]?h[v++]=$[A]||0:(h=[$[A]],v=1);while((A++<g||h[0]!==void 0)&&w--)}return y[0]||y.shift(),p.e=c,ue(p,o?a+be(p)+1:a)}}();function Dy(e,t){var r,n,i,a,o,u,c=0,s=0,f=e.constructor,l=f.precision;if(be(e)>16)throw Error(bs+be(e));if(!e.s)return new f(Ue);for(t==null?(he=!1,u=l):u=t,o=new f(.03125);e.abs().gte(.1);)e=e.times(o),s+=5;for(n=Math.log(Kt(2,s))/Math.LN10*2+5|0,u+=n,r=i=a=new f(Ue),f.precision=u;;){if(i=ue(i.times(e),u),r=r.times(++c),o=a.plus(bt(i,r,u)),at(o.d).slice(0,u)===at(a.d).slice(0,u)){for(;s--;)a=ue(a.times(a),u);return f.precision=l,t==null?(he=!0,ue(a,l)):a}a=o}}function be(e){for(var t=e.e*pe,r=e.d[0];r>=10;r/=10)t++;return t}function Uo(e,t,r){if(t>e.LN10.sd())throw he=!0,r&&(e.precision=r),Error(Ye+"LN10 precision limit exceeded");return ue(new e(e.LN10),t)}function Et(e){for(var t="";e--;)t+="0";return t}function Dn(e,t){var r,n,i,a,o,u,c,s,f,l=1,d=10,p=e,y=p.d,h=p.constructor,v=h.precision;if(p.s<1)throw Error(Ye+(p.s?"NaN":"-Infinity"));if(p.eq(Ue))return new h(0);if(t==null?(he=!1,s=v):s=t,p.eq(10))return t==null&&(he=!0),Uo(h,s);if(s+=d,h.precision=s,r=at(y),n=r.charAt(0),a=be(p),Math.abs(a)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)p=p.times(e),r=at(p.d),n=r.charAt(0),l++;a=be(p),n>1?(p=new h("0."+r),a++):p=new h(n+"."+r.slice(1))}else return c=Uo(h,s+2,v).times(a+""),p=Dn(new h(n+"."+r.slice(1)),s-d).plus(c),h.precision=v,t==null?(he=!0,ue(p,v)):p;for(u=o=p=bt(p.minus(Ue),p.plus(Ue),s),f=ue(p.times(p),s),i=3;;){if(o=ue(o.times(f),s),c=u.plus(bt(o,new h(i),s)),at(c.d).slice(0,s)===at(u.d).slice(0,s))return u=u.times(2),a!==0&&(u=u.plus(Uo(h,s+2,v).times(a+""))),u=bt(u,new h(l),s),h.precision=v,t==null?(he=!0,ue(u,v)):u;u=c,i+=2}}function Gf(e,t){var r,n,i;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(i=t.length;t.charCodeAt(i-1)===48;)--i;if(t=t.slice(n,i),t){if(i-=n,r=r-n-1,e.e=nn(r/pe),e.d=[],n=(r+1)%pe,r<0&&(n+=pe),n<i){for(n&&e.d.push(+t.slice(0,n)),i-=pe;n<i;)e.d.push(+t.slice(n,n+=pe));t=t.slice(n),n=pe-t.length}else n-=i;for(;n--;)t+="0";if(e.d.push(+t),he&&(e.e>ta||e.e<-ta))throw Error(bs+r)}else e.s=0,e.e=0,e.d=[0];return e}function ue(e,t,r){var n,i,a,o,u,c,s,f,l=e.d;for(o=1,a=l[0];a>=10;a/=10)o++;if(n=t-o,n<0)n+=pe,i=t,s=l[f=0];else{if(f=Math.ceil((n+1)/pe),a=l.length,f>=a)return e;for(s=a=l[f],o=1;a>=10;a/=10)o++;n%=pe,i=n-pe+o}if(r!==void 0&&(a=Kt(10,o-i-1),u=s/a%10|0,c=t<0||l[f+1]!==void 0||s%a,c=r<4?(u||c)&&(r==0||r==(e.s<0?3:2)):u>5||u==5&&(r==4||c||r==6&&(n>0?i>0?s/Kt(10,o-i):0:l[f-1])%10&1||r==(e.s<0?8:7))),t<1||!l[0])return c?(a=be(e),l.length=1,t=t-a-1,l[0]=Kt(10,(pe-t%pe)%pe),e.e=nn(-t/pe)||0):(l.length=1,l[0]=e.e=e.s=0),e;if(n==0?(l.length=f,a=1,f--):(l.length=f+1,a=Kt(10,pe-n),l[f]=i>0?(s/Kt(10,o-i)%Kt(10,i)|0)*a:0),c)for(;;)if(f==0){(l[0]+=a)==Se&&(l[0]=1,++e.e);break}else{if(l[f]+=a,l[f]!=Se)break;l[f--]=0,a=1}for(n=l.length;l[--n]===0;)l.pop();if(he&&(e.e>ta||e.e<-ta))throw Error(bs+be(e));return e}function Ry(e,t){var r,n,i,a,o,u,c,s,f,l,d=e.constructor,p=d.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new d(e),he?ue(t,p):t;if(c=e.d,l=t.d,n=t.e,s=e.e,c=c.slice(),o=s-n,o){for(f=o<0,f?(r=c,o=-o,u=l.length):(r=l,n=s,u=c.length),i=Math.max(Math.ceil(p/pe),u)+2,o>i&&(o=i,r.length=1),r.reverse(),i=o;i--;)r.push(0);r.reverse()}else{for(i=c.length,u=l.length,f=i<u,f&&(u=i),i=0;i<u;i++)if(c[i]!=l[i]){f=c[i]<l[i];break}o=0}for(f&&(r=c,c=l,l=r,t.s=-t.s),u=c.length,i=l.length-u;i>0;--i)c[u++]=0;for(i=l.length;i>o;){if(c[--i]<l[i]){for(a=i;a&&c[--a]===0;)c[a]=Se-1;--c[a],c[i]+=Se}c[i]-=l[i]}for(;c[--u]===0;)c.pop();for(;c[0]===0;c.shift())--n;return c[0]?(t.d=c,t.e=n,he?ue(t,p):t):new d(0)}function nr(e,t,r){var n,i=be(e),a=at(e.d),o=a.length;return t?(r&&(n=r-o)>0?a=a.charAt(0)+"."+a.slice(1)+Et(n):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(i<0?"e":"e+")+i):i<0?(a="0."+Et(-i-1)+a,r&&(n=r-o)>0&&(a+=Et(n))):i>=o?(a+=Et(i+1-o),r&&(n=r-i-1)>0&&(a=a+"."+Et(n))):((n=i+1)<o&&(a=a.slice(0,n)+"."+a.slice(n)),r&&(n=r-o)>0&&(i+1===o&&(a+="."),a+=Et(n))),e.s<0?"-"+a:a}function Kf(e,t){if(e.length>t)return e.length=t,!0}function Ly(e){var t,r,n;function i(a){var o=this;if(!(o instanceof i))return new i(a);if(o.constructor=i,a instanceof i){o.s=a.s,o.e=a.e,o.d=(a=a.d)?a.slice():a;return}if(typeof a=="number"){if(a*0!==0)throw Error(er+a);if(a>0)o.s=1;else if(a<0)a=-a,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(a===~~a&&a<1e7){o.e=0,o.d=[a];return}return Gf(o,a.toString())}else if(typeof a!="string")throw Error(er+a);if(a.charCodeAt(0)===45?(a=a.slice(1),o.s=-1):o.s=1,iI.test(a))Gf(o,a);else throw Error(er+a)}if(i.prototype=U,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=Ly,i.config=i.set=aI,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<n.length;)e.hasOwnProperty(r=n[t++])||(e[r]=this[r]);return i.config(e),i}function aI(e){if(!e||typeof e!="object")throw Error(Ye+"Object expected");var t,r,n,i=["precision",1,rn,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<i.length;t+=3)if((n=e[r=i[t]])!==void 0)if(nn(n)===n&&n>=i[t+1]&&n<=i[t+2])this[r]=n;else throw Error(er+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(er+r+": "+n);return this}var xs=Ly(nI);Ue=new xs(1);const oe=xs;function oI(e){return lI(e)||sI(e)||cI(e)||uI()}function uI(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cI(e,t){if(e){if(typeof e=="string")return Cu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Cu(e,t)}}function sI(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function lI(e){if(Array.isArray(e))return Cu(e)}function Cu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var fI=function(t){return t},By={"@@functional/placeholder":!0},Fy=function(t){return t===By},Xf=function(t){return function r(){return arguments.length===0||arguments.length===1&&Fy(arguments.length<=0?void 0:arguments[0])?r:t.apply(void 0,arguments)}},dI=function e(t,r){return t===1?r:Xf(function(){for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];var o=i.filter(function(u){return u!==By}).length;return o>=t?r.apply(void 0,i):e(t-o,Xf(function(){for(var u=arguments.length,c=new Array(u),s=0;s<u;s++)c[s]=arguments[s];var f=i.map(function(l){return Fy(l)?c.shift():l});return r.apply(void 0,oI(f).concat(c))}))})},uo=function(t){return dI(t.length,t)},Iu=function(t,r){for(var n=[],i=t;i<r;++i)n[i-t]=i;return n},pI=uo(function(e,t){return Array.isArray(t)?t.map(e):Object.keys(t).map(function(r){return t[r]}).map(e)}),hI=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(!r.length)return fI;var i=r.reverse(),a=i[0],o=i.slice(1);return function(){return o.reduce(function(u,c){return c(u)},a.apply(void 0,arguments))}},ku=function(t){return Array.isArray(t)?t.reverse():t.split("").reverse.join("")},Wy=function(t){var r=null,n=null;return function(){for(var i=arguments.length,a=new Array(i),o=0;o<i;o++)a[o]=arguments[o];return r&&a.every(function(u,c){return u===r[c]})||(r=a,n=t.apply(void 0,a)),n}};function yI(e){var t;return e===0?t=1:t=Math.floor(new oe(e).abs().log(10).toNumber())+1,t}function vI(e,t,r){for(var n=new oe(e),i=0,a=[];n.lt(t)&&i<1e5;)a.push(n.toNumber()),n=n.add(r),i++;return a}var gI=uo(function(e,t,r){var n=+e,i=+t;return n+r*(i-n)}),mI=uo(function(e,t,r){var n=t-+e;return n=n||1/0,(r-e)/n}),bI=uo(function(e,t,r){var n=t-+e;return n=n||1/0,Math.max(0,Math.min(1,(r-e)/n))});const co={rangeStep:vI,getDigitCount:yI,interpolateNumber:gI,uninterpolateNumber:mI,uninterpolateTruncation:bI};function Nu(e){return OI(e)||wI(e)||zy(e)||xI()}function xI(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wI(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function OI(e){if(Array.isArray(e))return Du(e)}function Rn(e,t){return SI(e)||PI(e,t)||zy(e,t)||AI()}function AI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zy(e,t){if(e){if(typeof e=="string")return Du(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Du(e,t)}}function Du(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function PI(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var r=[],n=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),u;!(n=(u=o.next()).done)&&(r.push(u.value),!(t&&r.length===t));n=!0);}catch(c){i=!0,a=c}finally{try{!n&&o.return!=null&&o.return()}finally{if(i)throw a}}return r}}function SI(e){if(Array.isArray(e))return e}function Uy(e){var t=Rn(e,2),r=t[0],n=t[1],i=r,a=n;return r>n&&(i=n,a=r),[i,a]}function qy(e,t,r){if(e.lte(0))return new oe(0);var n=co.getDigitCount(e.toNumber()),i=new oe(10).pow(n),a=e.div(i),o=n!==1?.05:.1,u=new oe(Math.ceil(a.div(o).toNumber())).add(r).mul(o),c=u.mul(i);return t?c:new oe(Math.ceil(c))}function _I(e,t,r){var n=1,i=new oe(e);if(!i.isint()&&r){var a=Math.abs(e);a<1?(n=new oe(10).pow(co.getDigitCount(e)-1),i=new oe(Math.floor(i.div(n).toNumber())).mul(n)):a>1&&(i=new oe(Math.floor(e)))}else e===0?i=new oe(Math.floor((t-1)/2)):r||(i=new oe(Math.floor(e)));var o=Math.floor((t-1)/2),u=hI(pI(function(c){return i.add(new oe(c-o).mul(n)).toNumber()}),Iu);return u(0,t)}function Hy(e,t,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-e)/(r-1)))return{step:new oe(0),tickMin:new oe(0),tickMax:new oe(0)};var a=qy(new oe(t).sub(e).div(r-1),n,i),o;e<=0&&t>=0?o=new oe(0):(o=new oe(e).add(t).div(2),o=o.sub(new oe(o).mod(a)));var u=Math.ceil(o.sub(e).div(a).toNumber()),c=Math.ceil(new oe(t).sub(o).div(a).toNumber()),s=u+c+1;return s>r?Hy(e,t,r,n,i+1):(s<r&&(c=t>0?c+(r-s):c,u=t>0?u:u+(r-s)),{step:a,tickMin:o.sub(new oe(u).mul(a)),tickMax:o.add(new oe(c).mul(a))})}function $I(e){var t=Rn(e,2),r=t[0],n=t[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),u=Uy([r,n]),c=Rn(u,2),s=c[0],f=c[1];if(s===-1/0||f===1/0){var l=f===1/0?[s].concat(Nu(Iu(0,i-1).map(function(){return 1/0}))):[].concat(Nu(Iu(0,i-1).map(function(){return-1/0})),[f]);return r>n?ku(l):l}if(s===f)return _I(s,i,a);var d=Hy(s,f,o,a),p=d.step,y=d.tickMin,h=d.tickMax,v=co.rangeStep(y,h.add(new oe(.1).mul(p)),p);return r>n?ku(v):v}function TI(e,t){var r=Rn(e,2),n=r[0],i=r[1],a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Uy([n,i]),u=Rn(o,2),c=u[0],s=u[1];if(c===-1/0||s===1/0)return[n,i];if(c===s)return[c];var f=Math.max(t,2),l=qy(new oe(s).sub(c).div(f-1),a,0),d=[].concat(Nu(co.rangeStep(new oe(c),new oe(s).sub(new oe(.99).mul(l)),l)),[s]);return n>i?ku(d):d}var EI=Wy($I),jI=Wy(TI),MI="Invariant failed";function ir(e,t){throw new Error(MI)}var CI=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function Mr(e){"@babel/helpers - typeof";return Mr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mr(e)}function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ra.apply(this,arguments)}function II(e,t){return RI(e)||DI(e,t)||NI(e,t)||kI()}function kI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NI(e,t){if(e){if(typeof e=="string")return Vf(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Vf(e,t)}}function Vf(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function DI(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function RI(e){if(Array.isArray(e))return e}function LI(e,t){if(e==null)return{};var r=BI(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function BI(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function FI(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function WI(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Xy(n.key),n)}}function zI(e,t,r){return WI(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function UI(e,t,r){return t=na(t),qI(e,Gy()?Reflect.construct(t,r||[],na(e).constructor):t.apply(e,r))}function qI(e,t){if(t&&(Mr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return HI(e)}function HI(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Gy(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Gy=function(){return!!e})()}function na(e){return na=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},na(e)}function GI(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ru(e,t)}function Ru(e,t){return Ru=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Ru(e,t)}function Ky(e,t,r){return t=Xy(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Xy(e){var t=KI(e,"string");return Mr(t)=="symbol"?t:t+""}function KI(e,t){if(Mr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Mr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var so=function(e){function t(){return FI(this,t),UI(this,t,arguments)}return GI(t,e),zI(t,[{key:"render",value:function(){var n=this.props,i=n.offset,a=n.layout,o=n.width,u=n.dataKey,c=n.data,s=n.dataPointFormatter,f=n.xAxis,l=n.yAxis,d=LI(n,CI),p=X(d,!1);this.props.direction==="x"&&f.type!=="number"&&ir();var y=c.map(function(h){var v=s(h,u),b=v.x,w=v.y,x=v.value,A=v.errorVal;if(!A)return null;var g=[],m,O;if(Array.isArray(A)){var S=II(A,2);m=S[0],O=S[1]}else m=O=A;if(a==="vertical"){var _=f.scale,E=w+i,$=E+o,T=E-o,C=_(x-m),I=_(x+O);g.push({x1:I,y1:$,x2:I,y2:T}),g.push({x1:C,y1:E,x2:I,y2:E}),g.push({x1:C,y1:$,x2:C,y2:T})}else if(a==="horizontal"){var M=l.scale,k=b+i,D=k-o,B=k+o,F=M(x-m),q=M(x+O);g.push({x1:D,y1:q,x2:B,y2:q}),g.push({x1:k,y1:F,x2:k,y2:q}),g.push({x1:D,y1:F,x2:B,y2:F})}return P.createElement(ne,ra({className:"recharts-errorBar",key:"bar-".concat(g.map(function(G){return"".concat(G.x1,"-").concat(G.x2,"-").concat(G.y1,"-").concat(G.y2)}))},p),g.map(function(G){return P.createElement("line",ra({},G,{key:"line-".concat(G.x1,"-").concat(G.x2,"-").concat(G.y1,"-").concat(G.y2)}))}))});return P.createElement(ne,{className:"recharts-errorBars"},y)}}])}(P.Component);Ky(so,"defaultProps",{stroke:"black",strokeWidth:1.5,width:5,offset:0,layout:"horizontal"});Ky(so,"displayName","ErrorBar");function Ln(e){"@babel/helpers - typeof";return Ln=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ln(e)}function Yf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function zt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Yf(Object(r),!0).forEach(function(n){XI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Yf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function XI(e,t,r){return t=VI(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function VI(e){var t=YI(e,"string");return Ln(t)=="symbol"?t:t+""}function YI(e,t){if(Ln(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ln(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Vy=function(t){var r=t.children,n=t.formattedGraphicalItems,i=t.legendWidth,a=t.legendContent,o=ze(r,xr);if(!o)return null;var u=xr.defaultProps,c=u!==void 0?zt(zt({},u),o.props):{},s;return o.props&&o.props.payload?s=o.props&&o.props.payload:a==="children"?s=(n||[]).reduce(function(f,l){var d=l.item,p=l.props,y=p.sectors||p.data||[];return f.concat(y.map(function(h){return{type:o.props.iconType||d.props.legendType,value:h.name,color:h.fill,payload:h}}))},[]):s=(n||[]).map(function(f){var l=f.item,d=l.type.defaultProps,p=d!==void 0?zt(zt({},d),l.props):{},y=p.dataKey,h=p.name,v=p.legendType,b=p.hide;return{inactive:b,dataKey:y,type:c.iconType||v||"square",color:ws(l),value:h||y,payload:p}}),zt(zt(zt({},c),xr.getWithHeight(o,i)),{},{payload:s,item:o})};function Bn(e){"@babel/helpers - typeof";return Bn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bn(e)}function Zf(e){return ek(e)||QI(e)||JI(e)||ZI()}function ZI(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JI(e,t){if(e){if(typeof e=="string")return Lu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Lu(e,t)}}function QI(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ek(e){if(Array.isArray(e))return Lu(e)}function Lu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Jf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ve(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Jf(Object(r),!0).forEach(function(n){Or(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Jf(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Or(e,t,r){return t=tk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tk(e){var t=rk(e,"string");return Bn(t)=="symbol"?t:t+""}function rk(e,t){if(Bn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Bn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Me(e,t,r){return Q(e)||Q(t)?r:Ae(t)?qe(e,t,r):V(t)?t(e):r}function xn(e,t,r,n){var i=QC(e,function(u){return Me(u,t)});if(r==="number"){var a=i.filter(function(u){return R(u)||parseFloat(u)});return a.length?[ao(a),io(a)]:[1/0,-1/0]}var o=n?i.filter(function(u){return!Q(u)}):i;return o.map(function(u){return Ae(u)||u instanceof Date?u:""})}var nk=function(t){var r,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,o=-1,u=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(u<=1)return 0;if(a&&a.axisType==="angleAxis"&&Math.abs(Math.abs(a.range[1]-a.range[0])-360)<=1e-6)for(var c=a.range,s=0;s<u;s++){var f=s>0?i[s-1].coordinate:i[u-1].coordinate,l=i[s].coordinate,d=s>=u-1?i[0].coordinate:i[s+1].coordinate,p=void 0;if(Ie(l-f)!==Ie(d-l)){var y=[];if(Ie(d-l)===Ie(c[1]-c[0])){p=d;var h=l+c[1]-c[0];y[0]=Math.min(h,(h+f)/2),y[1]=Math.max(h,(h+f)/2)}else{p=f;var v=d+c[1]-c[0];y[0]=Math.min(l,(v+l)/2),y[1]=Math.max(l,(v+l)/2)}var b=[Math.min(l,(p+l)/2),Math.max(l,(p+l)/2)];if(t>b[0]&&t<=b[1]||t>=y[0]&&t<=y[1]){o=i[s].index;break}}else{var w=Math.min(f,d),x=Math.max(f,d);if(t>(w+l)/2&&t<=(x+l)/2){o=i[s].index;break}}}else for(var A=0;A<u;A++)if(A===0&&t<=(n[A].coordinate+n[A+1].coordinate)/2||A>0&&A<u-1&&t>(n[A].coordinate+n[A-1].coordinate)/2&&t<=(n[A].coordinate+n[A+1].coordinate)/2||A===u-1&&t>(n[A].coordinate+n[A-1].coordinate)/2){o=n[A].index;break}return o},ws=function(t){var r,n=t,i=n.type.displayName,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?ve(ve({},t.type.defaultProps),t.props):t.props,o=a.stroke,u=a.fill,c;switch(i){case"Line":c=o;break;case"Area":case"Radar":c=o&&o!=="none"?o:u;break;default:c=u;break}return c},ik=function(t){var r=t.barSize,n=t.totalSize,i=t.stackGroups,a=i===void 0?{}:i;if(!a)return{};for(var o={},u=Object.keys(a),c=0,s=u.length;c<s;c++)for(var f=a[u[c]].stackGroups,l=Object.keys(f),d=0,p=l.length;d<p;d++){var y=f[l[d]],h=y.items,v=y.cateAxisId,b=h.filter(function(O){return gt(O.type).indexOf("Bar")>=0});if(b&&b.length){var w=b[0].type.defaultProps,x=w!==void 0?ve(ve({},w),b[0].props):b[0].props,A=x.barSize,g=x[v];o[g]||(o[g]=[]);var m=Q(A)?r:A;o[g].push({item:b[0],stackList:b.slice(1),barSize:Q(m)?void 0:ke(m,n,0)})}}return o},ak=function(t){var r=t.barGap,n=t.barCategoryGap,i=t.bandSize,a=t.sizeList,o=a===void 0?[]:a,u=t.maxBarSize,c=o.length;if(c<1)return null;var s=ke(r,i,0,!0),f,l=[];if(o[0].barSize===+o[0].barSize){var d=!1,p=i/c,y=o.reduce(function(A,g){return A+g.barSize||0},0);y+=(c-1)*s,y>=i&&(y-=(c-1)*s,s=0),y>=i&&p>0&&(d=!0,p*=.9,y=c*p);var h=(i-y)/2>>0,v={offset:h-s,size:0};f=o.reduce(function(A,g){var m={item:g.item,position:{offset:v.offset+v.size+s,size:d?p:g.barSize}},O=[].concat(Zf(A),[m]);return v=O[O.length-1].position,g.stackList&&g.stackList.length&&g.stackList.forEach(function(S){O.push({item:S,position:v})}),O},l)}else{var b=ke(n,i,0,!0);i-2*b-(c-1)*s<=0&&(s=0);var w=(i-2*b-(c-1)*s)/c;w>1&&(w>>=0);var x=u===+u?Math.min(w,u):w;f=o.reduce(function(A,g,m){var O=[].concat(Zf(A),[{item:g.item,position:{offset:b+(w+s)*m+(w-x)/2,size:x}}]);return g.stackList&&g.stackList.length&&g.stackList.forEach(function(S){O.push({item:S,position:O[O.length-1].position})}),O},l)}return f},ok=function(t,r,n,i){var a=n.children,o=n.width,u=n.margin,c=o-(u.left||0)-(u.right||0),s=Vy({children:a,legendWidth:c});if(s){var f=i||{},l=f.width,d=f.height,p=s.align,y=s.verticalAlign,h=s.layout;if((h==="vertical"||h==="horizontal"&&y==="middle")&&p!=="center"&&R(t[p]))return ve(ve({},t),{},Or({},p,t[p]+(l||0)));if((h==="horizontal"||h==="vertical"&&p==="center")&&y!=="middle"&&R(t[y]))return ve(ve({},t),{},Or({},y,t[y]+(d||0)))}return t},uk=function(t,r,n){return Q(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},Yy=function(t,r,n,i,a){var o=r.props.children,u=Ve(o,so).filter(function(s){return uk(i,a,s.props.direction)});if(u&&u.length){var c=u.map(function(s){return s.props.dataKey});return t.reduce(function(s,f){var l=Me(f,n);if(Q(l))return s;var d=Array.isArray(l)?[ao(l),io(l)]:[l,l],p=c.reduce(function(y,h){var v=Me(f,h,0),b=d[0]-Math.abs(Array.isArray(v)?v[0]:v),w=d[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(b,y[0]),Math.max(w,y[1])]},[1/0,-1/0]);return[Math.min(p[0],s[0]),Math.max(p[1],s[1])]},[1/0,-1/0])}return null},ck=function(t,r,n,i,a){var o=r.map(function(u){return Yy(t,u,n,a,i)}).filter(function(u){return!Q(u)});return o&&o.length?o.reduce(function(u,c){return[Math.min(u[0],c[0]),Math.max(u[1],c[1])]},[1/0,-1/0]):null},Zy=function(t,r,n,i,a){var o=r.map(function(c){var s=c.props.dataKey;return n==="number"&&s&&Yy(t,c,s,i)||xn(t,s,n,a)});if(n==="number")return o.reduce(function(c,s){return[Math.min(c[0],s[0]),Math.max(c[1],s[1])]},[1/0,-1/0]);var u={};return o.reduce(function(c,s){for(var f=0,l=s.length;f<l;f++)u[s[f]]||(u[s[f]]=!0,c.push(s[f]));return c},[])},Jy=function(t,r){return t==="horizontal"&&r==="xAxis"||t==="vertical"&&r==="yAxis"||t==="centric"&&r==="angleAxis"||t==="radial"&&r==="radiusAxis"},Qy=function(t,r,n,i){if(i)return t.map(function(c){return c.coordinate});var a,o,u=t.map(function(c){return c.coordinate===r&&(a=!0),c.coordinate===n&&(o=!0),c.coordinate});return a||u.push(r),o||u.push(n),u},vt=function(t,r,n){if(!t)return null;var i=t.scale,a=t.duplicateDomain,o=t.type,u=t.range,c=t.realScaleType==="scaleBand"?i.bandwidth()/2:2,s=(r||n)&&o==="category"&&i.bandwidth?i.bandwidth()/c:0;if(s=t.axisType==="angleAxis"&&(u==null?void 0:u.length)>=2?Ie(u[0]-u[1])*2*s:s,r&&(t.ticks||t.niceTicks)){var f=(t.ticks||t.niceTicks).map(function(l){var d=a?a.indexOf(l):l;return{coordinate:i(d)+s,value:l,offset:s}});return f.filter(function(l){return!ui(l.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(l,d){return{coordinate:i(l)+s,value:l,index:d,offset:s}}):i.ticks&&!n?i.ticks(t.tickCount).map(function(l){return{coordinate:i(l)+s,value:l,offset:s}}):i.domain().map(function(l,d){return{coordinate:i(l)+s,value:a?a[l]:l,index:d,offset:s}})},qo=new WeakMap,Pi=function(t,r){if(typeof r!="function")return t;qo.has(t)||qo.set(t,new WeakMap);var n=qo.get(t);if(n.has(r))return n.get(r);var i=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},ev=function(t,r,n){var i=t.scale,a=t.type,o=t.layout,u=t.axisType;if(i==="auto")return o==="radial"&&u==="radiusAxis"?{scale:Mn(),realScaleType:"band"}:o==="radial"&&u==="angleAxis"?{scale:Zi(),realScaleType:"linear"}:a==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:bn(),realScaleType:"point"}:a==="category"?{scale:Mn(),realScaleType:"band"}:{scale:Zi(),realScaleType:"linear"};if(oi(i)){var c="scale".concat(qa(i));return{scale:(Hf[c]||bn)(),realScaleType:Hf[c]?c:"point"}}return V(i)?{scale:i}:{scale:bn(),realScaleType:"point"}},Qf=1e-4,tv=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,i=t.range(),a=Math.min(i[0],i[1])-Qf,o=Math.max(i[0],i[1])+Qf,u=t(r[0]),c=t(r[n-1]);(u<a||u>o||c<a||c>o)&&t.domain([r[0],r[n-1]])}},sk=function(t,r){if(!t)return null;for(var n=0,i=t.length;n<i;n++)if(t[n].item===r)return t[n].position;return null},lk=function(t,r){if(!r||r.length!==2||!R(r[0])||!R(r[1]))return t;var n=Math.min(r[0],r[1]),i=Math.max(r[0],r[1]),a=[t[0],t[1]];return(!R(t[0])||t[0]<n)&&(a[0]=n),(!R(t[1])||t[1]>i)&&(a[1]=i),a[0]>i&&(a[0]=i),a[1]<n&&(a[1]=n),a},fk=function(t){var r=t.length;if(!(r<=0))for(var n=0,i=t[0].length;n<i;++n)for(var a=0,o=0,u=0;u<r;++u){var c=ui(t[u][n][1])?t[u][n][0]:t[u][n][1];c>=0?(t[u][n][0]=a,t[u][n][1]=a+c,a=t[u][n][1]):(t[u][n][0]=o,t[u][n][1]=o+c,o=t[u][n][1])}},dk=function(t){var r=t.length;if(!(r<=0))for(var n=0,i=t[0].length;n<i;++n)for(var a=0,o=0;o<r;++o){var u=ui(t[o][n][1])?t[o][n][0]:t[o][n][1];u>=0?(t[o][n][0]=a,t[o][n][1]=a+u,a=t[o][n][1]):(t[o][n][0]=0,t[o][n][1]=0)}},pk={sign:fk,expand:Iw,none:Ar,silhouette:kw,wiggle:Nw,positive:dk},hk=function(t,r,n){var i=r.map(function(u){return u.props.dataKey}),a=pk[n],o=Cw().keys(i).value(function(u,c){return+Me(u,c,0)}).order(su).offset(a);return o(t)},yk=function(t,r,n,i,a,o){if(!t)return null;var u=o?r.reverse():r,c={},s=u.reduce(function(l,d){var p,y=(p=d.type)!==null&&p!==void 0&&p.defaultProps?ve(ve({},d.type.defaultProps),d.props):d.props,h=y.stackId,v=y.hide;if(v)return l;var b=y[n],w=l[b]||{hasStack:!1,stackGroups:{}};if(Ae(h)){var x=w.stackGroups[h]||{numericAxisId:n,cateAxisId:i,items:[]};x.items.push(d),w.hasStack=!0,w.stackGroups[h]=x}else w.stackGroups[ci("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[d]};return ve(ve({},l),{},Or({},b,w))},c),f={};return Object.keys(s).reduce(function(l,d){var p=s[d];if(p.hasStack){var y={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(h,v){var b=p.stackGroups[v];return ve(ve({},h),{},Or({},v,{numericAxisId:n,cateAxisId:i,items:b.items,stackedData:hk(t,b.items,a)}))},y)}return ve(ve({},l),{},Or({},d,p))},f)},rv=function(t,r){var n=r.realScaleType,i=r.type,a=r.tickCount,o=r.originalDomain,u=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(a&&i==="number"&&o&&(o[0]==="auto"||o[1]==="auto")){var s=t.domain();if(!s.length)return null;var f=EI(s,a,u);return t.domain([ao(f),io(f)]),{niceTicks:f}}if(a&&i==="number"){var l=t.domain(),d=jI(l,a,u);return{niceTicks:d}}return null},ed=function(t){var r=t.axis,n=t.ticks,i=t.offset,a=t.bandSize,o=t.entry,u=t.index;if(r.type==="category")return n[u]?n[u].coordinate+i:null;var c=Me(o,r.dataKey,r.domain[u]);return Q(c)?null:r.scale(c)-a/2+i},vk=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return i<=0&&a>=0?0:a<0?a:i}return n[0]},gk=function(t,r){var n,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?ve(ve({},t.type.defaultProps),t.props):t.props,a=i.stackId;if(Ae(a)){var o=r[a];if(o){var u=o.items.indexOf(t);return u>=0?o.stackedData[u]:null}}return null},mk=function(t){return t.reduce(function(r,n){return[ao(n.concat([r[0]]).filter(R)),io(n.concat([r[1]]).filter(R))]},[1/0,-1/0])},nv=function(t,r,n){return Object.keys(t).reduce(function(i,a){var o=t[a],u=o.stackedData,c=u.reduce(function(s,f){var l=mk(f.slice(r,n+1));return[Math.min(s[0],l[0]),Math.max(s[1],l[1])]},[1/0,-1/0]);return[Math.min(c[0],i[0]),Math.max(c[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},td=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,rd=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Bu=function(t,r,n){if(V(t))return t(r,n);if(!Array.isArray(t))return r;var i=[];if(R(t[0]))i[0]=n?t[0]:Math.min(t[0],r[0]);else if(td.test(t[0])){var a=+td.exec(t[0])[1];i[0]=r[0]-a}else V(t[0])?i[0]=t[0](r[0]):i[0]=r[0];if(R(t[1]))i[1]=n?t[1]:Math.max(t[1],r[1]);else if(rd.test(t[1])){var o=+rd.exec(t[1])[1];i[1]=r[1]+o}else V(t[1])?i[1]=t[1](r[1]):i[1]=r[1];return i},ia=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var i=t.scale.bandwidth();if(!n||i>0)return i}if(t&&r&&r.length>=2){for(var a=Xc(r,function(l){return l.coordinate}),o=1/0,u=1,c=a.length;u<c;u++){var s=a[u],f=a[u-1];o=Math.min((s.coordinate||0)-(f.coordinate||0),o)}return o===1/0?0:o}return n?void 0:0},nd=function(t,r,n){return!t||!t.length||oo(t,qe(n,"type.defaultProps.domain"))?r:t},iv=function(t,r){var n=t.type.defaultProps?ve(ve({},t.type.defaultProps),t.props):t.props,i=n.dataKey,a=n.name,o=n.unit,u=n.formatter,c=n.tooltipType,s=n.chartType,f=n.hide;return ve(ve({},X(t,!1)),{},{dataKey:i,unit:o,formatter:u,name:a||i,color:ws(t),value:Me(r,i),type:c,payload:r,chartType:s,hide:f})};function Fn(e){"@babel/helpers - typeof";return Fn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fn(e)}function id(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function pt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?id(Object(r),!0).forEach(function(n){av(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):id(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function av(e,t,r){return t=bk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function bk(e){var t=xk(e,"string");return Fn(t)=="symbol"?t:t+""}function xk(e,t){if(Fn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Fn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function wk(e,t){return Sk(e)||Pk(e,t)||Ak(e,t)||Ok()}function Ok(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ak(e,t){if(e){if(typeof e=="string")return ad(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ad(e,t)}}function ad(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Pk(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function Sk(e){if(Array.isArray(e))return e}var aa=Math.PI/180,_k=function(t){return t*180/Math.PI},le=function(t,r,n,i){return{x:t+Math.cos(-aa*i)*n,y:r+Math.sin(-aa*i)*n}},ov=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},$k=function(t,r,n,i,a){var o=t.width,u=t.height,c=t.startAngle,s=t.endAngle,f=ke(t.cx,o,o/2),l=ke(t.cy,u,u/2),d=ov(o,u,n),p=ke(t.innerRadius,d,0),y=ke(t.outerRadius,d,d*.8),h=Object.keys(r);return h.reduce(function(v,b){var w=r[b],x=w.domain,A=w.reversed,g;if(Q(w.range))i==="angleAxis"?g=[c,s]:i==="radiusAxis"&&(g=[p,y]),A&&(g=[g[1],g[0]]);else{g=w.range;var m=g,O=wk(m,2);c=O[0],s=O[1]}var S=ev(w,a),_=S.realScaleType,E=S.scale;E.domain(x).range(g),tv(E);var $=rv(E,pt(pt({},w),{},{realScaleType:_})),T=pt(pt(pt({},w),$),{},{range:g,radius:y,realScaleType:_,scale:E,cx:f,cy:l,innerRadius:p,outerRadius:y,startAngle:c,endAngle:s});return pt(pt({},v),{},av({},b,T))},{})},Tk=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return Math.sqrt(Math.pow(n-a,2)+Math.pow(i-o,2))},Ek=function(t,r){var n=t.x,i=t.y,a=r.cx,o=r.cy,u=Tk({x:n,y:i},{x:a,y:o});if(u<=0)return{radius:u};var c=(n-a)/u,s=Math.acos(c);return i>o&&(s=2*Math.PI-s),{radius:u,angle:_k(s),angleInRadian:s}},jk=function(t){var r=t.startAngle,n=t.endAngle,i=Math.floor(r/360),a=Math.floor(n/360),o=Math.min(i,a);return{startAngle:r-o*360,endAngle:n-o*360}},Mk=function(t,r){var n=r.startAngle,i=r.endAngle,a=Math.floor(n/360),o=Math.floor(i/360),u=Math.min(a,o);return t+u*360},od=function(t,r){var n=t.x,i=t.y,a=Ek({x:n,y:i},r),o=a.radius,u=a.angle,c=r.innerRadius,s=r.outerRadius;if(o<c||o>s)return!1;if(o===0)return!0;var f=jk(r),l=f.startAngle,d=f.endAngle,p=u,y;if(l<=d){for(;p>d;)p-=360;for(;p<l;)p+=360;y=p>=l&&p<=d}else{for(;p>l;)p-=360;for(;p<d;)p+=360;y=p>=d&&p<=l}return y?pt(pt({},r),{},{radius:o,angle:Mk(p,r)}):null},uv=function(t){return!L.isValidElement(t)&&!V(t)&&typeof t!="boolean"?t.className:""};function Wn(e){"@babel/helpers - typeof";return Wn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wn(e)}var Ck=["offset"];function Ik(e){return Rk(e)||Dk(e)||Nk(e)||kk()}function kk(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Nk(e,t){if(e){if(typeof e=="string")return Fu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Fu(e,t)}}function Dk(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Rk(e){if(Array.isArray(e))return Fu(e)}function Fu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Lk(e,t){if(e==null)return{};var r=Bk(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Bk(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function ud(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Oe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ud(Object(r),!0).forEach(function(n){Fk(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ud(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Fk(e,t,r){return t=Wk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Wk(e){var t=zk(e,"string");return Wn(t)=="symbol"?t:t+""}function zk(e,t){if(Wn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Wn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zn(){return zn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zn.apply(this,arguments)}var Uk=function(t){var r=t.value,n=t.formatter,i=Q(t.children)?r:t.children;return V(n)?n(i):i},qk=function(t,r){var n=Ie(r-t),i=Math.min(Math.abs(r-t),360);return n*i},Hk=function(t,r,n){var i=t.position,a=t.viewBox,o=t.offset,u=t.className,c=a,s=c.cx,f=c.cy,l=c.innerRadius,d=c.outerRadius,p=c.startAngle,y=c.endAngle,h=c.clockWise,v=(l+d)/2,b=qk(p,y),w=b>=0?1:-1,x,A;i==="insideStart"?(x=p+w*o,A=h):i==="insideEnd"?(x=y-w*o,A=!h):i==="end"&&(x=y+w*o,A=h),A=b<=0?A:!A;var g=le(s,f,v,x),m=le(s,f,v,x+(A?1:-1)*359),O="M".concat(g.x,",").concat(g.y,` + A`).concat(v,",").concat(v,",0,1,").concat(A?0:1,`, + `).concat(m.x,",").concat(m.y),S=Q(t.id)?ci("recharts-radial-line-"):t.id;return P.createElement("text",zn({},n,{dominantBaseline:"central",className:J("recharts-radial-bar-label",u)}),P.createElement("defs",null,P.createElement("path",{id:S,d:O})),P.createElement("textPath",{xlinkHref:"#".concat(S)},r))},Gk=function(t){var r=t.viewBox,n=t.offset,i=t.position,a=r,o=a.cx,u=a.cy,c=a.innerRadius,s=a.outerRadius,f=a.startAngle,l=a.endAngle,d=(f+l)/2;if(i==="outside"){var p=le(o,u,s+n,d),y=p.x,h=p.y;return{x:y,y:h,textAnchor:y>=o?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"end"};var v=(c+s)/2,b=le(o,u,v,d),w=b.x,x=b.y;return{x:w,y:x,textAnchor:"middle",verticalAnchor:"middle"}},Kk=function(t){var r=t.viewBox,n=t.parentViewBox,i=t.offset,a=t.position,o=r,u=o.x,c=o.y,s=o.width,f=o.height,l=f>=0?1:-1,d=l*i,p=l>0?"end":"start",y=l>0?"start":"end",h=s>=0?1:-1,v=h*i,b=h>0?"end":"start",w=h>0?"start":"end";if(a==="top"){var x={x:u+s/2,y:c-l*i,textAnchor:"middle",verticalAnchor:p};return Oe(Oe({},x),n?{height:Math.max(c-n.y,0),width:s}:{})}if(a==="bottom"){var A={x:u+s/2,y:c+f+d,textAnchor:"middle",verticalAnchor:y};return Oe(Oe({},A),n?{height:Math.max(n.y+n.height-(c+f),0),width:s}:{})}if(a==="left"){var g={x:u-v,y:c+f/2,textAnchor:b,verticalAnchor:"middle"};return Oe(Oe({},g),n?{width:Math.max(g.x-n.x,0),height:f}:{})}if(a==="right"){var m={x:u+s+v,y:c+f/2,textAnchor:w,verticalAnchor:"middle"};return Oe(Oe({},m),n?{width:Math.max(n.x+n.width-m.x,0),height:f}:{})}var O=n?{width:s,height:f}:{};return a==="insideLeft"?Oe({x:u+v,y:c+f/2,textAnchor:w,verticalAnchor:"middle"},O):a==="insideRight"?Oe({x:u+s-v,y:c+f/2,textAnchor:b,verticalAnchor:"middle"},O):a==="insideTop"?Oe({x:u+s/2,y:c+d,textAnchor:"middle",verticalAnchor:y},O):a==="insideBottom"?Oe({x:u+s/2,y:c+f-d,textAnchor:"middle",verticalAnchor:p},O):a==="insideTopLeft"?Oe({x:u+v,y:c+d,textAnchor:w,verticalAnchor:y},O):a==="insideTopRight"?Oe({x:u+s-v,y:c+d,textAnchor:b,verticalAnchor:y},O):a==="insideBottomLeft"?Oe({x:u+v,y:c+f-d,textAnchor:w,verticalAnchor:p},O):a==="insideBottomRight"?Oe({x:u+s-v,y:c+f-d,textAnchor:b,verticalAnchor:p},O):Xr(a)&&(R(a.x)||Vt(a.x))&&(R(a.y)||Vt(a.y))?Oe({x:u+ke(a.x,s),y:c+ke(a.y,f),textAnchor:"end",verticalAnchor:"end"},O):Oe({x:u+s/2,y:c+f/2,textAnchor:"middle",verticalAnchor:"middle"},O)},Xk=function(t){return"cx"in t&&R(t.cx)};function _e(e){var t=e.offset,r=t===void 0?5:t,n=Lk(e,Ck),i=Oe({offset:r},n),a=i.viewBox,o=i.position,u=i.value,c=i.children,s=i.content,f=i.className,l=f===void 0?"":f,d=i.textBreakAll;if(!a||Q(u)&&Q(c)&&!L.isValidElement(s)&&!V(s))return null;if(L.isValidElement(s))return L.cloneElement(s,i);var p;if(V(s)){if(p=L.createElement(s,i),L.isValidElement(p))return p}else p=Uk(i);var y=Xk(a),h=X(i,!0);if(y&&(o==="insideStart"||o==="insideEnd"||o==="end"))return Hk(i,p,h);var v=y?Gk(i):Kk(i);return P.createElement(rr,zn({className:J("recharts-label",l)},h,v,{breakAll:d}),p)}_e.displayName="Label";var cv=function(t){var r=t.cx,n=t.cy,i=t.angle,a=t.startAngle,o=t.endAngle,u=t.r,c=t.radius,s=t.innerRadius,f=t.outerRadius,l=t.x,d=t.y,p=t.top,y=t.left,h=t.width,v=t.height,b=t.clockWise,w=t.labelViewBox;if(w)return w;if(R(h)&&R(v)){if(R(l)&&R(d))return{x:l,y:d,width:h,height:v};if(R(p)&&R(y))return{x:p,y,width:h,height:v}}return R(l)&&R(d)?{x:l,y:d,width:0,height:0}:R(r)&&R(n)?{cx:r,cy:n,startAngle:a||i||0,endAngle:o||i||0,innerRadius:s||0,outerRadius:f||c||u||0,clockWise:b}:t.viewBox?t.viewBox:{}},Vk=function(t,r){return t?t===!0?P.createElement(_e,{key:"label-implicit",viewBox:r}):Ae(t)?P.createElement(_e,{key:"label-implicit",viewBox:r,value:t}):L.isValidElement(t)?t.type===_e?L.cloneElement(t,{key:"label-implicit",viewBox:r}):P.createElement(_e,{key:"label-implicit",content:t,viewBox:r}):V(t)?P.createElement(_e,{key:"label-implicit",content:t,viewBox:r}):Xr(t)?P.createElement(_e,zn({viewBox:r},t,{key:"label-implicit"})):null:null},Yk=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var i=t.children,a=cv(t),o=Ve(i,_e).map(function(c,s){return L.cloneElement(c,{viewBox:r||a,key:"label-".concat(s)})});if(!n)return o;var u=Vk(t.label,r||a);return[u].concat(Ik(o))};_e.parseViewBox=cv;_e.renderCallByParent=Yk;function Zk(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}var Jk=Zk;const Qk=ie(Jk);function Un(e){"@babel/helpers - typeof";return Un=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Un(e)}var e2=["valueAccessor"],t2=["data","dataKey","clockWise","id","textBreakAll"];function r2(e){return o2(e)||a2(e)||i2(e)||n2()}function n2(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function i2(e,t){if(e){if(typeof e=="string")return Wu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Wu(e,t)}}function a2(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function o2(e){if(Array.isArray(e))return Wu(e)}function Wu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function oa(){return oa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},oa.apply(this,arguments)}function cd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function sd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?cd(Object(r),!0).forEach(function(n){u2(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):cd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function u2(e,t,r){return t=c2(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function c2(e){var t=s2(e,"string");return Un(t)=="symbol"?t:t+""}function s2(e,t){if(Un(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Un(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ld(e,t){if(e==null)return{};var r=l2(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function l2(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var f2=function(t){return Array.isArray(t.value)?Qk(t.value):t.value};function It(e){var t=e.valueAccessor,r=t===void 0?f2:t,n=ld(e,e2),i=n.data,a=n.dataKey,o=n.clockWise,u=n.id,c=n.textBreakAll,s=ld(n,t2);return!i||!i.length?null:P.createElement(ne,{className:"recharts-label-list"},i.map(function(f,l){var d=Q(a)?r(f,l):Me(f&&f.payload,a),p=Q(u)?{}:{id:"".concat(u,"-").concat(l)};return P.createElement(_e,oa({},X(f,!0),s,p,{parentViewBox:f.parentViewBox,value:d,textBreakAll:c,viewBox:_e.parseViewBox(Q(o)?f:sd(sd({},f),{},{clockWise:o})),key:"label-".concat(l),index:l}))}))}It.displayName="LabelList";function d2(e,t){return e?e===!0?P.createElement(It,{key:"labelList-implicit",data:t}):P.isValidElement(e)||V(e)?P.createElement(It,{key:"labelList-implicit",data:t,content:e}):Xr(e)?P.createElement(It,oa({data:t},e,{key:"labelList-implicit"})):null:null}function p2(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&r&&!e.label)return null;var n=e.children,i=Ve(n,It).map(function(o,u){return L.cloneElement(o,{data:t,key:"labelList-".concat(u)})});if(!r)return i;var a=d2(e.label,t);return[a].concat(r2(i))}It.renderCallByParent=p2;function qn(e){"@babel/helpers - typeof";return qn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qn(e)}function zu(){return zu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zu.apply(this,arguments)}function fd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function dd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fd(Object(r),!0).forEach(function(n){h2(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function h2(e,t,r){return t=y2(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function y2(e){var t=v2(e,"string");return qn(t)=="symbol"?t:t+""}function v2(e,t){if(qn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(qn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var g2=function(t,r){var n=Ie(r-t),i=Math.min(Math.abs(r-t),359.999);return n*i},Si=function(t){var r=t.cx,n=t.cy,i=t.radius,a=t.angle,o=t.sign,u=t.isExternal,c=t.cornerRadius,s=t.cornerIsExternal,f=c*(u?1:-1)+i,l=Math.asin(c/f)/aa,d=s?a:a+o*l,p=le(r,n,f,d),y=le(r,n,i,d),h=s?a-o*l:a,v=le(r,n,f*Math.cos(l*aa),h);return{center:p,circleTangency:y,lineTangency:v,theta:l}},sv=function(t){var r=t.cx,n=t.cy,i=t.innerRadius,a=t.outerRadius,o=t.startAngle,u=t.endAngle,c=g2(o,u),s=o+c,f=le(r,n,a,o),l=le(r,n,a,s),d="M ".concat(f.x,",").concat(f.y,` + A `).concat(a,",").concat(a,`,0, + `).concat(+(Math.abs(c)>180),",").concat(+(o>s),`, + `).concat(l.x,",").concat(l.y,` + `);if(i>0){var p=le(r,n,i,o),y=le(r,n,i,s);d+="L ".concat(y.x,",").concat(y.y,` + A `).concat(i,",").concat(i,`,0, + `).concat(+(Math.abs(c)>180),",").concat(+(o<=s),`, + `).concat(p.x,",").concat(p.y," Z")}else d+="L ".concat(r,",").concat(n," Z");return d},m2=function(t){var r=t.cx,n=t.cy,i=t.innerRadius,a=t.outerRadius,o=t.cornerRadius,u=t.forceCornerRadius,c=t.cornerIsExternal,s=t.startAngle,f=t.endAngle,l=Ie(f-s),d=Si({cx:r,cy:n,radius:a,angle:s,sign:l,cornerRadius:o,cornerIsExternal:c}),p=d.circleTangency,y=d.lineTangency,h=d.theta,v=Si({cx:r,cy:n,radius:a,angle:f,sign:-l,cornerRadius:o,cornerIsExternal:c}),b=v.circleTangency,w=v.lineTangency,x=v.theta,A=c?Math.abs(s-f):Math.abs(s-f)-h-x;if(A<0)return u?"M ".concat(y.x,",").concat(y.y,` + a`).concat(o,",").concat(o,",0,0,1,").concat(o*2,`,0 + a`).concat(o,",").concat(o,",0,0,1,").concat(-o*2,`,0 + `):sv({cx:r,cy:n,innerRadius:i,outerRadius:a,startAngle:s,endAngle:f});var g="M ".concat(y.x,",").concat(y.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(p.x,",").concat(p.y,` + A`).concat(a,",").concat(a,",0,").concat(+(A>180),",").concat(+(l<0),",").concat(b.x,",").concat(b.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(w.x,",").concat(w.y,` + `);if(i>0){var m=Si({cx:r,cy:n,radius:i,angle:s,sign:l,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),O=m.circleTangency,S=m.lineTangency,_=m.theta,E=Si({cx:r,cy:n,radius:i,angle:f,sign:-l,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),$=E.circleTangency,T=E.lineTangency,C=E.theta,I=c?Math.abs(s-f):Math.abs(s-f)-_-C;if(I<0&&o===0)return"".concat(g,"L").concat(r,",").concat(n,"Z");g+="L".concat(T.x,",").concat(T.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat($.x,",").concat($.y,` + A`).concat(i,",").concat(i,",0,").concat(+(I>180),",").concat(+(l>0),",").concat(O.x,",").concat(O.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(S.x,",").concat(S.y,"Z")}else g+="L".concat(r,",").concat(n,"Z");return g},b2={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},lv=function(t){var r=dd(dd({},b2),t),n=r.cx,i=r.cy,a=r.innerRadius,o=r.outerRadius,u=r.cornerRadius,c=r.forceCornerRadius,s=r.cornerIsExternal,f=r.startAngle,l=r.endAngle,d=r.className;if(o<a||f===l)return null;var p=J("recharts-sector",d),y=o-a,h=ke(u,y,0,!0),v;return h>0&&Math.abs(f-l)<360?v=m2({cx:n,cy:i,innerRadius:a,outerRadius:o,cornerRadius:Math.min(h,y/2),forceCornerRadius:c,cornerIsExternal:s,startAngle:f,endAngle:l}):v=sv({cx:n,cy:i,innerRadius:a,outerRadius:o,startAngle:f,endAngle:l}),P.createElement("path",zu({},X(r,!0),{className:p,d:v,role:"img"}))};function Hn(e){"@babel/helpers - typeof";return Hn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hn(e)}function Uu(){return Uu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Uu.apply(this,arguments)}function pd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function hd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pd(Object(r),!0).forEach(function(n){x2(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function x2(e,t,r){return t=w2(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function w2(e){var t=O2(e,"string");return Hn(t)=="symbol"?t:t+""}function O2(e,t){if(Hn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Hn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var yd={curveBasisClosed:ww,curveBasisOpen:Ow,curveBasis:xw,curveBumpX:ow,curveBumpY:uw,curveLinearClosed:Aw,curveLinear:Ga,curveMonotoneX:Pw,curveMonotoneY:Sw,curveNatural:_w,curveStep:$w,curveStepAfter:Ew,curveStepBefore:Tw},_i=function(t){return t.x===+t.x&&t.y===+t.y},pn=function(t){return t.x},hn=function(t){return t.y},A2=function(t,r){if(V(t))return t;var n="curve".concat(qa(t));return(n==="curveMonotone"||n==="curveBump")&&r?yd["".concat(n).concat(r==="vertical"?"Y":"X")]:yd[n]||Ga},P2=function(t){var r=t.type,n=r===void 0?"linear":r,i=t.points,a=i===void 0?[]:i,o=t.baseLine,u=t.layout,c=t.connectNulls,s=c===void 0?!1:c,f=A2(n,u),l=s?a.filter(function(h){return _i(h)}):a,d;if(Array.isArray(o)){var p=s?o.filter(function(h){return _i(h)}):o,y=l.map(function(h,v){return hd(hd({},h),{},{base:p[v]})});return u==="vertical"?d=vi().y(hn).x1(pn).x0(function(h){return h.base.x}):d=vi().x(pn).y1(hn).y0(function(h){return h.base.y}),d.defined(_i).curve(f),d(y)}return u==="vertical"&&R(o)?d=vi().y(hn).x1(pn).x0(o):R(o)?d=vi().x(pn).y1(hn).y0(o):d=nh().x(pn).y(hn),d.defined(_i).curve(f),d(l)},qu=function(t){var r=t.className,n=t.points,i=t.path,a=t.pathRef;if((!n||!n.length)&&!i)return null;var o=n&&n.length?P2(t):i;return P.createElement("path",Uu({},X(t,!1),Mi(t),{className:J("recharts-curve",r),d:o,ref:a}))},fv={exports:{}},S2="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",_2=S2,$2=_2;function dv(){}function pv(){}pv.resetWarningCache=dv;var T2=function(){function e(n,i,a,o,u,c){if(c!==$2){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}e.isRequired=e;function t(){return e}var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:pv,resetWarningCache:dv};return r.PropTypes=r,r};fv.exports=T2();var E2=fv.exports;const re=ie(E2);var j2=Object.getOwnPropertyNames,M2=Object.getOwnPropertySymbols,C2=Object.prototype.hasOwnProperty;function vd(e,t){return function(n,i,a){return e(n,i,a)&&t(n,i,a)}}function $i(e){return function(r,n,i){if(!r||!n||typeof r!="object"||typeof n!="object")return e(r,n,i);var a=i.cache,o=a.get(r),u=a.get(n);if(o&&u)return o===n&&u===r;a.set(r,n),a.set(n,r);var c=e(r,n,i);return a.delete(r),a.delete(n),c}}function gd(e){return j2(e).concat(M2(e))}var I2=Object.hasOwn||function(e,t){return C2.call(e,t)};function sr(e,t){return e===t||!e&&!t&&e!==e&&t!==t}var k2="__v",N2="__o",D2="_owner",md=Object.getOwnPropertyDescriptor,bd=Object.keys;function R2(e,t,r){var n=e.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(e[n],t[n],n,n,e,t,r))return!1;return!0}function L2(e,t){return sr(e.getTime(),t.getTime())}function B2(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function F2(e,t){return e===t}function xd(e,t,r){var n=e.size;if(n!==t.size)return!1;if(!n)return!0;for(var i=new Array(n),a=e.entries(),o,u,c=0;(o=a.next())&&!o.done;){for(var s=t.entries(),f=!1,l=0;(u=s.next())&&!u.done;){if(i[l]){l++;continue}var d=o.value,p=u.value;if(r.equals(d[0],p[0],c,l,e,t,r)&&r.equals(d[1],p[1],d[0],p[0],e,t,r)){f=i[l]=!0;break}l++}if(!f)return!1;c++}return!0}var W2=sr;function z2(e,t,r){var n=bd(e),i=n.length;if(bd(t).length!==i)return!1;for(;i-- >0;)if(!hv(e,t,r,n[i]))return!1;return!0}function yn(e,t,r){var n=gd(e),i=n.length;if(gd(t).length!==i)return!1;for(var a,o,u;i-- >0;)if(a=n[i],!hv(e,t,r,a)||(o=md(e,a),u=md(t,a),(o||u)&&(!o||!u||o.configurable!==u.configurable||o.enumerable!==u.enumerable||o.writable!==u.writable)))return!1;return!0}function U2(e,t){return sr(e.valueOf(),t.valueOf())}function q2(e,t){return e.source===t.source&&e.flags===t.flags}function wd(e,t,r){var n=e.size;if(n!==t.size)return!1;if(!n)return!0;for(var i=new Array(n),a=e.values(),o,u;(o=a.next())&&!o.done;){for(var c=t.values(),s=!1,f=0;(u=c.next())&&!u.done;){if(!i[f]&&r.equals(o.value,u.value,o.value,u.value,e,t,r)){s=i[f]=!0;break}f++}if(!s)return!1}return!0}function H2(e,t){var r=e.length;if(t.length!==r)return!1;for(;r-- >0;)if(e[r]!==t[r])return!1;return!0}function G2(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function hv(e,t,r,n){return(n===D2||n===N2||n===k2)&&(e.$$typeof||t.$$typeof)?!0:I2(t,n)&&r.equals(e[n],t[n],n,n,e,t,r)}var K2="[object Arguments]",X2="[object Boolean]",V2="[object Date]",Y2="[object Error]",Z2="[object Map]",J2="[object Number]",Q2="[object Object]",eN="[object RegExp]",tN="[object Set]",rN="[object String]",nN="[object URL]",iN=Array.isArray,Od=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,Ad=Object.assign,aN=Object.prototype.toString.call.bind(Object.prototype.toString);function oN(e){var t=e.areArraysEqual,r=e.areDatesEqual,n=e.areErrorsEqual,i=e.areFunctionsEqual,a=e.areMapsEqual,o=e.areNumbersEqual,u=e.areObjectsEqual,c=e.arePrimitiveWrappersEqual,s=e.areRegExpsEqual,f=e.areSetsEqual,l=e.areTypedArraysEqual,d=e.areUrlsEqual;return function(y,h,v){if(y===h)return!0;if(y==null||h==null)return!1;var b=typeof y;if(b!==typeof h)return!1;if(b!=="object")return b==="number"?o(y,h,v):b==="function"?i(y,h,v):!1;var w=y.constructor;if(w!==h.constructor)return!1;if(w===Object)return u(y,h,v);if(iN(y))return t(y,h,v);if(Od!=null&&Od(y))return l(y,h,v);if(w===Date)return r(y,h,v);if(w===RegExp)return s(y,h,v);if(w===Map)return a(y,h,v);if(w===Set)return f(y,h,v);var x=aN(y);return x===V2?r(y,h,v):x===eN?s(y,h,v):x===Z2?a(y,h,v):x===tN?f(y,h,v):x===Q2?typeof y.then!="function"&&typeof h.then!="function"&&u(y,h,v):x===nN?d(y,h,v):x===Y2?n(y,h,v):x===K2?u(y,h,v):x===X2||x===J2||x===rN?c(y,h,v):!1}}function uN(e){var t=e.circular,r=e.createCustomConfig,n=e.strict,i={areArraysEqual:n?yn:R2,areDatesEqual:L2,areErrorsEqual:B2,areFunctionsEqual:F2,areMapsEqual:n?vd(xd,yn):xd,areNumbersEqual:W2,areObjectsEqual:n?yn:z2,arePrimitiveWrappersEqual:U2,areRegExpsEqual:q2,areSetsEqual:n?vd(wd,yn):wd,areTypedArraysEqual:n?yn:H2,areUrlsEqual:G2};if(r&&(i=Ad({},i,r(i))),t){var a=$i(i.areArraysEqual),o=$i(i.areMapsEqual),u=$i(i.areObjectsEqual),c=$i(i.areSetsEqual);i=Ad({},i,{areArraysEqual:a,areMapsEqual:o,areObjectsEqual:u,areSetsEqual:c})}return i}function cN(e){return function(t,r,n,i,a,o,u){return e(t,r,u)}}function sN(e){var t=e.circular,r=e.comparator,n=e.createState,i=e.equals,a=e.strict;if(n)return function(c,s){var f=n(),l=f.cache,d=l===void 0?t?new WeakMap:void 0:l,p=f.meta;return r(c,s,{cache:d,equals:i,meta:p,strict:a})};if(t)return function(c,s){return r(c,s,{cache:new WeakMap,equals:i,meta:void 0,strict:a})};var o={cache:void 0,equals:i,meta:void 0,strict:a};return function(c,s){return r(c,s,o)}}var lN=Rt();Rt({strict:!0});Rt({circular:!0});Rt({circular:!0,strict:!0});Rt({createInternalComparator:function(){return sr}});Rt({strict:!0,createInternalComparator:function(){return sr}});Rt({circular:!0,createInternalComparator:function(){return sr}});Rt({circular:!0,createInternalComparator:function(){return sr},strict:!0});function Rt(e){e===void 0&&(e={});var t=e.circular,r=t===void 0?!1:t,n=e.createInternalComparator,i=e.createState,a=e.strict,o=a===void 0?!1:a,u=uN(e),c=oN(u),s=n?n(c):cN(c);return sN({circular:r,comparator:c,createState:i,equals:s,strict:o})}function fN(e){typeof requestAnimationFrame<"u"&&requestAnimationFrame(e)}function Pd(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(a){r<0&&(r=a),a-r>t?(e(a),r=-1):fN(i)};requestAnimationFrame(n)}function Hu(e){"@babel/helpers - typeof";return Hu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hu(e)}function dN(e){return vN(e)||yN(e)||hN(e)||pN()}function pN(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hN(e,t){if(e){if(typeof e=="string")return Sd(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Sd(e,t)}}function Sd(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function yN(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function vN(e){if(Array.isArray(e))return e}function gN(){var e={},t=function(){return null},r=!1,n=function i(a){if(!r){if(Array.isArray(a)){if(!a.length)return;var o=a,u=dN(o),c=u[0],s=u.slice(1);if(typeof c=="number"){Pd(i.bind(null,s),c);return}i(c),Pd(i.bind(null,s));return}Hu(a)==="object"&&(e=a,t(e)),typeof a=="function"&&a()}};return{stop:function(){r=!0},start:function(a){r=!1,n(a)},subscribe:function(a){return t=a,function(){t=function(){return null}}}}}function Gn(e){"@babel/helpers - typeof";return Gn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gn(e)}function _d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function $d(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_d(Object(r),!0).forEach(function(n){yv(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_d(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function yv(e,t,r){return t=mN(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function mN(e){var t=bN(e,"string");return Gn(t)==="symbol"?t:String(t)}function bN(e,t){if(Gn(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Gn(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var xN=function(t,r){return[Object.keys(t),Object.keys(r)].reduce(function(n,i){return n.filter(function(a){return i.includes(a)})})},wN=function(t){return t},ON=function(t){return t.replace(/([A-Z])/g,function(r){return"-".concat(r.toLowerCase())})},wn=function(t,r){return Object.keys(r).reduce(function(n,i){return $d($d({},n),{},yv({},i,t(i,r[i])))},{})},Td=function(t,r,n){return t.map(function(i){return"".concat(ON(i)," ").concat(r,"ms ").concat(n)}).join(",")};function AN(e,t){return _N(e)||SN(e,t)||vv(e,t)||PN()}function PN(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function SN(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function _N(e){if(Array.isArray(e))return e}function $N(e){return jN(e)||EN(e)||vv(e)||TN()}function TN(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vv(e,t){if(e){if(typeof e=="string")return Gu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Gu(e,t)}}function EN(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function jN(e){if(Array.isArray(e))return Gu(e)}function Gu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var ua=1e-4,gv=function(t,r){return[0,3*t,3*r-6*t,3*t-3*r+1]},mv=function(t,r){return t.map(function(n,i){return n*Math.pow(r,i)}).reduce(function(n,i){return n+i})},Ed=function(t,r){return function(n){var i=gv(t,r);return mv(i,n)}},MN=function(t,r){return function(n){var i=gv(t,r),a=[].concat($N(i.map(function(o,u){return o*u}).slice(1)),[0]);return mv(a,n)}},jd=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=r[0],a=r[1],o=r[2],u=r[3];if(r.length===1)switch(r[0]){case"linear":i=0,a=0,o=1,u=1;break;case"ease":i=.25,a=.1,o=.25,u=1;break;case"ease-in":i=.42,a=0,o=1,u=1;break;case"ease-out":i=.42,a=0,o=.58,u=1;break;case"ease-in-out":i=0,a=0,o=.58,u=1;break;default:{var c=r[0].split("(");if(c[0]==="cubic-bezier"&&c[1].split(")")[0].split(",").length===4){var s=c[1].split(")")[0].split(",").map(function(v){return parseFloat(v)}),f=AN(s,4);i=f[0],a=f[1],o=f[2],u=f[3]}}}var l=Ed(i,o),d=Ed(a,u),p=MN(i,o),y=function(b){return b>1?1:b<0?0:b},h=function(b){for(var w=b>1?1:b,x=w,A=0;A<8;++A){var g=l(x)-w,m=p(x);if(Math.abs(g-w)<ua||m<ua)return d(x);x=y(x-g/m)}return d(x)};return h.isStepper=!1,h},CN=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,i=t.damping,a=i===void 0?8:i,o=t.dt,u=o===void 0?17:o,c=function(f,l,d){var p=-(f-l)*n,y=d*a,h=d+(p-y)*u/1e3,v=d*u/1e3+f;return Math.abs(v-l)<ua&&Math.abs(h)<ua?[l,0]:[v,h]};return c.isStepper=!0,c.dt=u,c},IN=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=r[0];if(typeof i=="string")switch(i){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return jd(i);case"spring":return CN();default:if(i.split("(")[0]==="cubic-bezier")return jd(i)}return typeof i=="function"?i:null};function Kn(e){"@babel/helpers - typeof";return Kn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Kn(e)}function Md(e){return DN(e)||NN(e)||bv(e)||kN()}function kN(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NN(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function DN(e){if(Array.isArray(e))return Xu(e)}function Cd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Te(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Cd(Object(r),!0).forEach(function(n){Ku(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Cd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Ku(e,t,r){return t=RN(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RN(e){var t=LN(e,"string");return Kn(t)==="symbol"?t:String(t)}function LN(e,t){if(Kn(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Kn(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function BN(e,t){return zN(e)||WN(e,t)||bv(e,t)||FN()}function FN(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bv(e,t){if(e){if(typeof e=="string")return Xu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Xu(e,t)}}function Xu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function WN(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function zN(e){if(Array.isArray(e))return e}var ca=function(t,r,n){return t+(r-t)*n},Vu=function(t){var r=t.from,n=t.to;return r!==n},UN=function e(t,r,n){var i=wn(function(a,o){if(Vu(o)){var u=t(o.from,o.to,o.velocity),c=BN(u,2),s=c[0],f=c[1];return Te(Te({},o),{},{from:s,velocity:f})}return o},r);return n<1?wn(function(a,o){return Vu(o)?Te(Te({},o),{},{velocity:ca(o.velocity,i[a].velocity,n),from:ca(o.from,i[a].from,n)}):o},r):e(t,i,n-1)};const qN=function(e,t,r,n,i){var a=xN(e,t),o=a.reduce(function(v,b){return Te(Te({},v),{},Ku({},b,[e[b],t[b]]))},{}),u=a.reduce(function(v,b){return Te(Te({},v),{},Ku({},b,{from:e[b],velocity:0,to:t[b]}))},{}),c=-1,s,f,l=function(){return null},d=function(){return wn(function(b,w){return w.from},u)},p=function(){return!Object.values(u).filter(Vu).length},y=function(b){s||(s=b);var w=b-s,x=w/r.dt;u=UN(r,u,x),i(Te(Te(Te({},e),t),d())),s=b,p()||(c=requestAnimationFrame(l))},h=function(b){f||(f=b);var w=(b-f)/n,x=wn(function(g,m){return ca.apply(void 0,Md(m).concat([r(w)]))},o);if(i(Te(Te(Te({},e),t),x)),w<1)c=requestAnimationFrame(l);else{var A=wn(function(g,m){return ca.apply(void 0,Md(m).concat([r(1)]))},o);i(Te(Te(Te({},e),t),A))}};return l=r.isStepper?y:h,function(){return requestAnimationFrame(l),function(){cancelAnimationFrame(c)}}};function Cr(e){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Cr(e)}var HN=["children","begin","duration","attributeName","easing","isActive","steps","from","to","canBegin","onAnimationEnd","shouldReAnimate","onAnimationReStart"];function GN(e,t){if(e==null)return{};var r=KN(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function KN(e,t){if(e==null)return{};var r={},n=Object.keys(e),i,a;for(a=0;a<n.length;a++)i=n[a],!(t.indexOf(i)>=0)&&(r[i]=e[i]);return r}function Ho(e){return ZN(e)||YN(e)||VN(e)||XN()}function XN(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VN(e,t){if(e){if(typeof e=="string")return Yu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Yu(e,t)}}function YN(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ZN(e){if(Array.isArray(e))return Yu(e)}function Yu(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Id(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function et(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Id(Object(r),!0).forEach(function(n){gn(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Id(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function gn(e,t,r){return t=xv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function JN(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function QN(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,xv(n.key),n)}}function eD(e,t,r){return QN(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function xv(e){var t=tD(e,"string");return Cr(t)==="symbol"?t:String(t)}function tD(e,t){if(Cr(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Cr(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function rD(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Zu(e,t)}function Zu(e,t){return Zu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Zu(e,t)}function nD(e){var t=iD();return function(){var n=sa(e),i;if(t){var a=sa(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return Ju(this,i)}}function Ju(e,t){if(t&&(Cr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Qu(e)}function Qu(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function iD(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function sa(e){return sa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},sa(e)}var At=function(e){rD(r,e);var t=nD(r);function r(n,i){var a;JN(this,r),a=t.call(this,n,i);var o=a.props,u=o.isActive,c=o.attributeName,s=o.from,f=o.to,l=o.steps,d=o.children,p=o.duration;if(a.handleStyleChange=a.handleStyleChange.bind(Qu(a)),a.changeStyle=a.changeStyle.bind(Qu(a)),!u||p<=0)return a.state={style:{}},typeof d=="function"&&(a.state={style:f}),Ju(a);if(l&&l.length)a.state={style:l[0].style};else if(s){if(typeof d=="function")return a.state={style:s},Ju(a);a.state={style:c?gn({},c,s):s}}else a.state={style:{}};return a}return eD(r,[{key:"componentDidMount",value:function(){var i=this.props,a=i.isActive,o=i.canBegin;this.mounted=!0,!(!a||!o)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var a=this.props,o=a.isActive,u=a.canBegin,c=a.attributeName,s=a.shouldReAnimate,f=a.to,l=a.from,d=this.state.style;if(u){if(!o){var p={style:c?gn({},c,f):f};this.state&&d&&(c&&d[c]!==f||!c&&d!==f)&&this.setState(p);return}if(!(lN(i.to,f)&&i.canBegin&&i.isActive)){var y=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var h=y||s?l:i.to;if(this.state&&d){var v={style:c?gn({},c,h):h};(c&&d[c]!==h||!c&&d!==h)&&this.setState(v)}this.runAnimation(et(et({},this.props),{},{from:h,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var a=this,o=i.from,u=i.to,c=i.duration,s=i.easing,f=i.begin,l=i.onAnimationEnd,d=i.onAnimationStart,p=qN(o,u,IN(s),c,this.changeStyle),y=function(){a.stopJSAnimation=p()};this.manager.start([d,f,y,c,l])}},{key:"runStepAnimation",value:function(i){var a=this,o=i.steps,u=i.begin,c=i.onAnimationStart,s=o[0],f=s.style,l=s.duration,d=l===void 0?0:l,p=function(h,v,b){if(b===0)return h;var w=v.duration,x=v.easing,A=x===void 0?"ease":x,g=v.style,m=v.properties,O=v.onAnimationEnd,S=b>0?o[b-1]:v,_=m||Object.keys(g);if(typeof A=="function"||A==="spring")return[].concat(Ho(h),[a.runJSAnimation.bind(a,{from:S.style,to:g,duration:w,easing:A}),w]);var E=Td(_,w,A),$=et(et(et({},S.style),g),{},{transition:E});return[].concat(Ho(h),[$,w,O]).filter(wN)};return this.manager.start([c].concat(Ho(o.reduce(p,[f,Math.max(d,u)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=gN());var a=i.begin,o=i.duration,u=i.attributeName,c=i.to,s=i.easing,f=i.onAnimationStart,l=i.onAnimationEnd,d=i.steps,p=i.children,y=this.manager;if(this.unSubscribe=y.subscribe(this.handleStyleChange),typeof s=="function"||typeof p=="function"||s==="spring"){this.runJSAnimation(i);return}if(d.length>1){this.runStepAnimation(i);return}var h=u?gn({},u,c):c,v=Td(Object.keys(h),o,s);y.start([f,a,et(et({},h),{},{transition:v}),o,l])}},{key:"render",value:function(){var i=this.props,a=i.children;i.begin;var o=i.duration;i.attributeName,i.easing;var u=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var c=GN(i,HN),s=L.Children.count(a),f=this.state.style;if(typeof a=="function")return a(f);if(!u||s===0||o<=0)return a;var l=function(p){var y=p.props,h=y.style,v=h===void 0?{}:h,b=y.className,w=L.cloneElement(p,et(et({},c),{},{style:et(et({},v),f),className:b}));return w};return s===1?l(L.Children.only(a)):P.createElement("div",null,L.Children.map(a,function(d){return l(d)}))}}]),r}(L.PureComponent);At.displayName="Animate";At.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};At.propTypes={from:re.oneOfType([re.object,re.string]),to:re.oneOfType([re.object,re.string]),attributeName:re.string,duration:re.number,begin:re.number,easing:re.oneOfType([re.string,re.func]),steps:re.arrayOf(re.shape({duration:re.number.isRequired,style:re.object.isRequired,easing:re.oneOfType([re.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),re.func]),properties:re.arrayOf("string"),onAnimationEnd:re.func})),children:re.oneOfType([re.node,re.func]),isActive:re.bool,canBegin:re.bool,onAnimationEnd:re.func,shouldReAnimate:re.bool,onAnimationStart:re.func,onAnimationReStart:re.func};function Xn(e){"@babel/helpers - typeof";return Xn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xn(e)}function la(){return la=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},la.apply(this,arguments)}function aD(e,t){return sD(e)||cD(e,t)||uD(e,t)||oD()}function oD(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function uD(e,t){if(e){if(typeof e=="string")return kd(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return kd(e,t)}}function kd(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function cD(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function sD(e){if(Array.isArray(e))return e}function Nd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Dd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Nd(Object(r),!0).forEach(function(n){lD(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Nd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function lD(e,t,r){return t=fD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function fD(e){var t=dD(e,"string");return Xn(t)=="symbol"?t:t+""}function dD(e,t){if(Xn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Xn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Rd=function(t,r,n,i,a){var o=Math.min(Math.abs(n)/2,Math.abs(i)/2),u=i>=0?1:-1,c=n>=0?1:-1,s=i>=0&&n>=0||i<0&&n<0?1:0,f;if(o>0&&a instanceof Array){for(var l=[0,0,0,0],d=0,p=4;d<p;d++)l[d]=a[d]>o?o:a[d];f="M".concat(t,",").concat(r+u*l[0]),l[0]>0&&(f+="A ".concat(l[0],",").concat(l[0],",0,0,").concat(s,",").concat(t+c*l[0],",").concat(r)),f+="L ".concat(t+n-c*l[1],",").concat(r),l[1]>0&&(f+="A ".concat(l[1],",").concat(l[1],",0,0,").concat(s,`, + `).concat(t+n,",").concat(r+u*l[1])),f+="L ".concat(t+n,",").concat(r+i-u*l[2]),l[2]>0&&(f+="A ".concat(l[2],",").concat(l[2],",0,0,").concat(s,`, + `).concat(t+n-c*l[2],",").concat(r+i)),f+="L ".concat(t+c*l[3],",").concat(r+i),l[3]>0&&(f+="A ".concat(l[3],",").concat(l[3],",0,0,").concat(s,`, + `).concat(t,",").concat(r+i-u*l[3])),f+="Z"}else if(o>0&&a===+a&&a>0){var y=Math.min(o,a);f="M ".concat(t,",").concat(r+u*y,` + A `).concat(y,",").concat(y,",0,0,").concat(s,",").concat(t+c*y,",").concat(r,` + L `).concat(t+n-c*y,",").concat(r,` + A `).concat(y,",").concat(y,",0,0,").concat(s,",").concat(t+n,",").concat(r+u*y,` + L `).concat(t+n,",").concat(r+i-u*y,` + A `).concat(y,",").concat(y,",0,0,").concat(s,",").concat(t+n-c*y,",").concat(r+i,` + L `).concat(t+c*y,",").concat(r+i,` + A `).concat(y,",").concat(y,",0,0,").concat(s,",").concat(t,",").concat(r+i-u*y," Z")}else f="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return f},pD=function(t,r){if(!t||!r)return!1;var n=t.x,i=t.y,a=r.x,o=r.y,u=r.width,c=r.height;if(Math.abs(u)>0&&Math.abs(c)>0){var s=Math.min(a,a+u),f=Math.max(a,a+u),l=Math.min(o,o+c),d=Math.max(o,o+c);return n>=s&&n<=f&&i>=l&&i<=d}return!1},hD={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Os=function(t){var r=Dd(Dd({},hD),t),n=L.useRef(),i=L.useState(-1),a=aD(i,2),o=a[0],u=a[1];L.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var A=n.current.getTotalLength();A&&u(A)}catch{}},[]);var c=r.x,s=r.y,f=r.width,l=r.height,d=r.radius,p=r.className,y=r.animationEasing,h=r.animationDuration,v=r.animationBegin,b=r.isAnimationActive,w=r.isUpdateAnimationActive;if(c!==+c||s!==+s||f!==+f||l!==+l||f===0||l===0)return null;var x=J("recharts-rectangle",p);return w?P.createElement(At,{canBegin:o>0,from:{width:f,height:l,x:c,y:s},to:{width:f,height:l,x:c,y:s},duration:h,animationEasing:y,isActive:w},function(A){var g=A.width,m=A.height,O=A.x,S=A.y;return P.createElement(At,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:h,isActive:b,easing:y},P.createElement("path",la({},X(r,!0),{className:x,d:Rd(O,S,g,m,d),ref:n})))}):P.createElement("path",la({},X(r,!0),{className:x,d:Rd(c,s,f,l,d)}))},yD=["points","className","baseLinePoints","connectNulls"];function yr(){return yr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},yr.apply(this,arguments)}function vD(e,t){if(e==null)return{};var r=gD(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function gD(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ld(e){return wD(e)||xD(e)||bD(e)||mD()}function mD(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bD(e,t){if(e){if(typeof e=="string")return ec(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ec(e,t)}}function xD(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function wD(e){if(Array.isArray(e))return ec(e)}function ec(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Bd=function(t){return t&&t.x===+t.x&&t.y===+t.y},OD=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){Bd(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),Bd(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},On=function(t,r){var n=OD(t);r&&(n=[n.reduce(function(a,o){return[].concat(Ld(a),Ld(o))},[])]);var i=n.map(function(a){return a.reduce(function(o,u,c){return"".concat(o).concat(c===0?"M":"L").concat(u.x,",").concat(u.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},AD=function(t,r,n){var i=On(t,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(On(r.reverse(),n).slice(1))},PD=function(t){var r=t.points,n=t.className,i=t.baseLinePoints,a=t.connectNulls,o=vD(t,yD);if(!r||!r.length)return null;var u=J("recharts-polygon",n);if(i&&i.length){var c=o.stroke&&o.stroke!=="none",s=AD(r,i,a);return P.createElement("g",{className:u},P.createElement("path",yr({},X(o,!0),{fill:s.slice(-1)==="Z"?o.fill:"none",stroke:"none",d:s})),c?P.createElement("path",yr({},X(o,!0),{fill:"none",d:On(r,a)})):null,c?P.createElement("path",yr({},X(o,!0),{fill:"none",d:On(i,a)})):null)}var f=On(r,a);return P.createElement("path",yr({},X(o,!0),{fill:f.slice(-1)==="Z"?o.fill:"none",className:u,d:f}))};function tc(){return tc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},tc.apply(this,arguments)}var As=function(t){var r=t.cx,n=t.cy,i=t.r,a=t.className,o=J("recharts-dot",a);return r===+r&&n===+n&&i===+i?P.createElement("circle",tc({},X(t,!1),Mi(t),{className:o,cx:r,cy:n,r:i})):null};function Vn(e){"@babel/helpers - typeof";return Vn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vn(e)}var SD=["x","y","top","left","width","height","className"];function rc(){return rc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},rc.apply(this,arguments)}function Fd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function _D(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Fd(Object(r),!0).forEach(function(n){$D(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Fd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function $D(e,t,r){return t=TD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function TD(e){var t=ED(e,"string");return Vn(t)=="symbol"?t:t+""}function ED(e,t){if(Vn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Vn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function jD(e,t){if(e==null)return{};var r=MD(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function MD(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var CD=function(t,r,n,i,a,o){return"M".concat(t,",").concat(a,"v").concat(i,"M").concat(o,",").concat(r,"h").concat(n)},ID=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.top,u=o===void 0?0:o,c=t.left,s=c===void 0?0:c,f=t.width,l=f===void 0?0:f,d=t.height,p=d===void 0?0:d,y=t.className,h=jD(t,SD),v=_D({x:n,y:a,top:u,left:s,width:l,height:p},h);return!R(n)||!R(a)||!R(l)||!R(p)||!R(u)||!R(s)?null:P.createElement("path",rc({},X(v,!0),{className:J("recharts-cross",y),d:CD(n,a,l,p,u,s)}))},kD=no,ND=Cy,DD=lt;function RD(e,t){return e&&e.length?kD(e,DD(t),ND):void 0}var LD=RD;const BD=ie(LD);var FD=no,WD=lt,zD=Iy;function UD(e,t){return e&&e.length?FD(e,WD(t),zD):void 0}var qD=UD;const HD=ie(qD);var GD=["cx","cy","angle","ticks","axisLine"],KD=["ticks","tick","angle","tickFormatter","stroke"];function Ir(e){"@babel/helpers - typeof";return Ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ir(e)}function An(){return An=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},An.apply(this,arguments)}function Wd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ut(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Wd(Object(r),!0).forEach(function(n){lo(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Wd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function zd(e,t){if(e==null)return{};var r=XD(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function XD(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function VD(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ud(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Ov(n.key),n)}}function YD(e,t,r){return Ud(e.prototype,t),Ud(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function ZD(e,t,r){return t=fa(t),JD(e,wv()?Reflect.construct(t,r||[],fa(e).constructor):t.apply(e,r))}function JD(e,t){if(t&&(Ir(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return QD(e)}function QD(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function wv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(wv=function(){return!!e})()}function fa(e){return fa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},fa(e)}function eR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&nc(e,t)}function nc(e,t){return nc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},nc(e,t)}function lo(e,t,r){return t=Ov(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ov(e){var t=tR(e,"string");return Ir(t)=="symbol"?t:t+""}function tR(e,t){if(Ir(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ir(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var fo=function(e){function t(){return VD(this,t),ZD(this,t,arguments)}return eR(t,e),YD(t,[{key:"getTickValueCoord",value:function(n){var i=n.coordinate,a=this.props,o=a.angle,u=a.cx,c=a.cy;return le(u,c,i,o)}},{key:"getTickTextAnchor",value:function(){var n=this.props.orientation,i;switch(n){case"left":i="end";break;case"right":i="start";break;default:i="middle";break}return i}},{key:"getViewBox",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.angle,u=n.ticks,c=BD(u,function(f){return f.coordinate||0}),s=HD(u,function(f){return f.coordinate||0});return{cx:i,cy:a,startAngle:o,endAngle:o,innerRadius:s.coordinate||0,outerRadius:c.coordinate||0}}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.angle,u=n.ticks,c=n.axisLine,s=zd(n,GD),f=u.reduce(function(y,h){return[Math.min(y[0],h.coordinate),Math.max(y[1],h.coordinate)]},[1/0,-1/0]),l=le(i,a,f[0],o),d=le(i,a,f[1],o),p=Ut(Ut(Ut({},X(s,!1)),{},{fill:"none"},X(c,!1)),{},{x1:l.x,y1:l.y,x2:d.x,y2:d.y});return P.createElement("line",An({className:"recharts-polar-radius-axis-line"},p))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,o=i.tick,u=i.angle,c=i.tickFormatter,s=i.stroke,f=zd(i,KD),l=this.getTickTextAnchor(),d=X(f,!1),p=X(o,!1),y=a.map(function(h,v){var b=n.getTickValueCoord(h),w=Ut(Ut(Ut(Ut({textAnchor:l,transform:"rotate(".concat(90-u,", ").concat(b.x,", ").concat(b.y,")")},d),{},{stroke:"none",fill:s},p),{},{index:v},b),{},{payload:h});return P.createElement(ne,An({className:J("recharts-polar-radius-axis-tick",uv(o)),key:"tick-".concat(h.coordinate)},tr(n.props,h,v)),t.renderTickItem(o,w,c?c(h.value,v):h.value))});return P.createElement(ne,{className:"recharts-polar-radius-axis-ticks"},y)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.axisLine,o=n.tick;return!i||!i.length?null:P.createElement(ne,{className:J("recharts-polar-radius-axis",this.props.className)},a&&this.renderAxisLine(),o&&this.renderTicks(),_e.renderCallByParent(this.props,this.getViewBox()))}}],[{key:"renderTickItem",value:function(n,i,a){var o;return P.isValidElement(n)?o=P.cloneElement(n,i):V(n)?o=n(i):o=P.createElement(rr,An({},i,{className:"recharts-polar-radius-axis-tick-value"}),a),o}}])}(L.PureComponent);lo(fo,"displayName","PolarRadiusAxis");lo(fo,"axisType","radiusAxis");lo(fo,"defaultProps",{type:"number",radiusAxisId:0,cx:0,cy:0,angle:0,orientation:"right",stroke:"#ccc",axisLine:!0,tick:!0,tickCount:5,allowDataOverflow:!1,scale:"auto",allowDuplicatedCategory:!0});function kr(e){"@babel/helpers - typeof";return kr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},kr(e)}function Xt(){return Xt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Xt.apply(this,arguments)}function qd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function qt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?qd(Object(r),!0).forEach(function(n){po(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):qd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function rR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Hd(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Pv(n.key),n)}}function nR(e,t,r){return Hd(e.prototype,t),Hd(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function iR(e,t,r){return t=da(t),aR(e,Av()?Reflect.construct(t,r||[],da(e).constructor):t.apply(e,r))}function aR(e,t){if(t&&(kr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oR(e)}function oR(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Av(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Av=function(){return!!e})()}function da(e){return da=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},da(e)}function uR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ic(e,t)}function ic(e,t){return ic=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},ic(e,t)}function po(e,t,r){return t=Pv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Pv(e){var t=cR(e,"string");return kr(t)=="symbol"?t:t+""}function cR(e,t){if(kr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var sR=Math.PI/180,lR=1e-5,ho=function(e){function t(){return rR(this,t),iR(this,t,arguments)}return uR(t,e),nR(t,[{key:"getTickLineCoord",value:function(n){var i=this.props,a=i.cx,o=i.cy,u=i.radius,c=i.orientation,s=i.tickSize,f=s||8,l=le(a,o,u,n.coordinate),d=le(a,o,u+(c==="inner"?-1:1)*f,n.coordinate);return{x1:l.x,y1:l.y,x2:d.x,y2:d.y}}},{key:"getTickTextAnchor",value:function(n){var i=this.props.orientation,a=Math.cos(-n.coordinate*sR),o;return a>lR?o=i==="outer"?"start":"end":a<-1e-5?o=i==="outer"?"end":"start":o="middle",o}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.radius,u=n.axisLine,c=n.axisLineType,s=qt(qt({},X(this.props,!1)),{},{fill:"none"},X(u,!1));if(c==="circle")return P.createElement(As,Xt({className:"recharts-polar-angle-axis-line"},s,{cx:i,cy:a,r:o}));var f=this.props.ticks,l=f.map(function(d){return le(i,a,o,d.coordinate)});return P.createElement(PD,Xt({className:"recharts-polar-angle-axis-line"},s,{points:l}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,o=i.tick,u=i.tickLine,c=i.tickFormatter,s=i.stroke,f=X(this.props,!1),l=X(o,!1),d=qt(qt({},f),{},{fill:"none"},X(u,!1)),p=a.map(function(y,h){var v=n.getTickLineCoord(y),b=n.getTickTextAnchor(y),w=qt(qt(qt({textAnchor:b},f),{},{stroke:"none",fill:s},l),{},{index:h,payload:y,x:v.x2,y:v.y2});return P.createElement(ne,Xt({className:J("recharts-polar-angle-axis-tick",uv(o)),key:"tick-".concat(y.coordinate)},tr(n.props,y,h)),u&&P.createElement("line",Xt({className:"recharts-polar-angle-axis-tick-line"},d,v)),o&&t.renderTickItem(o,w,c?c(y.value,h):y.value))});return P.createElement(ne,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.radius,o=n.axisLine;return a<=0||!i||!i.length?null:P.createElement(ne,{className:J("recharts-polar-angle-axis",this.props.className)},o&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,a){var o;return P.isValidElement(n)?o=P.cloneElement(n,i):V(n)?o=n(i):o=P.createElement(rr,Xt({},i,{className:"recharts-polar-angle-axis-tick-value"}),a),o}}])}(L.PureComponent);po(ho,"displayName","PolarAngleAxis");po(ho,"axisType","angleAxis");po(ho,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var fR=$h,dR=fR(Object.getPrototypeOf,Object),pR=dR,hR=Pt,yR=pR,vR=St,gR="[object Object]",mR=Function.prototype,bR=Object.prototype,Sv=mR.toString,xR=bR.hasOwnProperty,wR=Sv.call(Object);function OR(e){if(!vR(e)||hR(e)!=gR)return!1;var t=yR(e);if(t===null)return!0;var r=xR.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Sv.call(r)==wR}var AR=OR;const PR=ie(AR);var SR=Pt,_R=St,$R="[object Boolean]";function TR(e){return e===!0||e===!1||_R(e)&&SR(e)==$R}var ER=TR;const jR=ie(ER);function Yn(e){"@babel/helpers - typeof";return Yn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yn(e)}function pa(){return pa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},pa.apply(this,arguments)}function MR(e,t){return NR(e)||kR(e,t)||IR(e,t)||CR()}function CR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function IR(e,t){if(e){if(typeof e=="string")return Gd(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Gd(e,t)}}function Gd(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function kR(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function NR(e){if(Array.isArray(e))return e}function Kd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Xd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Kd(Object(r),!0).forEach(function(n){DR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Kd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function DR(e,t,r){return t=RR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RR(e){var t=LR(e,"string");return Yn(t)=="symbol"?t:t+""}function LR(e,t){if(Yn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Yn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Vd=function(t,r,n,i,a){var o=n-i,u;return u="M ".concat(t,",").concat(r),u+="L ".concat(t+n,",").concat(r),u+="L ".concat(t+n-o/2,",").concat(r+a),u+="L ".concat(t+n-o/2-i,",").concat(r+a),u+="L ".concat(t,",").concat(r," Z"),u},BR={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},FR=function(t){var r=Xd(Xd({},BR),t),n=L.useRef(),i=L.useState(-1),a=MR(i,2),o=a[0],u=a[1];L.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var x=n.current.getTotalLength();x&&u(x)}catch{}},[]);var c=r.x,s=r.y,f=r.upperWidth,l=r.lowerWidth,d=r.height,p=r.className,y=r.animationEasing,h=r.animationDuration,v=r.animationBegin,b=r.isUpdateAnimationActive;if(c!==+c||s!==+s||f!==+f||l!==+l||d!==+d||f===0&&l===0||d===0)return null;var w=J("recharts-trapezoid",p);return b?P.createElement(At,{canBegin:o>0,from:{upperWidth:0,lowerWidth:0,height:d,x:c,y:s},to:{upperWidth:f,lowerWidth:l,height:d,x:c,y:s},duration:h,animationEasing:y,isActive:b},function(x){var A=x.upperWidth,g=x.lowerWidth,m=x.height,O=x.x,S=x.y;return P.createElement(At,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:h,easing:y},P.createElement("path",pa({},X(r,!0),{className:w,d:Vd(O,S,A,g,m),ref:n})))}):P.createElement("g",null,P.createElement("path",pa({},X(r,!0),{className:w,d:Vd(c,s,f,l,d)})))},WR=["option","shapeType","propTransformer","activeClassName","isActive"];function Zn(e){"@babel/helpers - typeof";return Zn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zn(e)}function zR(e,t){if(e==null)return{};var r=UR(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function UR(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Yd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ha(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Yd(Object(r),!0).forEach(function(n){qR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Yd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function qR(e,t,r){return t=HR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function HR(e){var t=GR(e,"string");return Zn(t)=="symbol"?t:t+""}function GR(e,t){if(Zn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Zn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function KR(e,t){return ha(ha({},t),e)}function XR(e,t){return e==="symbols"}function Zd(e){var t=e.shapeType,r=e.elementProps;switch(t){case"rectangle":return P.createElement(Os,r);case"trapezoid":return P.createElement(FR,r);case"sector":return P.createElement(lv,r);case"symbols":if(XR(t))return P.createElement(Fc,r);break;default:return null}}function VR(e){return L.isValidElement(e)?e.props:e}function _v(e){var t=e.option,r=e.shapeType,n=e.propTransformer,i=n===void 0?KR:n,a=e.activeClassName,o=a===void 0?"recharts-active-shape":a,u=e.isActive,c=zR(e,WR),s;if(L.isValidElement(t))s=L.cloneElement(t,ha(ha({},c),VR(t)));else if(V(t))s=t(c);else if(PR(t)&&!jR(t)){var f=i(t,c);s=P.createElement(Zd,{shapeType:r,elementProps:f})}else{var l=c;s=P.createElement(Zd,{shapeType:r,elementProps:l})}return u?P.createElement(ne,{className:o},s):s}function yo(e,t){return t!=null&&"trapezoids"in e.props}function vo(e,t){return t!=null&&"sectors"in e.props}function Jn(e,t){return t!=null&&"points"in e.props}function YR(e,t){var r,n,i=e.x===(t==null||(r=t.labelViewBox)===null||r===void 0?void 0:r.x)||e.x===t.x,a=e.y===(t==null||(n=t.labelViewBox)===null||n===void 0?void 0:n.y)||e.y===t.y;return i&&a}function ZR(e,t){var r=e.endAngle===t.endAngle,n=e.startAngle===t.startAngle;return r&&n}function JR(e,t){var r=e.x===t.x,n=e.y===t.y,i=e.z===t.z;return r&&n&&i}function QR(e,t){var r;return yo(e,t)?r=YR:vo(e,t)?r=ZR:Jn(e,t)&&(r=JR),r}function eL(e,t){var r;return yo(e,t)?r="trapezoids":vo(e,t)?r="sectors":Jn(e,t)&&(r="points"),r}function tL(e,t){if(yo(e,t)){var r;return(r=t.tooltipPayload)===null||r===void 0||(r=r[0])===null||r===void 0||(r=r.payload)===null||r===void 0?void 0:r.payload}if(vo(e,t)){var n;return(n=t.tooltipPayload)===null||n===void 0||(n=n[0])===null||n===void 0||(n=n.payload)===null||n===void 0?void 0:n.payload}return Jn(e,t)?t.payload:{}}function rL(e){var t=e.activeTooltipItem,r=e.graphicalItem,n=e.itemData,i=eL(r,t),a=tL(r,t),o=n.filter(function(c,s){var f=oo(a,c),l=r.props[i].filter(function(y){var h=QR(r,t);return h(y,t)}),d=r.props[i].indexOf(l[l.length-1]),p=s===d;return f&&p}),u=n.indexOf(o[o.length-1]);return u}var ji;function Nr(e){"@babel/helpers - typeof";return Nr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Nr(e)}function vr(){return vr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},vr.apply(this,arguments)}function Jd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ce(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Jd(Object(r),!0).forEach(function(n){Ke(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Jd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function nL(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Qd(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Tv(n.key),n)}}function iL(e,t,r){return Qd(e.prototype,t),Qd(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function aL(e,t,r){return t=ya(t),oL(e,$v()?Reflect.construct(t,r,ya(e).constructor):t.apply(e,r))}function oL(e,t){if(t&&(Nr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return uL(e)}function uL(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function $v(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($v=function(){return!!e})()}function ya(e){return ya=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ya(e)}function cL(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ac(e,t)}function ac(e,t){return ac=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},ac(e,t)}function Ke(e,t,r){return t=Tv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Tv(e){var t=sL(e,"string");return Nr(t)=="symbol"?t:t+""}function sL(e,t){if(Nr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Nr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Lt=function(e){function t(r){var n;return nL(this,t),n=aL(this,t,[r]),Ke(n,"pieRef",null),Ke(n,"sectorRefs",[]),Ke(n,"id",ci("recharts-pie-")),Ke(n,"handleAnimationEnd",function(){var i=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),V(i)&&i()}),Ke(n,"handleAnimationStart",function(){var i=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),V(i)&&i()}),n.state={isAnimationFinished:!r.isAnimationActive,prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,sectorToFocus:0},n}return cL(t,e),iL(t,[{key:"isActiveIndex",value:function(n){var i=this.props.activeIndex;return Array.isArray(i)?i.indexOf(n)!==-1:n===i}},{key:"hasActiveIndex",value:function(){var n=this.props.activeIndex;return Array.isArray(n)?n.length!==0:n||n===0}},{key:"renderLabels",value:function(n){var i=this.props.isAnimationActive;if(i&&!this.state.isAnimationFinished)return null;var a=this.props,o=a.label,u=a.labelLine,c=a.dataKey,s=a.valueKey,f=X(this.props,!1),l=X(o,!1),d=X(u,!1),p=o&&o.offsetRadius||20,y=n.map(function(h,v){var b=(h.startAngle+h.endAngle)/2,w=le(h.cx,h.cy,h.outerRadius+p,b),x=ce(ce(ce(ce({},f),h),{},{stroke:"none"},l),{},{index:v,textAnchor:t.getTextAnchor(w.x,h.cx)},w),A=ce(ce(ce(ce({},f),h),{},{fill:"none",stroke:h.fill},d),{},{index:v,points:[le(h.cx,h.cy,h.outerRadius,b),w]}),g=c;return Q(c)&&Q(s)?g="value":Q(c)&&(g=s),P.createElement(ne,{key:"label-".concat(h.startAngle,"-").concat(h.endAngle,"-").concat(h.midAngle,"-").concat(v)},u&&t.renderLabelLineItem(u,A,"line"),t.renderLabelItem(o,x,Me(h,g)))});return P.createElement(ne,{className:"recharts-pie-labels"},y)}},{key:"renderSectorsStatically",value:function(n){var i=this,a=this.props,o=a.activeShape,u=a.blendStroke,c=a.inactiveShape;return n.map(function(s,f){if((s==null?void 0:s.startAngle)===0&&(s==null?void 0:s.endAngle)===0&&n.length!==1)return null;var l=i.isActiveIndex(f),d=c&&i.hasActiveIndex()?c:null,p=l?o:d,y=ce(ce({},s),{},{stroke:u?s.fill:s.stroke,tabIndex:-1});return P.createElement(ne,vr({ref:function(v){v&&!i.sectorRefs.includes(v)&&i.sectorRefs.push(v)},tabIndex:-1,className:"recharts-pie-sector"},tr(i.props,s,f),{key:"sector-".concat(s==null?void 0:s.startAngle,"-").concat(s==null?void 0:s.endAngle,"-").concat(s.midAngle,"-").concat(f)}),P.createElement(_v,vr({option:p,isActive:l,shapeType:"sector"},y)))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,i=this.props,a=i.sectors,o=i.isAnimationActive,u=i.animationBegin,c=i.animationDuration,s=i.animationEasing,f=i.animationId,l=this.state,d=l.prevSectors,p=l.prevIsAnimationActive;return P.createElement(At,{begin:u,duration:c,isActive:o,easing:s,from:{t:0},to:{t:1},key:"pie-".concat(f,"-").concat(p),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(y){var h=y.t,v=[],b=a&&a[0],w=b.startAngle;return a.forEach(function(x,A){var g=d&&d[A],m=A>0?qe(x,"paddingAngle",0):0;if(g){var O=Tt(g.endAngle-g.startAngle,x.endAngle-x.startAngle),S=ce(ce({},x),{},{startAngle:w+m,endAngle:w+O(h)+m});v.push(S),w=S.endAngle}else{var _=x.endAngle,E=x.startAngle,$=Tt(0,_-E),T=$(h),C=ce(ce({},x),{},{startAngle:w+m,endAngle:w+T+m});v.push(C),w=C.endAngle}}),P.createElement(ne,null,n.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(a){if(!a.altKey)switch(a.key){case"ArrowLeft":{var o=++i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[o].focus(),i.setState({sectorToFocus:o});break}case"ArrowRight":{var u=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[u].focus(),i.setState({sectorToFocus:u});break}case"Escape":{i.sectorRefs[i.state.sectorToFocus].blur(),i.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,i=n.sectors,a=n.isAnimationActive,o=this.state.prevSectors;return a&&i&&i.length&&(!o||!oo(o,i))?this.renderSectorsWithAnimation():this.renderSectorsStatically(i)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,i=this.props,a=i.hide,o=i.sectors,u=i.className,c=i.label,s=i.cx,f=i.cy,l=i.innerRadius,d=i.outerRadius,p=i.isAnimationActive,y=this.state.isAnimationFinished;if(a||!o||!o.length||!R(s)||!R(f)||!R(l)||!R(d))return null;var h=J("recharts-pie",u);return P.createElement(ne,{tabIndex:this.props.rootTabIndex,className:h,ref:function(b){n.pieRef=b}},this.renderSectors(),c&&this.renderLabels(o),_e.renderCallByParent(this.props,null,!1),(!p||y)&&It.renderCallByParent(this.props,o,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return i.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:i.curSectors,isAnimationFinished:!0}:n.sectors!==i.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,i){return n>i?"start":n<i?"end":"middle"}},{key:"renderLabelLineItem",value:function(n,i,a){if(P.isValidElement(n))return P.cloneElement(n,i);if(V(n))return n(i);var o=J("recharts-pie-label-line",typeof n!="boolean"?n.className:"");return P.createElement(qu,vr({},i,{key:a,type:"linear",className:o}))}},{key:"renderLabelItem",value:function(n,i,a){if(P.isValidElement(n))return P.cloneElement(n,i);var o=a;if(V(n)&&(o=n(i),P.isValidElement(o)))return o;var u=J("recharts-pie-label-text",typeof n!="boolean"&&!V(n)?n.className:"");return P.createElement(rr,vr({},i,{alignmentBaseline:"middle",className:u}),o)}}])}(L.PureComponent);ji=Lt;Ke(Lt,"displayName","Pie");Ke(Lt,"defaultProps",{stroke:"#fff",fill:"#808080",legendType:"rect",cx:"50%",cy:"50%",startAngle:0,endAngle:360,innerRadius:0,outerRadius:"80%",paddingAngle:0,labelLine:!0,hide:!1,minAngle:0,isAnimationActive:!mt.isSsr,animationBegin:400,animationDuration:1500,animationEasing:"ease",nameKey:"name",blendStroke:!1,rootTabIndex:0});Ke(Lt,"parseDeltaAngle",function(e,t){var r=Ie(t-e),n=Math.min(Math.abs(t-e),360);return r*n});Ke(Lt,"getRealPieData",function(e){var t=e.data,r=e.children,n=X(e,!1),i=Ve(r,Yc);return t&&t.length?t.map(function(a,o){return ce(ce(ce({payload:a},n),a),i[o]&&i[o].props)}):i.length?i.map(function(a){return ce(ce({},n),a.props)}):[]});Ke(Lt,"parseCoordinateOfPie",function(e,t){var r=t.top,n=t.left,i=t.width,a=t.height,o=ov(i,a),u=n+ke(e.cx,i,i/2),c=r+ke(e.cy,a,a/2),s=ke(e.innerRadius,o,0),f=ke(e.outerRadius,o,o*.8),l=e.maxRadius||Math.sqrt(i*i+a*a)/2;return{cx:u,cy:c,innerRadius:s,outerRadius:f,maxRadius:l}});Ke(Lt,"getComposedData",function(e){var t=e.item,r=e.offset,n=t.type.defaultProps!==void 0?ce(ce({},t.type.defaultProps),t.props):t.props,i=ji.getRealPieData(n);if(!i||!i.length)return null;var a=n.cornerRadius,o=n.startAngle,u=n.endAngle,c=n.paddingAngle,s=n.dataKey,f=n.nameKey,l=n.valueKey,d=n.tooltipType,p=Math.abs(n.minAngle),y=ji.parseCoordinateOfPie(n,r),h=ji.parseDeltaAngle(o,u),v=Math.abs(h),b=s;Q(s)&&Q(l)?(nt(!1,`Use "dataKey" to specify the value of pie, + the props "valueKey" will be deprecated in 1.1.0`),b="value"):Q(s)&&(nt(!1,`Use "dataKey" to specify the value of pie, + the props "valueKey" will be deprecated in 1.1.0`),b=l);var w=i.filter(function(S){return Me(S,b,0)!==0}).length,x=(v>=360?w:w-1)*c,A=v-w*p-x,g=i.reduce(function(S,_){var E=Me(_,b,0);return S+(R(E)?E:0)},0),m;if(g>0){var O;m=i.map(function(S,_){var E=Me(S,b,0),$=Me(S,f,_),T=(R(E)?E:0)/g,C;_?C=O.endAngle+Ie(h)*c*(E!==0?1:0):C=o;var I=C+Ie(h)*((E!==0?p:0)+T*A),M=(C+I)/2,k=(y.innerRadius+y.outerRadius)/2,D=[{name:$,value:E,payload:S,dataKey:b,type:d}],B=le(y.cx,y.cy,k,M);return O=ce(ce(ce({percent:T,cornerRadius:a,name:$,tooltipPayload:D,midAngle:M,middleRadius:k,tooltipPosition:B},S),y),{},{value:Me(S,b),startAngle:C,endAngle:I,payload:S,paddingAngle:Ie(h)*c}),O})}return ce(ce({},y),{},{sectors:m,data:i})});var lL=Math.ceil,fL=Math.max;function dL(e,t,r,n){for(var i=-1,a=fL(lL((t-e)/(r||1)),0),o=Array(a);a--;)o[n?a:++i]=e,e+=r;return o}var pL=dL,hL=Gh,yL=1/0,vL=17976931348623157e292;function gL(e){if(!e)return e===0?e:0;if(e=hL(e),e===yL||e===-1/0){var t=e<0?-1:1;return t*vL}return e===e?e:0}var Ev=gL,mL=pL,bL=Ya,Go=Ev;function xL(e){return function(t,r,n){return n&&typeof n!="number"&&bL(t,r,n)&&(r=n=void 0),t=Go(t),r===void 0?(r=t,t=0):r=Go(r),n=n===void 0?t<r?1:-1:Go(n),mL(t,r,n,e)}}var wL=xL,OL=wL,AL=OL(),PL=AL;const va=ie(PL);function Qn(e){"@babel/helpers - typeof";return Qn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qn(e)}function ep(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function tp(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ep(Object(r),!0).forEach(function(n){jv(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ep(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function jv(e,t,r){return t=SL(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function SL(e){var t=_L(e,"string");return Qn(t)=="symbol"?t:t+""}function _L(e,t){if(Qn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Qn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var $L=["Webkit","Moz","O","ms"],TL=function(t,r){var n=t.replace(/(\w)/,function(a){return a.toUpperCase()}),i=$L.reduce(function(a,o){return tp(tp({},a),{},jv({},o+n,r))},{});return i[t]=r,i};function Dr(e){"@babel/helpers - typeof";return Dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dr(e)}function ga(){return ga=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ga.apply(this,arguments)}function rp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ko(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rp(Object(r),!0).forEach(function(n){We(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function EL(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function np(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Cv(n.key),n)}}function jL(e,t,r){return np(e.prototype,t),np(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function ML(e,t,r){return t=ma(t),CL(e,Mv()?Reflect.construct(t,r,ma(e).constructor):t.apply(e,r))}function CL(e,t){if(t&&(Dr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return IL(e)}function IL(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Mv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Mv=function(){return!!e})()}function ma(e){return ma=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ma(e)}function kL(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&oc(e,t)}function oc(e,t){return oc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},oc(e,t)}function We(e,t,r){return t=Cv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Cv(e){var t=NL(e,"string");return Dr(t)=="symbol"?t:t+""}function NL(e,t){if(Dr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Dr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var DL=function(t){var r=t.data,n=t.startIndex,i=t.endIndex,a=t.x,o=t.width,u=t.travellerWidth;if(!r||!r.length)return{};var c=r.length,s=bn().domain(va(0,c)).range([a,a+o-u]),f=s.domain().map(function(l){return s(l)});return{isTextActive:!1,isSlideMoving:!1,isTravellerMoving:!1,isTravellerFocused:!1,startX:s(n),endX:s(i),scale:s,scaleValues:f}},ip=function(t){return t.changedTouches&&!!t.changedTouches.length},Rr=function(e){function t(r){var n;return EL(this,t),n=ML(this,t,[r]),We(n,"handleDrag",function(i){n.leaveTimer&&(clearTimeout(n.leaveTimer),n.leaveTimer=null),n.state.isTravellerMoving?n.handleTravellerMove(i):n.state.isSlideMoving&&n.handleSlideDrag(i)}),We(n,"handleTouchMove",function(i){i.changedTouches!=null&&i.changedTouches.length>0&&n.handleDrag(i.changedTouches[0])}),We(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,a=i.endIndex,o=i.onDragEnd,u=i.startIndex;o==null||o({endIndex:a,startIndex:u})}),n.detachDragEndListener()}),We(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),We(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),We(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),We(n,"handleSlideDragStart",function(i){var a=ip(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:a.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return kL(t,e),jL(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,a=n.endX,o=this.state.scaleValues,u=this.props,c=u.gap,s=u.data,f=s.length-1,l=Math.min(i,a),d=Math.max(i,a),p=t.getIndexInRange(o,l),y=t.getIndexInRange(o,d);return{startIndex:p-p%c,endIndex:y===f?f:y-y%c}}},{key:"getTextOfTick",value:function(n){var i=this.props,a=i.data,o=i.tickFormatter,u=i.dataKey,c=Me(a[n],u,n);return V(o)?o(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,a=i.slideMoveStartX,o=i.startX,u=i.endX,c=this.props,s=c.x,f=c.width,l=c.travellerWidth,d=c.startIndex,p=c.endIndex,y=c.onChange,h=n.pageX-a;h>0?h=Math.min(h,s+f-l-u,s+f-l-o):h<0&&(h=Math.max(h,s-o,s-u));var v=this.getIndex({startX:o+h,endX:u+h});(v.startIndex!==d||v.endIndex!==p)&&y&&y(v),this.setState({startX:o+h,endX:u+h,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var a=ip(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:a.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,a=i.brushMoveStartX,o=i.movingTravellerId,u=i.endX,c=i.startX,s=this.state[o],f=this.props,l=f.x,d=f.width,p=f.travellerWidth,y=f.onChange,h=f.gap,v=f.data,b={startX:this.state.startX,endX:this.state.endX},w=n.pageX-a;w>0?w=Math.min(w,l+d-p-s):w<0&&(w=Math.max(w,l-s)),b[o]=s+w;var x=this.getIndex(b),A=x.startIndex,g=x.endIndex,m=function(){var S=v.length-1;return o==="startX"&&(u>c?A%h===0:g%h===0)||u<c&&g===S||o==="endX"&&(u>c?g%h===0:A%h===0)||u>c&&g===S};this.setState(We(We({},o,s+w),"brushMoveStartX",n.pageX),function(){y&&m()&&y(x)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var a=this,o=this.state,u=o.scaleValues,c=o.startX,s=o.endX,f=this.state[i],l=u.indexOf(f);if(l!==-1){var d=l+n;if(!(d===-1||d>=u.length)){var p=u[d];i==="startX"&&p>=s||i==="endX"&&p<=c||this.setState(We({},i,p),function(){a.props.onChange(a.getIndex({startX:a.state.startX,endX:a.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,u=n.height,c=n.fill,s=n.stroke;return P.createElement("rect",{stroke:s,fill:c,x:i,y:a,width:o,height:u})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,u=n.height,c=n.data,s=n.children,f=n.padding,l=L.Children.only(s);return l?P.cloneElement(l,{x:i,y:a,width:o,height:u,margin:f,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,i){var a,o,u=this,c=this.props,s=c.y,f=c.travellerWidth,l=c.height,d=c.traveller,p=c.ariaLabel,y=c.data,h=c.startIndex,v=c.endIndex,b=Math.max(n,this.props.x),w=Ko(Ko({},X(this.props,!1)),{},{x:b,y:s,width:f,height:l}),x=p||"Min value: ".concat((a=y[h])===null||a===void 0?void 0:a.name,", Max value: ").concat((o=y[v])===null||o===void 0?void 0:o.name);return P.createElement(ne,{tabIndex:0,role:"slider","aria-label":x,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(g){["ArrowLeft","ArrowRight"].includes(g.key)&&(g.preventDefault(),g.stopPropagation(),u.handleTravellerMoveKeyboard(g.key==="ArrowRight"?1:-1,i))},onFocus:function(){u.setState({isTravellerFocused:!0})},onBlur:function(){u.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(d,w))}},{key:"renderSlide",value:function(n,i){var a=this.props,o=a.y,u=a.height,c=a.stroke,s=a.travellerWidth,f=Math.min(n,i)+s,l=Math.max(Math.abs(i-n)-s,0);return P.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:f,y:o,width:l,height:u})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,a=n.endIndex,o=n.y,u=n.height,c=n.travellerWidth,s=n.stroke,f=this.state,l=f.startX,d=f.endX,p=5,y={pointerEvents:"none",fill:s};return P.createElement(ne,{className:"recharts-brush-texts"},P.createElement(rr,ga({textAnchor:"end",verticalAnchor:"middle",x:Math.min(l,d)-p,y:o+u/2},y),this.getTextOfTick(i)),P.createElement(rr,ga({textAnchor:"start",verticalAnchor:"middle",x:Math.max(l,d)+c+p,y:o+u/2},y),this.getTextOfTick(a)))}},{key:"render",value:function(){var n=this.props,i=n.data,a=n.className,o=n.children,u=n.x,c=n.y,s=n.width,f=n.height,l=n.alwaysShowText,d=this.state,p=d.startX,y=d.endX,h=d.isTextActive,v=d.isSlideMoving,b=d.isTravellerMoving,w=d.isTravellerFocused;if(!i||!i.length||!R(u)||!R(c)||!R(s)||!R(f)||s<=0||f<=0)return null;var x=J("recharts-brush",a),A=P.Children.count(o)===1,g=TL("userSelect","none");return P.createElement(ne,{className:x,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:g},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(p,y),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(y,"endX"),(h||v||b||w||l)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,a=n.y,o=n.width,u=n.height,c=n.stroke,s=Math.floor(a+u/2)-1;return P.createElement(P.Fragment,null,P.createElement("rect",{x:i,y:a,width:o,height:u,fill:c,stroke:"none"}),P.createElement("line",{x1:i+1,y1:s,x2:i+o-1,y2:s,fill:"none",stroke:"#fff"}),P.createElement("line",{x1:i+1,y1:s+2,x2:i+o-1,y2:s+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var a;return P.isValidElement(n)?a=P.cloneElement(n,i):V(n)?a=n(i):a=t.renderDefaultTraveller(i),a}},{key:"getDerivedStateFromProps",value:function(n,i){var a=n.data,o=n.width,u=n.x,c=n.travellerWidth,s=n.updateId,f=n.startIndex,l=n.endIndex;if(a!==i.prevData||s!==i.prevUpdateId)return Ko({prevData:a,prevTravellerWidth:c,prevUpdateId:s,prevX:u,prevWidth:o},a&&a.length?DL({data:a,width:o,x:u,travellerWidth:c,startIndex:f,endIndex:l}):{scale:null,scaleValues:null});if(i.scale&&(o!==i.prevWidth||u!==i.prevX||c!==i.prevTravellerWidth)){i.scale.range([u,u+o-c]);var d=i.scale.domain().map(function(p){return i.scale(p)});return{prevData:a,prevTravellerWidth:c,prevUpdateId:s,prevX:u,prevWidth:o,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:d}}return null}},{key:"getIndexInRange",value:function(n,i){for(var a=n.length,o=0,u=a-1;u-o>1;){var c=Math.floor((o+u)/2);n[c]>i?u=c:o=c}return i>=n[u]?u:o}}])}(L.PureComponent);We(Rr,"displayName","Brush");We(Rr,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var RL=Kc;function LL(e,t){var r;return RL(e,function(n,i,a){return r=t(n,i,a),!r}),!!r}var BL=LL,FL=bh,WL=lt,zL=BL,UL=Be,qL=Ya;function HL(e,t,r){var n=UL(e)?FL:zL;return r&&qL(e,t,r)&&(t=void 0),n(e,WL(t))}var GL=HL;const KL=ie(GL);var ut=function(t,r){var n=t.alwaysShow,i=t.ifOverflow;return n&&(i="extendDomain"),i===r},ap=Wh;function XL(e,t,r){t=="__proto__"&&ap?ap(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var VL=XL,YL=VL,ZL=Bh,JL=lt;function QL(e,t){var r={};return t=JL(t),ZL(e,function(n,i,a){YL(r,i,t(n,i,a))}),r}var eB=QL;const tB=ie(eB);function rB(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}var nB=rB,iB=Kc;function aB(e,t){var r=!0;return iB(e,function(n,i,a){return r=!!t(n,i,a),r}),r}var oB=aB,uB=nB,cB=oB,sB=lt,lB=Be,fB=Ya;function dB(e,t,r){var n=lB(e)?uB:cB;return r&&fB(e,t,r)&&(t=void 0),n(e,sB(t))}var pB=dB;const Iv=ie(pB);var hB=["x","y"];function ei(e){"@babel/helpers - typeof";return ei=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ei(e)}function uc(){return uc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},uc.apply(this,arguments)}function op(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function vn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?op(Object(r),!0).forEach(function(n){yB(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):op(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function yB(e,t,r){return t=vB(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function vB(e){var t=gB(e,"string");return ei(t)=="symbol"?t:t+""}function gB(e,t){if(ei(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ei(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function mB(e,t){if(e==null)return{};var r=bB(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function bB(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function xB(e,t){var r=e.x,n=e.y,i=mB(e,hB),a="".concat(r),o=parseInt(a,10),u="".concat(n),c=parseInt(u,10),s="".concat(t.height||i.height),f=parseInt(s,10),l="".concat(t.width||i.width),d=parseInt(l,10);return vn(vn(vn(vn(vn({},t),i),o?{x:o}:{}),c?{y:c}:{}),{},{height:f,width:d,name:t.name,radius:t.radius})}function up(e){return P.createElement(_v,uc({shapeType:"rectangle",propTransformer:xB,activeClassName:"recharts-active-bar"},e))}var wB=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof t=="number")return t;var a=typeof n=="number";return a?t(n,i):(a||ir(),r)}},OB=["value","background"],kv;function Lr(e){"@babel/helpers - typeof";return Lr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lr(e)}function AB(e,t){if(e==null)return{};var r=PB(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function PB(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function ba(){return ba=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ba.apply(this,arguments)}function cp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function me(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?cp(Object(r),!0).forEach(function(n){Mt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):cp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function SB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function sp(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Dv(n.key),n)}}function _B(e,t,r){return sp(e.prototype,t),sp(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function $B(e,t,r){return t=xa(t),TB(e,Nv()?Reflect.construct(t,r,xa(e).constructor):t.apply(e,r))}function TB(e,t){if(t&&(Lr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return EB(e)}function EB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Nv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Nv=function(){return!!e})()}function xa(e){return xa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},xa(e)}function jB(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&cc(e,t)}function cc(e,t){return cc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},cc(e,t)}function Mt(e,t,r){return t=Dv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Dv(e){var t=MB(e,"string");return Lr(t)=="symbol"?t:t+""}function MB(e,t){if(Lr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Lr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var an=function(e){function t(){var r;SB(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=$B(this,t,[].concat(i)),Mt(r,"state",{isAnimationFinished:!1}),Mt(r,"id",ci("recharts-bar-")),Mt(r,"handleAnimationEnd",function(){var o=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),o&&o()}),Mt(r,"handleAnimationStart",function(){var o=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),o&&o()}),r}return jB(t,e),_B(t,[{key:"renderRectanglesStatically",value:function(n){var i=this,a=this.props,o=a.shape,u=a.dataKey,c=a.activeIndex,s=a.activeBar,f=X(this.props,!1);return n&&n.map(function(l,d){var p=d===c,y=p?s:o,h=me(me(me({},f),l),{},{isActive:p,option:y,index:d,dataKey:u,onAnimationStart:i.handleAnimationStart,onAnimationEnd:i.handleAnimationEnd});return P.createElement(ne,ba({className:"recharts-bar-rectangle"},tr(i.props,l,d),{key:"rectangle-".concat(l==null?void 0:l.x,"-").concat(l==null?void 0:l.y,"-").concat(l==null?void 0:l.value)}),P.createElement(up,h))})}},{key:"renderRectanglesWithAnimation",value:function(){var n=this,i=this.props,a=i.data,o=i.layout,u=i.isAnimationActive,c=i.animationBegin,s=i.animationDuration,f=i.animationEasing,l=i.animationId,d=this.state.prevData;return P.createElement(At,{begin:c,duration:s,isActive:u,easing:f,from:{t:0},to:{t:1},key:"bar-".concat(l),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(p){var y=p.t,h=a.map(function(v,b){var w=d&&d[b];if(w){var x=Tt(w.x,v.x),A=Tt(w.y,v.y),g=Tt(w.width,v.width),m=Tt(w.height,v.height);return me(me({},v),{},{x:x(y),y:A(y),width:g(y),height:m(y)})}if(o==="horizontal"){var O=Tt(0,v.height),S=O(y);return me(me({},v),{},{y:v.y+v.height-S,height:S})}var _=Tt(0,v.width),E=_(y);return me(me({},v),{},{width:E})});return P.createElement(ne,null,n.renderRectanglesStatically(h))})}},{key:"renderRectangles",value:function(){var n=this.props,i=n.data,a=n.isAnimationActive,o=this.state.prevData;return a&&i&&i.length&&(!o||!oo(o,i))?this.renderRectanglesWithAnimation():this.renderRectanglesStatically(i)}},{key:"renderBackground",value:function(){var n=this,i=this.props,a=i.data,o=i.dataKey,u=i.activeIndex,c=X(this.props.background,!1);return a.map(function(s,f){s.value;var l=s.background,d=AB(s,OB);if(!l)return null;var p=me(me(me(me(me({},d),{},{fill:"#eee"},l),c),tr(n.props,s,f)),{},{onAnimationStart:n.handleAnimationStart,onAnimationEnd:n.handleAnimationEnd,dataKey:o,index:f,className:"recharts-bar-background-rectangle"});return P.createElement(up,ba({key:"background-bar-".concat(f),option:n.props.background,isActive:f===u},p))})}},{key:"renderErrorBar",value:function(n,i){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var a=this.props,o=a.data,u=a.xAxis,c=a.yAxis,s=a.layout,f=a.children,l=Ve(f,so);if(!l)return null;var d=s==="vertical"?o[0].height/2:o[0].width/2,p=function(v,b){var w=Array.isArray(v.value)?v.value[1]:v.value;return{x:v.x,y:v.y,value:w,errorVal:Me(v,b)}},y={clipPath:n?"url(#clipPath-".concat(i,")"):null};return P.createElement(ne,y,l.map(function(h){return P.cloneElement(h,{key:"error-bar-".concat(i,"-").concat(h.props.dataKey),data:o,xAxis:u,yAxis:c,layout:s,offset:d,dataPointFormatter:p})}))}},{key:"render",value:function(){var n=this.props,i=n.hide,a=n.data,o=n.className,u=n.xAxis,c=n.yAxis,s=n.left,f=n.top,l=n.width,d=n.height,p=n.isAnimationActive,y=n.background,h=n.id;if(i||!a||!a.length)return null;var v=this.state.isAnimationFinished,b=J("recharts-bar",o),w=u&&u.allowDataOverflow,x=c&&c.allowDataOverflow,A=w||x,g=Q(h)?this.id:h;return P.createElement(ne,{className:b},w||x?P.createElement("defs",null,P.createElement("clipPath",{id:"clipPath-".concat(g)},P.createElement("rect",{x:w?s:s-l/2,y:x?f:f-d/2,width:w?l:l*2,height:x?d:d*2}))):null,P.createElement(ne,{className:"recharts-bar-rectangles",clipPath:A?"url(#clipPath-".concat(g,")"):null},y?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(A,g),(!p||v)&&It.renderCallByParent(this.props,a))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curData:n.data,prevData:i.curData}:n.data!==i.curData?{curData:n.data}:null}}])}(L.PureComponent);kv=an;Mt(an,"displayName","Bar");Mt(an,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!mt.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"});Mt(an,"getComposedData",function(e){var t=e.props,r=e.item,n=e.barPosition,i=e.bandSize,a=e.xAxis,o=e.yAxis,u=e.xAxisTicks,c=e.yAxisTicks,s=e.stackedData,f=e.dataStartIndex,l=e.displayedData,d=e.offset,p=sk(n,r);if(!p)return null;var y=t.layout,h=r.type.defaultProps,v=h!==void 0?me(me({},h),r.props):r.props,b=v.dataKey,w=v.children,x=v.minPointSize,A=y==="horizontal"?o:a,g=s?A.scale.domain():null,m=vk({numericAxis:A}),O=Ve(w,Yc),S=l.map(function(_,E){var $,T,C,I,M,k;s?$=lk(s[f+E],g):($=Me(_,b),Array.isArray($)||($=[m,$]));var D=wB(x,kv.defaultProps.minPointSize)($[1],E);if(y==="horizontal"){var B,F=[o.scale($[0]),o.scale($[1])],q=F[0],G=F[1];T=ed({axis:a,ticks:u,bandSize:i,offset:p.offset,entry:_,index:E}),C=(B=G??q)!==null&&B!==void 0?B:void 0,I=p.size;var z=q-G;if(M=Number.isNaN(z)?0:z,k={x:T,y:o.y,width:I,height:o.height},Math.abs(D)>0&&Math.abs(M)<Math.abs(D)){var K=Ie(M||D)*(Math.abs(D)-Math.abs(M));C-=K,M+=K}}else{var fe=[a.scale($[0]),a.scale($[1])],ge=fe[0],Fe=fe[1];if(T=ge,C=ed({axis:o,ticks:c,bandSize:i,offset:p.offset,entry:_,index:E}),I=Fe-ge,M=p.size,k={x:a.x,y:C,width:a.width,height:M},Math.abs(D)>0&&Math.abs(I)<Math.abs(D)){var Bt=Ie(I||D)*(Math.abs(D)-Math.abs(I));I+=Bt}}return me(me(me({},_),{},{x:T,y:C,width:I,height:M,value:s?$:$[1],payload:_,background:k},O[E]&&O[E].props),{},{tooltipPayload:[iv(r,_)],tooltipPosition:{x:T+I/2,y:C+M/2}})});return me({data:S,layout:y},d)});function ti(e){"@babel/helpers - typeof";return ti=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ti(e)}function CB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function lp(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Rv(n.key),n)}}function IB(e,t,r){return lp(e.prototype,t),lp(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function fp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function tt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fp(Object(r),!0).forEach(function(n){go(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function go(e,t,r){return t=Rv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Rv(e){var t=kB(e,"string");return ti(t)=="symbol"?t:t+""}function kB(e,t){if(ti(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ti(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var NB=function(t,r,n,i,a){var o=t.width,u=t.height,c=t.layout,s=t.children,f=Object.keys(r),l={left:n.left,leftMirror:n.left,right:o-n.right,rightMirror:o-n.right,top:n.top,topMirror:n.top,bottom:u-n.bottom,bottomMirror:u-n.bottom},d=!!ze(s,an);return f.reduce(function(p,y){var h=r[y],v=h.orientation,b=h.domain,w=h.padding,x=w===void 0?{}:w,A=h.mirror,g=h.reversed,m="".concat(v).concat(A?"Mirror":""),O,S,_,E,$;if(h.type==="number"&&(h.padding==="gap"||h.padding==="no-gap")){var T=b[1]-b[0],C=1/0,I=h.categoricalDomain.sort();if(I.forEach(function(fe,ge){ge>0&&(C=Math.min((fe||0)-(I[ge-1]||0),C))}),Number.isFinite(C)){var M=C/T,k=h.layout==="vertical"?n.height:n.width;if(h.padding==="gap"&&(O=M*k/2),h.padding==="no-gap"){var D=ke(t.barCategoryGap,M*k),B=M*k/2;O=B-D-(B-D)/k*D}}}i==="xAxis"?S=[n.left+(x.left||0)+(O||0),n.left+n.width-(x.right||0)-(O||0)]:i==="yAxis"?S=c==="horizontal"?[n.top+n.height-(x.bottom||0),n.top+(x.top||0)]:[n.top+(x.top||0)+(O||0),n.top+n.height-(x.bottom||0)-(O||0)]:S=h.range,g&&(S=[S[1],S[0]]);var F=ev(h,a,d),q=F.scale,G=F.realScaleType;q.domain(b).range(S),tv(q);var z=rv(q,tt(tt({},h),{},{realScaleType:G}));i==="xAxis"?($=v==="top"&&!A||v==="bottom"&&A,_=n.left,E=l[m]-$*h.height):i==="yAxis"&&($=v==="left"&&!A||v==="right"&&A,_=l[m]-$*h.width,E=n.top);var K=tt(tt(tt({},h),z),{},{realScaleType:G,x:_,y:E,scale:q,width:i==="xAxis"?n.width:h.width,height:i==="yAxis"?n.height:h.height});return K.bandSize=ia(K,z),!h.hide&&i==="xAxis"?l[m]+=($?-1:1)*K.height:h.hide||(l[m]+=($?-1:1)*K.width),tt(tt({},p),{},go({},y,K))},{})},Lv=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return{x:Math.min(n,a),y:Math.min(i,o),width:Math.abs(a-n),height:Math.abs(o-i)}},DB=function(t){var r=t.x1,n=t.y1,i=t.x2,a=t.y2;return Lv({x:r,y:n},{x:i,y:a})},Bv=function(){function e(t){CB(this,e),this.scale=t}return IB(e,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,a=n.position;if(r!==void 0){if(a)switch(a){case"start":return this.scale(r);case"middle":{var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+o}case"end":{var u=this.bandwidth?this.bandwidth():0;return this.scale(r)+u}default:return this.scale(r)}if(i){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],a=n[n.length-1];return i<=a?r>=i&&r<=a:r>=a&&r<=i}}],[{key:"create",value:function(r){return new e(r)}}])}();go(Bv,"EPS",1e-4);var Ps=function(t){var r=Object.keys(t).reduce(function(n,i){return tt(tt({},n),{},go({},i,Bv.create(t[i])))},{});return tt(tt({},r),{},{apply:function(i){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=a.bandAware,u=a.position;return tB(i,function(c,s){return r[s].apply(c,{bandAware:o,position:u})})},isInRange:function(i){return Iv(i,function(a,o){return r[o].isInRange(a)})}})};function RB(e){return(e%180+180)%180}var LB=function(t){var r=t.width,n=t.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=RB(i),o=a*Math.PI/180,u=Math.atan(n/r),c=o>u&&o<Math.PI-u?n/Math.sin(o):r/Math.cos(o);return Math.abs(c)},BB=lt,FB=si,WB=Xa;function zB(e){return function(t,r,n){var i=Object(t);if(!FB(t)){var a=BB(r);t=WB(t),r=function(u){return a(i[u],u,i)}}var o=e(t,r,n);return o>-1?i[a?t[o]:o]:void 0}}var UB=zB,qB=Ev;function HB(e){var t=qB(e),r=t%1;return t===t?r?t-r:t:0}var GB=HB,KB=Ih,XB=lt,VB=GB,YB=Math.max;function ZB(e,t,r){var n=e==null?0:e.length;if(!n)return-1;var i=r==null?0:VB(r);return i<0&&(i=YB(n+i,0)),KB(e,XB(t),i)}var JB=ZB,QB=UB,eF=JB,tF=QB(eF),rF=tF;const nF=ie(rF);var iF=e0(function(e){return{x:e.left,y:e.top,width:e.width,height:e.height}},function(e){return["l",e.left,"t",e.top,"w",e.width,"h",e.height].join("")}),Ss=L.createContext(void 0),_s=L.createContext(void 0),Fv=L.createContext(void 0),Wv=L.createContext({}),zv=L.createContext(void 0),Uv=L.createContext(0),qv=L.createContext(0),dp=function(t){var r=t.state,n=r.xAxisMap,i=r.yAxisMap,a=r.offset,o=t.clipPathId,u=t.children,c=t.width,s=t.height,f=iF(a);return P.createElement(Ss.Provider,{value:n},P.createElement(_s.Provider,{value:i},P.createElement(Wv.Provider,{value:a},P.createElement(Fv.Provider,{value:f},P.createElement(zv.Provider,{value:o},P.createElement(Uv.Provider,{value:s},P.createElement(qv.Provider,{value:c},u)))))))},aF=function(){return L.useContext(zv)},Hv=function(t){var r=L.useContext(Ss);r==null&&ir();var n=r[t];return n==null&&ir(),n},oF=function(){var t=L.useContext(Ss);return jt(t)},uF=function(){var t=L.useContext(_s),r=nF(t,function(n){return Iv(n.domain,Number.isFinite)});return r||jt(t)},Gv=function(t){var r=L.useContext(_s);r==null&&ir();var n=r[t];return n==null&&ir(),n},cF=function(){var t=L.useContext(Fv);return t},sF=function(){return L.useContext(Wv)},$s=function(){return L.useContext(qv)},Ts=function(){return L.useContext(Uv)};function Br(e){"@babel/helpers - typeof";return Br=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Br(e)}function lF(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function fF(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Xv(n.key),n)}}function dF(e,t,r){return fF(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function pF(e,t,r){return t=wa(t),hF(e,Kv()?Reflect.construct(t,r||[],wa(e).constructor):t.apply(e,r))}function hF(e,t){if(t&&(Br(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return yF(e)}function yF(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Kv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Kv=function(){return!!e})()}function wa(e){return wa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},wa(e)}function vF(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&sc(e,t)}function sc(e,t){return sc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},sc(e,t)}function pp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function hp(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pp(Object(r),!0).forEach(function(n){Es(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Es(e,t,r){return t=Xv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Xv(e){var t=gF(e,"string");return Br(t)=="symbol"?t:t+""}function gF(e,t){if(Br(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Br(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function mF(e,t){return OF(e)||wF(e,t)||xF(e,t)||bF()}function bF(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xF(e,t){if(e){if(typeof e=="string")return yp(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return yp(e,t)}}function yp(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function wF(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function OF(e){if(Array.isArray(e))return e}function lc(){return lc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},lc.apply(this,arguments)}var AF=function(t,r){var n;return P.isValidElement(t)?n=P.cloneElement(t,r):V(t)?n=t(r):n=P.createElement("line",lc({},r,{className:"recharts-reference-line-line"})),n},PF=function(t,r,n,i,a,o,u,c,s){var f=a.x,l=a.y,d=a.width,p=a.height;if(n){var y=s.y,h=t.y.apply(y,{position:o});if(ut(s,"discard")&&!t.y.isInRange(h))return null;var v=[{x:f+d,y:h},{x:f,y:h}];return c==="left"?v.reverse():v}if(r){var b=s.x,w=t.x.apply(b,{position:o});if(ut(s,"discard")&&!t.x.isInRange(w))return null;var x=[{x:w,y:l+p},{x:w,y:l}];return u==="top"?x.reverse():x}if(i){var A=s.segment,g=A.map(function(m){return t.apply(m,{position:o})});return ut(s,"discard")&&KL(g,function(m){return!t.isInRange(m)})?null:g}return null};function SF(e){var t=e.x,r=e.y,n=e.segment,i=e.xAxisId,a=e.yAxisId,o=e.shape,u=e.className,c=e.alwaysShow,s=aF(),f=Hv(i),l=Gv(a),d=cF();if(!s||!d)return null;nt(c===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var p=Ps({x:f.scale,y:l.scale}),y=Ae(t),h=Ae(r),v=n&&n.length===2,b=PF(p,y,h,v,d,e.position,f.orientation,l.orientation,e);if(!b)return null;var w=mF(b,2),x=w[0],A=x.x,g=x.y,m=w[1],O=m.x,S=m.y,_=ut(e,"hidden")?"url(#".concat(s,")"):void 0,E=hp(hp({clipPath:_},X(e,!0)),{},{x1:A,y1:g,x2:O,y2:S});return P.createElement(ne,{className:J("recharts-reference-line",u)},AF(o,E),_e.renderCallByParent(e,DB({x1:A,y1:g,x2:O,y2:S})))}var js=function(e){function t(){return lF(this,t),pF(this,t,arguments)}return vF(t,e),dF(t,[{key:"render",value:function(){return P.createElement(SF,this.props)}}])}(P.Component);Es(js,"displayName","ReferenceLine");Es(js,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});function fc(){return fc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},fc.apply(this,arguments)}function Fr(e){"@babel/helpers - typeof";return Fr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fr(e)}function vp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function gp(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?vp(Object(r),!0).forEach(function(n){mo(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):vp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function _F(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $F(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Yv(n.key),n)}}function TF(e,t,r){return $F(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function EF(e,t,r){return t=Oa(t),jF(e,Vv()?Reflect.construct(t,r||[],Oa(e).constructor):t.apply(e,r))}function jF(e,t){if(t&&(Fr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return MF(e)}function MF(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Vv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Vv=function(){return!!e})()}function Oa(e){return Oa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Oa(e)}function CF(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dc(e,t)}function dc(e,t){return dc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},dc(e,t)}function mo(e,t,r){return t=Yv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Yv(e){var t=IF(e,"string");return Fr(t)=="symbol"?t:t+""}function IF(e,t){if(Fr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Fr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var kF=function(t){var r=t.x,n=t.y,i=t.xAxis,a=t.yAxis,o=Ps({x:i.scale,y:a.scale}),u=o.apply({x:r,y:n},{bandAware:!0});return ut(t,"discard")&&!o.isInRange(u)?null:u},bo=function(e){function t(){return _F(this,t),EF(this,t,arguments)}return CF(t,e),TF(t,[{key:"render",value:function(){var n=this.props,i=n.x,a=n.y,o=n.r,u=n.alwaysShow,c=n.clipPathId,s=Ae(i),f=Ae(a);if(nt(u===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!s||!f)return null;var l=kF(this.props);if(!l)return null;var d=l.x,p=l.y,y=this.props,h=y.shape,v=y.className,b=ut(this.props,"hidden")?"url(#".concat(c,")"):void 0,w=gp(gp({clipPath:b},X(this.props,!0)),{},{cx:d,cy:p});return P.createElement(ne,{className:J("recharts-reference-dot",v)},t.renderDot(h,w),_e.renderCallByParent(this.props,{x:d-o,y:p-o,width:2*o,height:2*o}))}}])}(P.Component);mo(bo,"displayName","ReferenceDot");mo(bo,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});mo(bo,"renderDot",function(e,t){var r;return P.isValidElement(e)?r=P.cloneElement(e,t):V(e)?r=e(t):r=P.createElement(As,fc({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),r});function pc(){return pc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},pc.apply(this,arguments)}function Wr(e){"@babel/helpers - typeof";return Wr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wr(e)}function mp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function bp(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?mp(Object(r),!0).forEach(function(n){xo(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):mp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function NF(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function DF(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Jv(n.key),n)}}function RF(e,t,r){return DF(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function LF(e,t,r){return t=Aa(t),BF(e,Zv()?Reflect.construct(t,r||[],Aa(e).constructor):t.apply(e,r))}function BF(e,t){if(t&&(Wr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return FF(e)}function FF(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Zv(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Zv=function(){return!!e})()}function Aa(e){return Aa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Aa(e)}function WF(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&hc(e,t)}function hc(e,t){return hc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},hc(e,t)}function xo(e,t,r){return t=Jv(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Jv(e){var t=zF(e,"string");return Wr(t)=="symbol"?t:t+""}function zF(e,t){if(Wr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Wr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var UF=function(t,r,n,i,a){var o=a.x1,u=a.x2,c=a.y1,s=a.y2,f=a.xAxis,l=a.yAxis;if(!f||!l)return null;var d=Ps({x:f.scale,y:l.scale}),p={x:t?d.x.apply(o,{position:"start"}):d.x.rangeMin,y:n?d.y.apply(c,{position:"start"}):d.y.rangeMin},y={x:r?d.x.apply(u,{position:"end"}):d.x.rangeMax,y:i?d.y.apply(s,{position:"end"}):d.y.rangeMax};return ut(a,"discard")&&(!d.isInRange(p)||!d.isInRange(y))?null:Lv(p,y)},wo=function(e){function t(){return NF(this,t),LF(this,t,arguments)}return WF(t,e),RF(t,[{key:"render",value:function(){var n=this.props,i=n.x1,a=n.x2,o=n.y1,u=n.y2,c=n.className,s=n.alwaysShow,f=n.clipPathId;nt(s===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var l=Ae(i),d=Ae(a),p=Ae(o),y=Ae(u),h=this.props.shape;if(!l&&!d&&!p&&!y&&!h)return null;var v=UF(l,d,p,y,this.props);if(!v&&!h)return null;var b=ut(this.props,"hidden")?"url(#".concat(f,")"):void 0;return P.createElement(ne,{className:J("recharts-reference-area",c)},t.renderRect(h,bp(bp({clipPath:b},X(this.props,!0)),v)),_e.renderCallByParent(this.props,v))}}])}(P.Component);xo(wo,"displayName","ReferenceArea");xo(wo,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});xo(wo,"renderRect",function(e,t){var r;return P.isValidElement(e)?r=P.cloneElement(e,t):V(e)?r=e(t):r=P.createElement(Os,pc({},t,{className:"recharts-reference-area-rect"})),r});function Qv(e,t,r){if(t<1)return[];if(t===1&&r===void 0)return e;for(var n=[],i=0;i<e.length;i+=t)n.push(e[i]);return n}function qF(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return LB(n,r)}function HF(e,t,r){var n=r==="width",i=e.x,a=e.y,o=e.width,u=e.height;return t===1?{start:n?i:a,end:n?i+o:a+u}:{start:n?i+o:a+u,end:n?i:a}}function Pa(e,t,r,n,i){if(e*t<e*n||e*t>e*i)return!1;var a=r();return e*(t-e*a/2-n)>=0&&e*(t+e*a/2-i)<=0}function GF(e,t){return Qv(e,t+1)}function KF(e,t,r,n,i){for(var a=(n||[]).slice(),o=t.start,u=t.end,c=0,s=1,f=o,l=function(){var y=n==null?void 0:n[c];if(y===void 0)return{v:Qv(n,s)};var h=c,v,b=function(){return v===void 0&&(v=r(y,h)),v},w=y.coordinate,x=c===0||Pa(e,w,b,f,u);x||(c=0,f=o,s+=1),x&&(f=w+e*(b()/2+i),c+=s)},d;s<=a.length;)if(d=l(),d)return d.v;return[]}function ri(e){"@babel/helpers - typeof";return ri=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ri(e)}function xp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ee(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?xp(Object(r),!0).forEach(function(n){XF(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):xp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function XF(e,t,r){return t=VF(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function VF(e){var t=YF(e,"string");return ri(t)=="symbol"?t:t+""}function YF(e,t){if(ri(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ri(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ZF(e,t,r,n,i){for(var a=(n||[]).slice(),o=a.length,u=t.start,c=t.end,s=function(d){var p=a[d],y,h=function(){return y===void 0&&(y=r(p,d)),y};if(d===o-1){var v=e*(p.coordinate+e*h()/2-c);a[d]=p=Ee(Ee({},p),{},{tickCoord:v>0?p.coordinate-v*e:p.coordinate})}else a[d]=p=Ee(Ee({},p),{},{tickCoord:p.coordinate});var b=Pa(e,p.tickCoord,h,u,c);b&&(c=p.tickCoord-e*(h()/2+i),a[d]=Ee(Ee({},p),{},{isShow:!0}))},f=o-1;f>=0;f--)s(f);return a}function JF(e,t,r,n,i,a){var o=(n||[]).slice(),u=o.length,c=t.start,s=t.end;if(a){var f=n[u-1],l=r(f,u-1),d=e*(f.coordinate+e*l/2-s);o[u-1]=f=Ee(Ee({},f),{},{tickCoord:d>0?f.coordinate-d*e:f.coordinate});var p=Pa(e,f.tickCoord,function(){return l},c,s);p&&(s=f.tickCoord-e*(l/2+i),o[u-1]=Ee(Ee({},f),{},{isShow:!0}))}for(var y=a?u-1:u,h=function(w){var x=o[w],A,g=function(){return A===void 0&&(A=r(x,w)),A};if(w===0){var m=e*(x.coordinate-e*g()/2-c);o[w]=x=Ee(Ee({},x),{},{tickCoord:m<0?x.coordinate-m*e:x.coordinate})}else o[w]=x=Ee(Ee({},x),{},{tickCoord:x.coordinate});var O=Pa(e,x.tickCoord,g,c,s);O&&(c=x.tickCoord+e*(g()/2+i),o[w]=Ee(Ee({},x),{},{isShow:!0}))},v=0;v<y;v++)h(v);return o}function Ms(e,t,r){var n=e.tick,i=e.ticks,a=e.viewBox,o=e.minTickGap,u=e.orientation,c=e.interval,s=e.tickFormatter,f=e.unit,l=e.angle;if(!i||!i.length||!n)return[];if(R(c)||mt.isSsr)return GF(i,typeof c=="number"&&R(c)?c:0);var d=[],p=u==="top"||u==="bottom"?"width":"height",y=f&&p==="width"?mn(f,{fontSize:t,letterSpacing:r}):{width:0,height:0},h=function(x,A){var g=V(s)?s(x.value,A):x.value;return p==="width"?qF(mn(g,{fontSize:t,letterSpacing:r}),y,l):mn(g,{fontSize:t,letterSpacing:r})[p]},v=i.length>=2?Ie(i[1].coordinate-i[0].coordinate):1,b=HF(a,v,p);return c==="equidistantPreserveStart"?KF(v,b,h,i,o):(c==="preserveStart"||c==="preserveStartEnd"?d=JF(v,b,h,i,o,c==="preserveStartEnd"):d=ZF(v,b,h,i,o),d.filter(function(w){return w.isShow}))}var QF=["viewBox"],e3=["viewBox"],t3=["ticks"];function zr(e){"@babel/helpers - typeof";return zr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zr(e)}function gr(){return gr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gr.apply(this,arguments)}function wp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ce(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?wp(Object(r),!0).forEach(function(n){Cs(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Xo(e,t){if(e==null)return{};var r=r3(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function r3(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function n3(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Op(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,tg(n.key),n)}}function i3(e,t,r){return Op(e.prototype,t),Op(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function a3(e,t,r){return t=Sa(t),o3(e,eg()?Reflect.construct(t,r,Sa(e).constructor):t.apply(e,r))}function o3(e,t){if(t&&(zr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return u3(e)}function u3(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function eg(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(eg=function(){return!!e})()}function Sa(e){return Sa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Sa(e)}function c3(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&yc(e,t)}function yc(e,t){return yc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},yc(e,t)}function Cs(e,t,r){return t=tg(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tg(e){var t=s3(e,"string");return zr(t)=="symbol"?t:t+""}function s3(e,t){if(zr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(zr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var on=function(e){function t(r){var n;return n3(this,t),n=a3(this,t,[r]),n.state={fontSize:"",letterSpacing:""},n}return c3(t,e),i3(t,[{key:"shouldComponentUpdate",value:function(n,i){var a=n.viewBox,o=Xo(n,QF),u=this.props,c=u.viewBox,s=Xo(u,e3);return!br(a,c)||!br(o,s)||!br(i,this.state)}},{key:"componentDidMount",value:function(){var n=this.layerReference;if(n){var i=n.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];i&&this.setState({fontSize:window.getComputedStyle(i).fontSize,letterSpacing:window.getComputedStyle(i).letterSpacing})}}},{key:"getTickLineCoord",value:function(n){var i=this.props,a=i.x,o=i.y,u=i.width,c=i.height,s=i.orientation,f=i.tickSize,l=i.mirror,d=i.tickMargin,p,y,h,v,b,w,x=l?-1:1,A=n.tickSize||f,g=R(n.tickCoord)?n.tickCoord:n.coordinate;switch(s){case"top":p=y=n.coordinate,v=o+ +!l*c,h=v-x*A,w=h-x*d,b=g;break;case"left":h=v=n.coordinate,y=a+ +!l*u,p=y-x*A,b=p-x*d,w=g;break;case"right":h=v=n.coordinate,y=a+ +l*u,p=y+x*A,b=p+x*d,w=g;break;default:p=y=n.coordinate,v=o+ +l*c,h=v+x*A,w=h+x*d,b=g;break}return{line:{x1:p,y1:h,x2:y,y2:v},tick:{x:b,y:w}}}},{key:"getTickTextAnchor",value:function(){var n=this.props,i=n.orientation,a=n.mirror,o;switch(i){case"left":o=a?"start":"end";break;case"right":o=a?"end":"start";break;default:o="middle";break}return o}},{key:"getTickVerticalAnchor",value:function(){var n=this.props,i=n.orientation,a=n.mirror,o="end";switch(i){case"left":case"right":o="middle";break;case"top":o=a?"start":"end";break;default:o=a?"end":"start";break}return o}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,u=n.height,c=n.orientation,s=n.mirror,f=n.axisLine,l=Ce(Ce(Ce({},X(this.props,!1)),X(f,!1)),{},{fill:"none"});if(c==="top"||c==="bottom"){var d=+(c==="top"&&!s||c==="bottom"&&s);l=Ce(Ce({},l),{},{x1:i,y1:a+d*u,x2:i+o,y2:a+d*u})}else{var p=+(c==="left"&&!s||c==="right"&&s);l=Ce(Ce({},l),{},{x1:i+p*o,y1:a,x2:i+p*o,y2:a+u})}return P.createElement("line",gr({},l,{className:J("recharts-cartesian-axis-line",qe(f,"className"))}))}},{key:"renderTicks",value:function(n,i,a){var o=this,u=this.props,c=u.tickLine,s=u.stroke,f=u.tick,l=u.tickFormatter,d=u.unit,p=Ms(Ce(Ce({},this.props),{},{ticks:n}),i,a),y=this.getTickTextAnchor(),h=this.getTickVerticalAnchor(),v=X(this.props,!1),b=X(f,!1),w=Ce(Ce({},v),{},{fill:"none"},X(c,!1)),x=p.map(function(A,g){var m=o.getTickLineCoord(A),O=m.line,S=m.tick,_=Ce(Ce(Ce(Ce({textAnchor:y,verticalAnchor:h},v),{},{stroke:"none",fill:s},b),S),{},{index:g,payload:A,visibleTicksCount:p.length,tickFormatter:l});return P.createElement(ne,gr({className:"recharts-cartesian-axis-tick",key:"tick-".concat(A.value,"-").concat(A.coordinate,"-").concat(A.tickCoord)},tr(o.props,A,g)),c&&P.createElement("line",gr({},w,O,{className:J("recharts-cartesian-axis-tick-line",qe(c,"className"))})),f&&t.renderTickItem(f,_,"".concat(V(l)?l(A.value,g):A.value).concat(d||"")))});return P.createElement("g",{className:"recharts-cartesian-axis-ticks"},x)}},{key:"render",value:function(){var n=this,i=this.props,a=i.axisLine,o=i.width,u=i.height,c=i.ticksGenerator,s=i.className,f=i.hide;if(f)return null;var l=this.props,d=l.ticks,p=Xo(l,t3),y=d;return V(c)&&(y=d&&d.length>0?c(this.props):c(p)),o<=0||u<=0||!y||!y.length?null:P.createElement(ne,{className:J("recharts-cartesian-axis",s),ref:function(v){n.layerReference=v}},a&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),_e.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,a){var o;return P.isValidElement(n)?o=P.cloneElement(n,i):V(n)?o=n(i):o=P.createElement(rr,gr({},i,{className:"recharts-cartesian-axis-tick-value"}),a),o}}])}(L.Component);Cs(on,"displayName","CartesianAxis");Cs(on,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var l3=["x1","y1","x2","y2","key"],f3=["offset"];function ar(e){"@babel/helpers - typeof";return ar=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ar(e)}function Ap(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function je(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ap(Object(r),!0).forEach(function(n){d3(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ap(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function d3(e,t,r){return t=p3(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function p3(e){var t=h3(e,"string");return ar(t)=="symbol"?t:t+""}function h3(e,t){if(ar(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ar(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Jt(){return Jt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Jt.apply(this,arguments)}function Pp(e,t){if(e==null)return{};var r=y3(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function y3(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var v3=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,i=t.x,a=t.y,o=t.width,u=t.height,c=t.ry;return P.createElement("rect",{x:i,y:a,ry:c,width:o,height:u,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function rg(e,t){var r;if(P.isValidElement(e))r=P.cloneElement(e,t);else if(V(e))r=e(t);else{var n=t.x1,i=t.y1,a=t.x2,o=t.y2,u=t.key,c=Pp(t,l3),s=X(c,!1);s.offset;var f=Pp(s,f3);r=P.createElement("line",Jt({},f,{x1:n,y1:i,x2:a,y2:o,fill:"none",key:u}))}return r}function g3(e){var t=e.x,r=e.width,n=e.horizontal,i=n===void 0?!0:n,a=e.horizontalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(u,c){var s=je(je({},e),{},{x1:t,y1:u,x2:t+r,y2:u,key:"line-".concat(c),index:c});return rg(i,s)});return P.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function m3(e){var t=e.y,r=e.height,n=e.vertical,i=n===void 0?!0:n,a=e.verticalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(u,c){var s=je(je({},e),{},{x1:u,y1:t,x2:u,y2:t+r,key:"line-".concat(c),index:c});return rg(i,s)});return P.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function b3(e){var t=e.horizontalFill,r=e.fillOpacity,n=e.x,i=e.y,a=e.width,o=e.height,u=e.horizontalPoints,c=e.horizontal,s=c===void 0?!0:c;if(!s||!t||!t.length)return null;var f=u.map(function(d){return Math.round(d+i-i)}).sort(function(d,p){return d-p});i!==f[0]&&f.unshift(0);var l=f.map(function(d,p){var y=!f[p+1],h=y?i+o-d:f[p+1]-d;if(h<=0)return null;var v=p%t.length;return P.createElement("rect",{key:"react-".concat(p),y:d,x:n,height:h,width:a,stroke:"none",fill:t[v],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return P.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},l)}function x3(e){var t=e.vertical,r=t===void 0?!0:t,n=e.verticalFill,i=e.fillOpacity,a=e.x,o=e.y,u=e.width,c=e.height,s=e.verticalPoints;if(!r||!n||!n.length)return null;var f=s.map(function(d){return Math.round(d+a-a)}).sort(function(d,p){return d-p});a!==f[0]&&f.unshift(0);var l=f.map(function(d,p){var y=!f[p+1],h=y?a+u-d:f[p+1]-d;if(h<=0)return null;var v=p%n.length;return P.createElement("rect",{key:"react-".concat(p),x:d,y:o,width:h,height:c,stroke:"none",fill:n[v],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return P.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},l)}var w3=function(t,r){var n=t.xAxis,i=t.width,a=t.height,o=t.offset;return Qy(Ms(je(je(je({},on.defaultProps),n),{},{ticks:vt(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.left,o.left+o.width,r)},O3=function(t,r){var n=t.yAxis,i=t.width,a=t.height,o=t.offset;return Qy(Ms(je(je(je({},on.defaultProps),n),{},{ticks:vt(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.top,o.top+o.height,r)},pr={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function A3(e){var t,r,n,i,a,o,u=$s(),c=Ts(),s=sF(),f=je(je({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:pr.stroke,fill:(r=e.fill)!==null&&r!==void 0?r:pr.fill,horizontal:(n=e.horizontal)!==null&&n!==void 0?n:pr.horizontal,horizontalFill:(i=e.horizontalFill)!==null&&i!==void 0?i:pr.horizontalFill,vertical:(a=e.vertical)!==null&&a!==void 0?a:pr.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:pr.verticalFill,x:R(e.x)?e.x:s.left,y:R(e.y)?e.y:s.top,width:R(e.width)?e.width:s.width,height:R(e.height)?e.height:s.height}),l=f.x,d=f.y,p=f.width,y=f.height,h=f.syncWithTicks,v=f.horizontalValues,b=f.verticalValues,w=oF(),x=uF();if(!R(p)||p<=0||!R(y)||y<=0||!R(l)||l!==+l||!R(d)||d!==+d)return null;var A=f.verticalCoordinatesGenerator||w3,g=f.horizontalCoordinatesGenerator||O3,m=f.horizontalPoints,O=f.verticalPoints;if((!m||!m.length)&&V(g)){var S=v&&v.length,_=g({yAxis:x?je(je({},x),{},{ticks:S?v:x.ticks}):void 0,width:u,height:c,offset:s},S?!0:h);nt(Array.isArray(_),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(ar(_),"]")),Array.isArray(_)&&(m=_)}if((!O||!O.length)&&V(A)){var E=b&&b.length,$=A({xAxis:w?je(je({},w),{},{ticks:E?b:w.ticks}):void 0,width:u,height:c,offset:s},E?!0:h);nt(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(ar($),"]")),Array.isArray($)&&(O=$)}return P.createElement("g",{className:"recharts-cartesian-grid"},P.createElement(v3,{fill:f.fill,fillOpacity:f.fillOpacity,x:f.x,y:f.y,width:f.width,height:f.height,ry:f.ry}),P.createElement(g3,Jt({},f,{offset:s,horizontalPoints:m,xAxis:w,yAxis:x})),P.createElement(m3,Jt({},f,{offset:s,verticalPoints:O,xAxis:w,yAxis:x})),P.createElement(b3,Jt({},f,{horizontalPoints:m})),P.createElement(x3,Jt({},f,{verticalPoints:O})))}A3.displayName="CartesianGrid";function Ur(e){"@babel/helpers - typeof";return Ur=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ur(e)}function P3(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function S3(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ag(n.key),n)}}function _3(e,t,r){return S3(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function $3(e,t,r){return t=_a(t),T3(e,ng()?Reflect.construct(t,r||[],_a(e).constructor):t.apply(e,r))}function T3(e,t){if(t&&(Ur(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return E3(e)}function E3(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ng(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ng=function(){return!!e})()}function _a(e){return _a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},_a(e)}function j3(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&vc(e,t)}function vc(e,t){return vc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},vc(e,t)}function ig(e,t,r){return t=ag(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ag(e){var t=M3(e,"string");return Ur(t)=="symbol"?t:t+""}function M3(e,t){if(Ur(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ur(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function gc(){return gc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gc.apply(this,arguments)}function C3(e){var t=e.xAxisId,r=$s(),n=Ts(),i=Hv(t);return i==null?null:P.createElement(on,gc({},i,{className:J("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:r,height:n},ticksGenerator:function(o){return vt(o,!0)}}))}var Is=function(e){function t(){return P3(this,t),$3(this,t,arguments)}return j3(t,e),_3(t,[{key:"render",value:function(){return P.createElement(C3,this.props)}}])}(P.Component);ig(Is,"displayName","XAxis");ig(Is,"defaultProps",{allowDecimals:!0,hide:!1,orientation:"bottom",width:0,height:30,mirror:!1,xAxisId:0,tickCount:5,type:"category",padding:{left:0,right:0},allowDataOverflow:!1,scale:"auto",reversed:!1,allowDuplicatedCategory:!0});function qr(e){"@babel/helpers - typeof";return qr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qr(e)}function I3(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function k3(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,cg(n.key),n)}}function N3(e,t,r){return k3(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function D3(e,t,r){return t=$a(t),R3(e,og()?Reflect.construct(t,r||[],$a(e).constructor):t.apply(e,r))}function R3(e,t){if(t&&(qr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return L3(e)}function L3(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function og(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(og=function(){return!!e})()}function $a(e){return $a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},$a(e)}function B3(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&mc(e,t)}function mc(e,t){return mc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},mc(e,t)}function ug(e,t,r){return t=cg(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function cg(e){var t=F3(e,"string");return qr(t)=="symbol"?t:t+""}function F3(e,t){if(qr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(qr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function bc(){return bc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},bc.apply(this,arguments)}var W3=function(t){var r=t.yAxisId,n=$s(),i=Ts(),a=Gv(r);return a==null?null:P.createElement(on,bc({},a,{className:J("recharts-".concat(a.axisType," ").concat(a.axisType),a.className),viewBox:{x:0,y:0,width:n,height:i},ticksGenerator:function(u){return vt(u,!0)}}))},ks=function(e){function t(){return I3(this,t),D3(this,t,arguments)}return B3(t,e),N3(t,[{key:"render",value:function(){return P.createElement(W3,this.props)}}])}(P.Component);ug(ks,"displayName","YAxis");ug(ks,"defaultProps",{allowDuplicatedCategory:!0,allowDecimals:!0,hide:!1,orientation:"left",width:60,height:0,mirror:!1,yAxisId:0,tickCount:5,type:"number",padding:{top:0,bottom:0},allowDataOverflow:!1,scale:"auto",reversed:!1});function Sp(e){return H3(e)||q3(e)||U3(e)||z3()}function z3(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function U3(e,t){if(e){if(typeof e=="string")return xc(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return xc(e,t)}}function q3(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function H3(e){if(Array.isArray(e))return xc(e)}function xc(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var wc=function(t,r,n,i,a){var o=Ve(t,js),u=Ve(t,bo),c=[].concat(Sp(o),Sp(u)),s=Ve(t,wo),f="".concat(i,"Id"),l=i[0],d=r;if(c.length&&(d=c.reduce(function(h,v){if(v.props[f]===n&&ut(v.props,"extendDomain")&&R(v.props[l])){var b=v.props[l];return[Math.min(h[0],b),Math.max(h[1],b)]}return h},d)),s.length){var p="".concat(l,"1"),y="".concat(l,"2");d=s.reduce(function(h,v){if(v.props[f]===n&&ut(v.props,"extendDomain")&&R(v.props[p])&&R(v.props[y])){var b=v.props[p],w=v.props[y];return[Math.min(h[0],b,w),Math.max(h[1],b,w)]}return h},d)}return a&&a.length&&(d=a.reduce(function(h,v){return R(v)?[Math.min(h[0],v),Math.max(h[1],v)]:h},d)),d},sg={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function i(c,s,f){this.fn=c,this.context=s,this.once=f||!1}function a(c,s,f,l,d){if(typeof f!="function")throw new TypeError("The listener must be a function");var p=new i(f,l||c,d),y=r?r+s:s;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],p]:c._events[y].push(p):(c._events[y]=p,c._eventsCount++),c}function o(c,s){--c._eventsCount===0?c._events=new n:delete c._events[s]}function u(){this._events=new n,this._eventsCount=0}u.prototype.eventNames=function(){var s=[],f,l;if(this._eventsCount===0)return s;for(l in f=this._events)t.call(f,l)&&s.push(r?l.slice(1):l);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(f)):s},u.prototype.listeners=function(s){var f=r?r+s:s,l=this._events[f];if(!l)return[];if(l.fn)return[l.fn];for(var d=0,p=l.length,y=new Array(p);d<p;d++)y[d]=l[d].fn;return y},u.prototype.listenerCount=function(s){var f=r?r+s:s,l=this._events[f];return l?l.fn?1:l.length:0},u.prototype.emit=function(s,f,l,d,p,y){var h=r?r+s:s;if(!this._events[h])return!1;var v=this._events[h],b=arguments.length,w,x;if(v.fn){switch(v.once&&this.removeListener(s,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,f),!0;case 3:return v.fn.call(v.context,f,l),!0;case 4:return v.fn.call(v.context,f,l,d),!0;case 5:return v.fn.call(v.context,f,l,d,p),!0;case 6:return v.fn.call(v.context,f,l,d,p,y),!0}for(x=1,w=new Array(b-1);x<b;x++)w[x-1]=arguments[x];v.fn.apply(v.context,w)}else{var A=v.length,g;for(x=0;x<A;x++)switch(v[x].once&&this.removeListener(s,v[x].fn,void 0,!0),b){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,f);break;case 3:v[x].fn.call(v[x].context,f,l);break;case 4:v[x].fn.call(v[x].context,f,l,d);break;default:if(!w)for(g=1,w=new Array(b-1);g<b;g++)w[g-1]=arguments[g];v[x].fn.apply(v[x].context,w)}}return!0},u.prototype.on=function(s,f,l){return a(this,s,f,l,!1)},u.prototype.once=function(s,f,l){return a(this,s,f,l,!0)},u.prototype.removeListener=function(s,f,l,d){var p=r?r+s:s;if(!this._events[p])return this;if(!f)return o(this,p),this;var y=this._events[p];if(y.fn)y.fn===f&&(!d||y.once)&&(!l||y.context===l)&&o(this,p);else{for(var h=0,v=[],b=y.length;h<b;h++)(y[h].fn!==f||d&&!y[h].once||l&&y[h].context!==l)&&v.push(y[h]);v.length?this._events[p]=v.length===1?v[0]:v:o(this,p)}return this},u.prototype.removeAllListeners=function(s){var f;return s?(f=r?r+s:s,this._events[f]&&o(this,f)):(this._events=new n,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=r,u.EventEmitter=u,e.exports=u})(sg);var G3=sg.exports;const K3=ie(G3);var Vo=new K3,Yo="recharts.syncMouseEvents";function ni(e){"@babel/helpers - typeof";return ni=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ni(e)}function X3(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function V3(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,lg(n.key),n)}}function Y3(e,t,r){return V3(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Zo(e,t,r){return t=lg(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function lg(e){var t=Z3(e,"string");return ni(t)=="symbol"?t:t+""}function Z3(e,t){if(ni(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(ni(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var J3=function(){function e(){X3(this,e),Zo(this,"activeIndex",0),Zo(this,"coordinateList",[]),Zo(this,"layout","horizontal")}return Y3(e,[{key:"setDetails",value:function(r){var n,i=r.coordinateList,a=i===void 0?null:i,o=r.container,u=o===void 0?null:o,c=r.layout,s=c===void 0?null:c,f=r.offset,l=f===void 0?null:f,d=r.mouseHandlerCallback,p=d===void 0?null:d;this.coordinateList=(n=a??this.coordinateList)!==null&&n!==void 0?n:[],this.container=u??this.container,this.layout=s??this.layout,this.offset=l??this.offset,this.mouseHandlerCallback=p??this.mouseHandlerCallback,this.activeIndex=Math.min(Math.max(this.activeIndex,0),this.coordinateList.length-1)}},{key:"focus",value:function(){this.spoofMouse()}},{key:"keyboardEvent",value:function(r){if(this.coordinateList.length!==0)switch(r.key){case"ArrowRight":{if(this.layout!=="horizontal")return;this.activeIndex=Math.min(this.activeIndex+1,this.coordinateList.length-1),this.spoofMouse();break}case"ArrowLeft":{if(this.layout!=="horizontal")return;this.activeIndex=Math.max(this.activeIndex-1,0),this.spoofMouse();break}}}},{key:"setIndex",value:function(r){this.activeIndex=r}},{key:"spoofMouse",value:function(){var r,n;if(this.layout==="horizontal"&&this.coordinateList.length!==0){var i=this.container.getBoundingClientRect(),a=i.x,o=i.y,u=i.height,c=this.coordinateList[this.activeIndex].coordinate,s=((r=window)===null||r===void 0?void 0:r.scrollX)||0,f=((n=window)===null||n===void 0?void 0:n.scrollY)||0,l=a+c+s,d=o+this.offset.top+u/2+f;this.mouseHandlerCallback({pageX:l,pageY:d})}}}])}();function Q3(e,t,r){if(r==="number"&&t===!0&&Array.isArray(e)){var n=e==null?void 0:e[0],i=e==null?void 0:e[1];if(n&&i&&R(n)&&R(i))return!0}return!1}function eW(e,t,r,n){var i=n/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-i:r.left+.5,y:e==="horizontal"?r.top+.5:t.y-i,width:e==="horizontal"?n:r.width-1,height:e==="horizontal"?r.height-1:n}}function fg(e){var t=e.cx,r=e.cy,n=e.radius,i=e.startAngle,a=e.endAngle,o=le(t,r,n,i),u=le(t,r,n,a);return{points:[o,u],cx:t,cy:r,radius:n,startAngle:i,endAngle:a}}function tW(e,t,r){var n,i,a,o;if(e==="horizontal")n=t.x,a=n,i=r.top,o=r.top+r.height;else if(e==="vertical")i=t.y,o=i,n=r.left,a=r.left+r.width;else if(t.cx!=null&&t.cy!=null)if(e==="centric"){var u=t.cx,c=t.cy,s=t.innerRadius,f=t.outerRadius,l=t.angle,d=le(u,c,s,l),p=le(u,c,f,l);n=d.x,i=d.y,a=p.x,o=p.y}else return fg(t);return[{x:n,y:i},{x:a,y:o}]}function ii(e){"@babel/helpers - typeof";return ii=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ii(e)}function _p(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ti(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_p(Object(r),!0).forEach(function(n){rW(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_p(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function rW(e,t,r){return t=nW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nW(e){var t=iW(e,"string");return ii(t)=="symbol"?t:t+""}function iW(e,t){if(ii(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ii(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function aW(e){var t,r,n=e.element,i=e.tooltipEventType,a=e.isActive,o=e.activeCoordinate,u=e.activePayload,c=e.offset,s=e.activeTooltipIndex,f=e.tooltipAxisBandSize,l=e.layout,d=e.chartName,p=(t=n.props.cursor)!==null&&t!==void 0?t:(r=n.type.defaultProps)===null||r===void 0?void 0:r.cursor;if(!n||!p||!a||!o||d!=="ScatterChart"&&i!=="axis")return null;var y,h=qu;if(d==="ScatterChart")y=o,h=ID;else if(d==="BarChart")y=eW(l,o,c,f),h=Os;else if(l==="radial"){var v=fg(o),b=v.cx,w=v.cy,x=v.radius,A=v.startAngle,g=v.endAngle;y={cx:b,cy:w,startAngle:A,endAngle:g,innerRadius:x,outerRadius:x},h=lv}else y={points:tW(l,o,c)},h=qu;var m=Ti(Ti(Ti(Ti({stroke:"#ccc",pointerEvents:"none"},c),y),X(p,!1)),{},{payload:u,payloadIndex:s,className:J("recharts-tooltip-cursor",p.className)});return L.isValidElement(p)?L.cloneElement(p,m):L.createElement(h,m)}var oW=["item"],uW=["children","className","width","height","style","compact","title","desc"];function Hr(e){"@babel/helpers - typeof";return Hr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hr(e)}function mr(){return mr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},mr.apply(this,arguments)}function $p(e,t){return lW(e)||sW(e,t)||pg(e,t)||cW()}function cW(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sW(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(f){s=!0,i=f}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(s)throw i}}return u}}function lW(e){if(Array.isArray(e))return e}function Tp(e,t){if(e==null)return{};var r=fW(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function fW(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function dW(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pW(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,hg(n.key),n)}}function hW(e,t,r){return pW(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function yW(e,t,r){return t=Ta(t),vW(e,dg()?Reflect.construct(t,r,Ta(e).constructor):t.apply(e,r))}function vW(e,t){if(t&&(Hr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return gW(e)}function gW(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function dg(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(dg=function(){return!!e})()}function Ta(e){return Ta=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ta(e)}function mW(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Oc(e,t)}function Oc(e,t){return Oc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Oc(e,t)}function Gr(e){return wW(e)||xW(e)||pg(e)||bW()}function bW(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pg(e,t){if(e){if(typeof e=="string")return Ac(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Ac(e,t)}}function xW(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function wW(e){if(Array.isArray(e))return Ac(e)}function Ac(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Ep(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function j(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ep(Object(r),!0).forEach(function(n){H(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ep(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function H(e,t,r){return t=hg(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hg(e){var t=OW(e,"string");return Hr(t)=="symbol"?t:t+""}function OW(e,t){if(Hr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Hr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var AW={xAxis:["bottom","top"],yAxis:["left","right"]},PW={width:"100%",height:"100%"},yg={x:0,y:0};function Ei(e){return e}var SW=function(t,r){return r==="horizontal"?t.x:r==="vertical"?t.y:r==="centric"?t.angle:t.radius},_W=function(t,r,n,i){var a=r.find(function(f){return f&&f.index===n});if(a){if(t==="horizontal")return{x:a.coordinate,y:i.y};if(t==="vertical")return{x:i.x,y:a.coordinate};if(t==="centric"){var o=a.coordinate,u=i.radius;return j(j(j({},i),le(i.cx,i.cy,u,o)),{},{angle:o,radius:u})}var c=a.coordinate,s=i.angle;return j(j(j({},i),le(i.cx,i.cy,c,s)),{},{angle:s,radius:c})}return yg},Oo=function(t,r){var n=r.graphicalItems,i=r.dataStartIndex,a=r.dataEndIndex,o=(n??[]).reduce(function(u,c){var s=c.props.data;return s&&s.length?[].concat(Gr(u),Gr(s)):u},[]);return o.length>0?o:t&&t.length&&R(i)&&R(a)?t.slice(i,a+1):[]};function vg(e){return e==="number"?[0,"auto"]:void 0}var Pc=function(t,r,n,i){var a=t.graphicalItems,o=t.tooltipAxis,u=Oo(r,t);return n<0||!a||!a.length||n>=u.length?null:a.reduce(function(c,s){var f,l=(f=s.props.data)!==null&&f!==void 0?f:r;l&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(l=l.slice(t.dataStartIndex,t.dataEndIndex+1));var d;if(o.dataKey&&!o.allowDuplicatedCategory){var p=l===void 0?u:l;d=Jo(p,o.dataKey,i)}else d=l&&l[n]||u[n];return d?[].concat(Gr(c),[iv(s,d)]):c},[])},jp=function(t,r,n,i){var a=i||{x:t.chartX,y:t.chartY},o=SW(a,n),u=t.orderedTooltipTicks,c=t.tooltipAxis,s=t.tooltipTicks,f=nk(o,u,s,c);if(f>=0&&s){var l=s[f]&&s[f].value,d=Pc(t,r,f,l),p=_W(n,u,f,a);return{activeTooltipIndex:f,activeLabel:l,activePayload:d,activeCoordinate:p}}return null},$W=function(t,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,o=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.layout,l=t.children,d=t.stackOffset,p=Jy(f,a);return n.reduce(function(y,h){var v,b=h.type.defaultProps!==void 0?j(j({},h.type.defaultProps),h.props):h.props,w=b.type,x=b.dataKey,A=b.allowDataOverflow,g=b.allowDuplicatedCategory,m=b.scale,O=b.ticks,S=b.includeHidden,_=b[o];if(y[_])return y;var E=Oo(t.data,{graphicalItems:i.filter(function(z){var K,fe=o in z.props?z.props[o]:(K=z.type.defaultProps)===null||K===void 0?void 0:K[o];return fe===_}),dataStartIndex:c,dataEndIndex:s}),$=E.length,T,C,I;Q3(b.domain,A,w)&&(T=Bu(b.domain,null,A),p&&(w==="number"||m!=="auto")&&(I=xn(E,x,"category")));var M=vg(w);if(!T||T.length===0){var k,D=(k=b.domain)!==null&&k!==void 0?k:M;if(x){if(T=xn(E,x,w),w==="category"&&p){var B=V0(T);g&&B?(C=T,T=va(0,$)):g||(T=nd(D,T,h).reduce(function(z,K){return z.indexOf(K)>=0?z:[].concat(Gr(z),[K])},[]))}else if(w==="category")g?T=T.filter(function(z){return z!==""&&!Q(z)}):T=nd(D,T,h).reduce(function(z,K){return z.indexOf(K)>=0||K===""||Q(K)?z:[].concat(Gr(z),[K])},[]);else if(w==="number"){var F=ck(E,i.filter(function(z){var K,fe,ge=o in z.props?z.props[o]:(K=z.type.defaultProps)===null||K===void 0?void 0:K[o],Fe="hide"in z.props?z.props.hide:(fe=z.type.defaultProps)===null||fe===void 0?void 0:fe.hide;return ge===_&&(S||!Fe)}),x,a,f);F&&(T=F)}p&&(w==="number"||m!=="auto")&&(I=xn(E,x,"category"))}else p?T=va(0,$):u&&u[_]&&u[_].hasStack&&w==="number"?T=d==="expand"?[0,1]:nv(u[_].stackGroups,c,s):T=Zy(E,i.filter(function(z){var K=o in z.props?z.props[o]:z.type.defaultProps[o],fe="hide"in z.props?z.props.hide:z.type.defaultProps.hide;return K===_&&(S||!fe)}),w,f,!0);if(w==="number")T=wc(l,T,_,a,O),D&&(T=Bu(D,T,A));else if(w==="category"&&D){var q=D,G=T.every(function(z){return q.indexOf(z)>=0});G&&(T=q)}}return j(j({},y),{},H({},_,j(j({},b),{},{axisType:a,domain:T,categoricalDomain:I,duplicateDomain:C,originalDomain:(v=b.domain)!==null&&v!==void 0?v:M,isCategorical:p,layout:f})))},{})},TW=function(t,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,o=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.layout,l=t.children,d=Oo(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:s}),p=d.length,y=Jy(f,a),h=-1;return n.reduce(function(v,b){var w=b.type.defaultProps!==void 0?j(j({},b.type.defaultProps),b.props):b.props,x=w[o],A=vg("number");if(!v[x]){h++;var g;return y?g=va(0,p):u&&u[x]&&u[x].hasStack?(g=nv(u[x].stackGroups,c,s),g=wc(l,g,x,a)):(g=Bu(A,Zy(d,n.filter(function(m){var O,S,_=o in m.props?m.props[o]:(O=m.type.defaultProps)===null||O===void 0?void 0:O[o],E="hide"in m.props?m.props.hide:(S=m.type.defaultProps)===null||S===void 0?void 0:S.hide;return _===x&&!E}),"number",f),i.defaultProps.allowDataOverflow),g=wc(l,g,x,a)),j(j({},v),{},H({},x,j(j({axisType:a},i.defaultProps),{},{hide:!0,orientation:qe(AW,"".concat(a,".").concat(h%2),null),domain:g,originalDomain:A,isCategorical:y,layout:f})))}return v},{})},EW=function(t,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,o=r.graphicalItems,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.children,l="".concat(i,"Id"),d=Ve(f,a),p={};return d.length?p=$W(t,{axes:d,graphicalItems:o,axisType:i,axisIdKey:l,stackGroups:u,dataStartIndex:c,dataEndIndex:s}):o&&o.length&&(p=TW(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:l,stackGroups:u,dataStartIndex:c,dataEndIndex:s})),p},jW=function(t){var r=jt(t),n=vt(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:Xc(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:ia(r,n)}},Mp=function(t){var r=t.children,n=t.defaultShowTooltip,i=ze(r,Rr),a=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},MW=function(t){return!t||!t.length?!1:t.some(function(r){var n=gt(r&&r.type);return n&&n.indexOf("Bar")>=0})},Cp=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},CW=function(t,r){var n=t.props,i=t.graphicalItems,a=t.xAxisMap,o=a===void 0?{}:a,u=t.yAxisMap,c=u===void 0?{}:u,s=n.width,f=n.height,l=n.children,d=n.margin||{},p=ze(l,Rr),y=ze(l,xr),h=Object.keys(c).reduce(function(g,m){var O=c[m],S=O.orientation;return!O.mirror&&!O.hide?j(j({},g),{},H({},S,g[S]+O.width)):g},{left:d.left||0,right:d.right||0}),v=Object.keys(o).reduce(function(g,m){var O=o[m],S=O.orientation;return!O.mirror&&!O.hide?j(j({},g),{},H({},S,qe(g,"".concat(S))+O.height)):g},{top:d.top||0,bottom:d.bottom||0}),b=j(j({},v),h),w=b.bottom;p&&(b.bottom+=p.props.height||Rr.defaultProps.height),y&&r&&(b=ok(b,i,n,r));var x=s-b.left-b.right,A=f-b.top-b.bottom;return j(j({brushBottom:w},b),{},{width:Math.max(x,0),height:Math.max(A,0)})},IW=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},gg=function(t){var r=t.chartName,n=t.GraphicalChild,i=t.defaultTooltipEventType,a=i===void 0?"axis":i,o=t.validateTooltipEventTypes,u=o===void 0?["axis"]:o,c=t.axisComponents,s=t.legendContent,f=t.formatAxisMap,l=t.defaultProps,d=function(b,w){var x=w.graphicalItems,A=w.stackGroups,g=w.offset,m=w.updateId,O=w.dataStartIndex,S=w.dataEndIndex,_=b.barSize,E=b.layout,$=b.barGap,T=b.barCategoryGap,C=b.maxBarSize,I=Cp(E),M=I.numericAxisName,k=I.cateAxisName,D=MW(x),B=[];return x.forEach(function(F,q){var G=Oo(b.data,{graphicalItems:[F],dataStartIndex:O,dataEndIndex:S}),z=F.type.defaultProps!==void 0?j(j({},F.type.defaultProps),F.props):F.props,K=z.dataKey,fe=z.maxBarSize,ge=z["".concat(M,"Id")],Fe=z["".concat(k,"Id")],Bt={},De=c.reduce(function(Ft,Wt){var Ao=w["".concat(Wt.axisType,"Map")],Ns=z["".concat(Wt.axisType,"Id")];Ao&&Ao[Ns]||Wt.axisType==="zAxis"||ir();var Ds=Ao[Ns];return j(j({},Ft),{},H(H({},Wt.axisType,Ds),"".concat(Wt.axisType,"Ticks"),vt(Ds)))},Bt),W=De[k],Y=De["".concat(k,"Ticks")],Z=A&&A[ge]&&A[ge].hasStack&&gk(F,A[ge].stackGroups),N=gt(F.type).indexOf("Bar")>=0,ye=ia(W,Y),ee=[],xe=D&&ik({barSize:_,stackGroups:A,totalSize:IW(De,k)});if(N){var we,Re,$t=Q(fe)?C:fe,lr=(we=(Re=ia(W,Y,!0))!==null&&Re!==void 0?Re:$t)!==null&&we!==void 0?we:0;ee=ak({barGap:$,barCategoryGap:T,bandSize:lr!==ye?lr:ye,sizeList:xe[Fe],maxBarSize:$t}),lr!==ye&&(ee=ee.map(function(Ft){return j(j({},Ft),{},{position:j(j({},Ft.position),{},{offset:Ft.position.offset-lr/2})})}))}var hi=F&&F.type&&F.type.getComposedData;hi&&B.push({props:j(j({},hi(j(j({},De),{},{displayedData:G,props:b,dataKey:K,item:F,bandSize:ye,barPosition:ee,offset:g,stackedData:Z,layout:E,dataStartIndex:O,dataEndIndex:S}))),{},H(H(H({key:F.key||"item-".concat(q)},M,De[M]),k,De[k]),"animationId",m)),childIndex:ox(F,b.children),item:F})}),B},p=function(b,w){var x=b.props,A=b.dataStartIndex,g=b.dataEndIndex,m=b.updateId;if(!Ys({props:x}))return null;var O=x.children,S=x.layout,_=x.stackOffset,E=x.data,$=x.reverseStackOrder,T=Cp(S),C=T.numericAxisName,I=T.cateAxisName,M=Ve(O,n),k=yk(E,M,"".concat(C,"Id"),"".concat(I,"Id"),_,$),D=c.reduce(function(z,K){var fe="".concat(K.axisType,"Map");return j(j({},z),{},H({},fe,EW(x,j(j({},K),{},{graphicalItems:M,stackGroups:K.axisType===C&&k,dataStartIndex:A,dataEndIndex:g}))))},{}),B=CW(j(j({},D),{},{props:x,graphicalItems:M}),w==null?void 0:w.legendBBox);Object.keys(D).forEach(function(z){D[z]=f(x,D[z],B,z.replace("Map",""),r)});var F=D["".concat(I,"Map")],q=jW(F),G=d(x,j(j({},D),{},{dataStartIndex:A,dataEndIndex:g,updateId:m,graphicalItems:M,stackGroups:k,offset:B}));return j(j({formattedGraphicalItems:G,graphicalItems:M,offset:B,stackGroups:k},q),D)},y=function(v){function b(w){var x,A,g;return dW(this,b),g=yW(this,b,[w]),H(g,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),H(g,"accessibilityManager",new J3),H(g,"handleLegendBBoxUpdate",function(m){if(m){var O=g.state,S=O.dataStartIndex,_=O.dataEndIndex,E=O.updateId;g.setState(j({legendBBox:m},p({props:g.props,dataStartIndex:S,dataEndIndex:_,updateId:E},j(j({},g.state),{},{legendBBox:m}))))}}),H(g,"handleReceiveSyncEvent",function(m,O,S){if(g.props.syncId===m){if(S===g.eventEmitterSymbol&&typeof g.props.syncMethod!="function")return;g.applySyncEvent(O)}}),H(g,"handleBrushChange",function(m){var O=m.startIndex,S=m.endIndex;if(O!==g.state.dataStartIndex||S!==g.state.dataEndIndex){var _=g.state.updateId;g.setState(function(){return j({dataStartIndex:O,dataEndIndex:S},p({props:g.props,dataStartIndex:O,dataEndIndex:S,updateId:_},g.state))}),g.triggerSyncEvent({dataStartIndex:O,dataEndIndex:S})}}),H(g,"handleMouseEnter",function(m){var O=g.getMouseInfo(m);if(O){var S=j(j({},O),{},{isTooltipActive:!0});g.setState(S),g.triggerSyncEvent(S);var _=g.props.onMouseEnter;V(_)&&_(S,m)}}),H(g,"triggeredAfterMouseMove",function(m){var O=g.getMouseInfo(m),S=O?j(j({},O),{},{isTooltipActive:!0}):{isTooltipActive:!1};g.setState(S),g.triggerSyncEvent(S);var _=g.props.onMouseMove;V(_)&&_(S,m)}),H(g,"handleItemMouseEnter",function(m){g.setState(function(){return{isTooltipActive:!0,activeItem:m,activePayload:m.tooltipPayload,activeCoordinate:m.tooltipPosition||{x:m.cx,y:m.cy}}})}),H(g,"handleItemMouseLeave",function(){g.setState(function(){return{isTooltipActive:!1}})}),H(g,"handleMouseMove",function(m){m.persist(),g.throttleTriggeredAfterMouseMove(m)}),H(g,"handleMouseLeave",function(m){g.throttleTriggeredAfterMouseMove.cancel();var O={isTooltipActive:!1};g.setState(O),g.triggerSyncEvent(O);var S=g.props.onMouseLeave;V(S)&&S(O,m)}),H(g,"handleOuterEvent",function(m){var O=ax(m),S=qe(g.props,"".concat(O));if(O&&V(S)){var _,E;/.*touch.*/i.test(O)?E=g.getMouseInfo(m.changedTouches[0]):E=g.getMouseInfo(m),S((_=E)!==null&&_!==void 0?_:{},m)}}),H(g,"handleClick",function(m){var O=g.getMouseInfo(m);if(O){var S=j(j({},O),{},{isTooltipActive:!0});g.setState(S),g.triggerSyncEvent(S);var _=g.props.onClick;V(_)&&_(S,m)}}),H(g,"handleMouseDown",function(m){var O=g.props.onMouseDown;if(V(O)){var S=g.getMouseInfo(m);O(S,m)}}),H(g,"handleMouseUp",function(m){var O=g.props.onMouseUp;if(V(O)){var S=g.getMouseInfo(m);O(S,m)}}),H(g,"handleTouchMove",function(m){m.changedTouches!=null&&m.changedTouches.length>0&&g.throttleTriggeredAfterMouseMove(m.changedTouches[0])}),H(g,"handleTouchStart",function(m){m.changedTouches!=null&&m.changedTouches.length>0&&g.handleMouseDown(m.changedTouches[0])}),H(g,"handleTouchEnd",function(m){m.changedTouches!=null&&m.changedTouches.length>0&&g.handleMouseUp(m.changedTouches[0])}),H(g,"handleDoubleClick",function(m){var O=g.props.onDoubleClick;if(V(O)){var S=g.getMouseInfo(m);O(S,m)}}),H(g,"handleContextMenu",function(m){var O=g.props.onContextMenu;if(V(O)){var S=g.getMouseInfo(m);O(S,m)}}),H(g,"triggerSyncEvent",function(m){g.props.syncId!==void 0&&Vo.emit(Yo,g.props.syncId,m,g.eventEmitterSymbol)}),H(g,"applySyncEvent",function(m){var O=g.props,S=O.layout,_=O.syncMethod,E=g.state.updateId,$=m.dataStartIndex,T=m.dataEndIndex;if(m.dataStartIndex!==void 0||m.dataEndIndex!==void 0)g.setState(j({dataStartIndex:$,dataEndIndex:T},p({props:g.props,dataStartIndex:$,dataEndIndex:T,updateId:E},g.state)));else if(m.activeTooltipIndex!==void 0){var C=m.chartX,I=m.chartY,M=m.activeTooltipIndex,k=g.state,D=k.offset,B=k.tooltipTicks;if(!D)return;if(typeof _=="function")M=_(B,m);else if(_==="value"){M=-1;for(var F=0;F<B.length;F++)if(B[F].value===m.activeLabel){M=F;break}}var q=j(j({},D),{},{x:D.left,y:D.top}),G=Math.min(C,q.x+q.width),z=Math.min(I,q.y+q.height),K=B[M]&&B[M].value,fe=Pc(g.state,g.props.data,M),ge=B[M]?{x:S==="horizontal"?B[M].coordinate:G,y:S==="horizontal"?z:B[M].coordinate}:yg;g.setState(j(j({},m),{},{activeLabel:K,activeCoordinate:ge,activePayload:fe,activeTooltipIndex:M}))}else g.setState(m)}),H(g,"renderCursor",function(m){var O,S=g.state,_=S.isTooltipActive,E=S.activeCoordinate,$=S.activePayload,T=S.offset,C=S.activeTooltipIndex,I=S.tooltipAxisBandSize,M=g.getTooltipEventType(),k=(O=m.props.active)!==null&&O!==void 0?O:_,D=g.props.layout,B=m.key||"_recharts-cursor";return P.createElement(aW,{key:B,activeCoordinate:E,activePayload:$,activeTooltipIndex:C,chartName:r,element:m,isActive:k,layout:D,offset:T,tooltipAxisBandSize:I,tooltipEventType:M})}),H(g,"renderPolarAxis",function(m,O,S){var _=qe(m,"type.axisType"),E=qe(g.state,"".concat(_,"Map")),$=m.type.defaultProps,T=$!==void 0?j(j({},$),m.props):m.props,C=E&&E[T["".concat(_,"Id")]];return L.cloneElement(m,j(j({},C),{},{className:J(_,C.className),key:m.key||"".concat(O,"-").concat(S),ticks:vt(C,!0)}))}),H(g,"renderPolarGrid",function(m){var O=m.props,S=O.radialLines,_=O.polarAngles,E=O.polarRadius,$=g.state,T=$.radiusAxisMap,C=$.angleAxisMap,I=jt(T),M=jt(C),k=M.cx,D=M.cy,B=M.innerRadius,F=M.outerRadius;return L.cloneElement(m,{polarAngles:Array.isArray(_)?_:vt(M,!0).map(function(q){return q.coordinate}),polarRadius:Array.isArray(E)?E:vt(I,!0).map(function(q){return q.coordinate}),cx:k,cy:D,innerRadius:B,outerRadius:F,key:m.key||"polar-grid",radialLines:S})}),H(g,"renderLegend",function(){var m=g.state.formattedGraphicalItems,O=g.props,S=O.children,_=O.width,E=O.height,$=g.props.margin||{},T=_-($.left||0)-($.right||0),C=Vy({children:S,formattedGraphicalItems:m,legendWidth:T,legendContent:s});if(!C)return null;var I=C.item,M=Tp(C,oW);return L.cloneElement(I,j(j({},M),{},{chartWidth:_,chartHeight:E,margin:$,onBBoxUpdate:g.handleLegendBBoxUpdate}))}),H(g,"renderTooltip",function(){var m,O=g.props,S=O.children,_=O.accessibilityLayer,E=ze(S,dt);if(!E)return null;var $=g.state,T=$.isTooltipActive,C=$.activeCoordinate,I=$.activePayload,M=$.activeLabel,k=$.offset,D=(m=E.props.active)!==null&&m!==void 0?m:T;return L.cloneElement(E,{viewBox:j(j({},k),{},{x:k.left,y:k.top}),active:D,label:M,payload:D?I:[],coordinate:C,accessibilityLayer:_})}),H(g,"renderBrush",function(m){var O=g.props,S=O.margin,_=O.data,E=g.state,$=E.offset,T=E.dataStartIndex,C=E.dataEndIndex,I=E.updateId;return L.cloneElement(m,{key:m.key||"_recharts-brush",onChange:Pi(g.handleBrushChange,m.props.onChange),data:_,x:R(m.props.x)?m.props.x:$.left,y:R(m.props.y)?m.props.y:$.top+$.height+$.brushBottom-(S.bottom||0),width:R(m.props.width)?m.props.width:$.width,startIndex:T,endIndex:C,updateId:"brush-".concat(I)})}),H(g,"renderReferenceElement",function(m,O,S){if(!m)return null;var _=g,E=_.clipPathId,$=g.state,T=$.xAxisMap,C=$.yAxisMap,I=$.offset,M=m.type.defaultProps||{},k=m.props,D=k.xAxisId,B=D===void 0?M.xAxisId:D,F=k.yAxisId,q=F===void 0?M.yAxisId:F;return L.cloneElement(m,{key:m.key||"".concat(O,"-").concat(S),xAxis:T[B],yAxis:C[q],viewBox:{x:I.left,y:I.top,width:I.width,height:I.height},clipPathId:E})}),H(g,"renderActivePoints",function(m){var O=m.item,S=m.activePoint,_=m.basePoint,E=m.childIndex,$=m.isRange,T=[],C=O.props.key,I=O.item.type.defaultProps!==void 0?j(j({},O.item.type.defaultProps),O.item.props):O.item.props,M=I.activeDot,k=I.dataKey,D=j(j({index:E,dataKey:k,cx:S.x,cy:S.y,r:4,fill:ws(O.item),strokeWidth:2,stroke:"#fff",payload:S.payload,value:S.value},X(M,!1)),Mi(M));return T.push(b.renderActiveDot(M,D,"".concat(C,"-activePoint-").concat(E))),_?T.push(b.renderActiveDot(M,j(j({},D),{},{cx:_.x,cy:_.y}),"".concat(C,"-basePoint-").concat(E))):$&&T.push(null),T}),H(g,"renderGraphicChild",function(m,O,S){var _=g.filterFormatItem(m,O,S);if(!_)return null;var E=g.getTooltipEventType(),$=g.state,T=$.isTooltipActive,C=$.tooltipAxis,I=$.activeTooltipIndex,M=$.activeLabel,k=g.props.children,D=ze(k,dt),B=_.props,F=B.points,q=B.isRange,G=B.baseLine,z=_.item.type.defaultProps!==void 0?j(j({},_.item.type.defaultProps),_.item.props):_.item.props,K=z.activeDot,fe=z.hide,ge=z.activeBar,Fe=z.activeShape,Bt=!!(!fe&&T&&D&&(K||ge||Fe)),De={};E!=="axis"&&D&&D.props.trigger==="click"?De={onClick:Pi(g.handleItemMouseEnter,m.props.onClick)}:E!=="axis"&&(De={onMouseLeave:Pi(g.handleItemMouseLeave,m.props.onMouseLeave),onMouseEnter:Pi(g.handleItemMouseEnter,m.props.onMouseEnter)});var W=L.cloneElement(m,j(j({},_.props),De));function Y(Wt){return typeof C.dataKey=="function"?C.dataKey(Wt.payload):null}if(Bt)if(I>=0){var Z,N;if(C.dataKey&&!C.allowDuplicatedCategory){var ye=typeof C.dataKey=="function"?Y:"payload.".concat(C.dataKey.toString());Z=Jo(F,ye,M),N=q&&G&&Jo(G,ye,M)}else Z=F==null?void 0:F[I],N=q&&G&&G[I];if(Fe||ge){var ee=m.props.activeIndex!==void 0?m.props.activeIndex:I;return[L.cloneElement(m,j(j(j({},_.props),De),{},{activeIndex:ee})),null,null]}if(!Q(Z))return[W].concat(Gr(g.renderActivePoints({item:_,activePoint:Z,basePoint:N,childIndex:I,isRange:q})))}else{var xe,we=(xe=g.getItemByXY(g.state.activeCoordinate))!==null&&xe!==void 0?xe:{graphicalItem:W},Re=we.graphicalItem,$t=Re.item,lr=$t===void 0?m:$t,hi=Re.childIndex,Ft=j(j(j({},_.props),De),{},{activeIndex:hi});return[L.cloneElement(lr,Ft),null,null]}return q?[W,null,null]:[W,null]}),H(g,"renderCustomized",function(m,O,S){return L.cloneElement(m,j(j({key:"recharts-customized-".concat(S)},g.props),g.state))}),H(g,"renderMap",{CartesianGrid:{handler:Ei,once:!0},ReferenceArea:{handler:g.renderReferenceElement},ReferenceLine:{handler:Ei},ReferenceDot:{handler:g.renderReferenceElement},XAxis:{handler:Ei},YAxis:{handler:Ei},Brush:{handler:g.renderBrush,once:!0},Bar:{handler:g.renderGraphicChild},Line:{handler:g.renderGraphicChild},Area:{handler:g.renderGraphicChild},Radar:{handler:g.renderGraphicChild},RadialBar:{handler:g.renderGraphicChild},Scatter:{handler:g.renderGraphicChild},Pie:{handler:g.renderGraphicChild},Funnel:{handler:g.renderGraphicChild},Tooltip:{handler:g.renderCursor,once:!0},PolarGrid:{handler:g.renderPolarGrid,once:!0},PolarAngleAxis:{handler:g.renderPolarAxis},PolarRadiusAxis:{handler:g.renderPolarAxis},Customized:{handler:g.renderCustomized}}),g.clipPathId="".concat((x=w.id)!==null&&x!==void 0?x:ci("recharts"),"-clip"),g.throttleTriggeredAfterMouseMove=Xh(g.triggeredAfterMouseMove,(A=w.throttleDelay)!==null&&A!==void 0?A:1e3/60),g.state={},g}return mW(b,v),hW(b,[{key:"componentDidMount",value:function(){var x,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(x=this.props.margin.left)!==null&&x!==void 0?x:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var x=this.props,A=x.children,g=x.data,m=x.height,O=x.layout,S=ze(A,dt);if(S){var _=S.props.defaultIndex;if(!(typeof _!="number"||_<0||_>this.state.tooltipTicks.length-1)){var E=this.state.tooltipTicks[_]&&this.state.tooltipTicks[_].value,$=Pc(this.state,g,_,E),T=this.state.tooltipTicks[_].coordinate,C=(this.state.offset.top+m)/2,I=O==="horizontal",M=I?{x:T,y:C}:{y:T,x:C},k=this.state.formattedGraphicalItems.find(function(B){var F=B.item;return F.type.name==="Scatter"});k&&(M=j(j({},M),k.props.points[_].tooltipPosition),$=k.props.points[_].tooltipPayload);var D={activeTooltipIndex:_,isTooltipActive:!0,activeLabel:E,activePayload:$,activeCoordinate:M};this.setState(D),this.renderCursor(S),this.accessibilityManager.setIndex(_)}}}},{key:"getSnapshotBeforeUpdate",value:function(x,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==x.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==x.margin){var g,m;this.accessibilityManager.setDetails({offset:{left:(g=this.props.margin.left)!==null&&g!==void 0?g:0,top:(m=this.props.margin.top)!==null&&m!==void 0?m:0}})}return null}},{key:"componentDidUpdate",value:function(x){eu([ze(x.children,dt)],[ze(this.props.children,dt)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=ze(this.props.children,dt);if(x&&typeof x.props.shared=="boolean"){var A=x.props.shared?"axis":"item";return u.indexOf(A)>=0?A:a}return a}},{key:"getMouseInfo",value:function(x){if(!this.container)return null;var A=this.container,g=A.getBoundingClientRect(),m=ME(g),O={chartX:Math.round(x.pageX-m.left),chartY:Math.round(x.pageY-m.top)},S=g.width/A.offsetWidth||1,_=this.inRange(O.chartX,O.chartY,S);if(!_)return null;var E=this.state,$=E.xAxisMap,T=E.yAxisMap,C=this.getTooltipEventType();if(C!=="axis"&&$&&T){var I=jt($).scale,M=jt(T).scale,k=I&&I.invert?I.invert(O.chartX):null,D=M&&M.invert?M.invert(O.chartY):null;return j(j({},O),{},{xValue:k,yValue:D})}var B=jp(this.state,this.props.data,this.props.layout,_);return B?j(j({},O),B):null}},{key:"inRange",value:function(x,A){var g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,m=this.props.layout,O=x/g,S=A/g;if(m==="horizontal"||m==="vertical"){var _=this.state.offset,E=O>=_.left&&O<=_.left+_.width&&S>=_.top&&S<=_.top+_.height;return E?{x:O,y:S}:null}var $=this.state,T=$.angleAxisMap,C=$.radiusAxisMap;if(T&&C){var I=jt(T);return od({x:O,y:S},I)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,A=this.getTooltipEventType(),g=ze(x,dt),m={};g&&A==="axis"&&(g.props.trigger==="click"?m={onClick:this.handleClick}:m={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var O=Mi(this.props,this.handleOuterEvent);return j(j({},O),m)}},{key:"addListener",value:function(){Vo.on(Yo,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Vo.removeListener(Yo,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(x,A,g){for(var m=this.state.formattedGraphicalItems,O=0,S=m.length;O<S;O++){var _=m[O];if(_.item===x||_.props.key===x.key||A===gt(_.item.type)&&g===_.childIndex)return _}return null}},{key:"renderClipPath",value:function(){var x=this.clipPathId,A=this.state.offset,g=A.left,m=A.top,O=A.height,S=A.width;return P.createElement("defs",null,P.createElement("clipPath",{id:x},P.createElement("rect",{x:g,y:m,height:O,width:S})))}},{key:"getXScales",value:function(){var x=this.state.xAxisMap;return x?Object.entries(x).reduce(function(A,g){var m=$p(g,2),O=m[0],S=m[1];return j(j({},A),{},H({},O,S.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(A,g){var m=$p(g,2),O=m[0],S=m[1];return j(j({},A),{},H({},O,S.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(x){var A;return(A=this.state.xAxisMap)===null||A===void 0||(A=A[x])===null||A===void 0?void 0:A.scale}},{key:"getYScaleByAxisId",value:function(x){var A;return(A=this.state.yAxisMap)===null||A===void 0||(A=A[x])===null||A===void 0?void 0:A.scale}},{key:"getItemByXY",value:function(x){var A=this.state,g=A.formattedGraphicalItems,m=A.activeItem;if(g&&g.length)for(var O=0,S=g.length;O<S;O++){var _=g[O],E=_.props,$=_.item,T=$.type.defaultProps!==void 0?j(j({},$.type.defaultProps),$.props):$.props,C=gt($.type);if(C==="Bar"){var I=(E.data||[]).find(function(B){return pD(x,B)});if(I)return{graphicalItem:_,payload:I}}else if(C==="RadialBar"){var M=(E.data||[]).find(function(B){return od(x,B)});if(M)return{graphicalItem:_,payload:M}}else if(yo(_,m)||vo(_,m)||Jn(_,m)){var k=rL({graphicalItem:_,activeTooltipItem:m,itemData:T.data}),D=T.activeIndex===void 0?k:T.activeIndex;return{graphicalItem:j(j({},_),{},{childIndex:D}),payload:Jn(_,m)?T.data[k]:_.props.data[k]}}}return null}},{key:"render",value:function(){var x=this;if(!Ys(this))return null;var A=this.props,g=A.children,m=A.className,O=A.width,S=A.height,_=A.style,E=A.compact,$=A.title,T=A.desc,C=Tp(A,uW),I=X(C,!1);if(E)return P.createElement(dp,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},P.createElement(ru,mr({},I,{width:O,height:S,title:$,desc:T}),this.renderClipPath(),Js(g,this.renderMap)));if(this.props.accessibilityLayer){var M,k;I.tabIndex=(M=this.props.tabIndex)!==null&&M!==void 0?M:0,I.role=(k=this.props.role)!==null&&k!==void 0?k:"application",I.onKeyDown=function(B){x.accessibilityManager.keyboardEvent(B)},I.onFocus=function(){x.accessibilityManager.focus()}}var D=this.parseEventsOfWrapper();return P.createElement(dp,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},P.createElement("div",mr({className:J("recharts-wrapper",m),style:j({position:"relative",cursor:"default",width:O,height:S},_)},D,{ref:function(F){x.container=F}}),P.createElement(ru,mr({},I,{width:O,height:S,title:$,desc:T,style:PW}),this.renderClipPath(),Js(g,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(L.Component);H(y,"displayName",r),H(y,"defaultProps",j({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},l)),H(y,"getDerivedStateFromProps",function(v,b){var w=v.dataKey,x=v.data,A=v.children,g=v.width,m=v.height,O=v.layout,S=v.stackOffset,_=v.margin,E=b.dataStartIndex,$=b.dataEndIndex;if(b.updateId===void 0){var T=Mp(v);return j(j(j({},T),{},{updateId:0},p(j(j({props:v},T),{},{updateId:0}),b)),{},{prevDataKey:w,prevData:x,prevWidth:g,prevHeight:m,prevLayout:O,prevStackOffset:S,prevMargin:_,prevChildren:A})}if(w!==b.prevDataKey||x!==b.prevData||g!==b.prevWidth||m!==b.prevHeight||O!==b.prevLayout||S!==b.prevStackOffset||!br(_,b.prevMargin)){var C=Mp(v),I={chartX:b.chartX,chartY:b.chartY,isTooltipActive:b.isTooltipActive},M=j(j({},jp(b,x,O)),{},{updateId:b.updateId+1}),k=j(j(j({},C),I),M);return j(j(j({},k),p(j({props:v},k),b)),{},{prevDataKey:w,prevData:x,prevWidth:g,prevHeight:m,prevLayout:O,prevStackOffset:S,prevMargin:_,prevChildren:A})}if(!eu(A,b.prevChildren)){var D,B,F,q,G=ze(A,Rr),z=G&&(D=(B=G.props)===null||B===void 0?void 0:B.startIndex)!==null&&D!==void 0?D:E,K=G&&(F=(q=G.props)===null||q===void 0?void 0:q.endIndex)!==null&&F!==void 0?F:$,fe=z!==E||K!==$,ge=!Q(x),Fe=ge&&!fe?b.updateId:b.updateId+1;return j(j({updateId:Fe},p(j(j({props:v},b),{},{updateId:Fe,dataStartIndex:z,dataEndIndex:K}),b)),{},{prevChildren:A,dataStartIndex:z,dataEndIndex:K})}return null}),H(y,"renderActiveDot",function(v,b,w){var x;return L.isValidElement(v)?x=L.cloneElement(v,b):V(v)?x=v(b):x=P.createElement(As,b),P.createElement(ne,{className:"recharts-active-dot",key:w},x)});var h=L.forwardRef(function(b,w){return P.createElement(y,mr({},b,{ref:w}))});return h.displayName=y.displayName,h},LW=gg({chartName:"BarChart",GraphicalChild:an,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Is},{axisType:"yAxis",AxisComp:ks}],formatAxisMap:NB}),BW=gg({chartName:"PieChart",GraphicalChild:Lt,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:ho},{axisType:"radiusAxis",AxisComp:fo}],formatAxisMap:$k,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}});export{LW as B,Yc as C,BW as P,RW as R,dt as T,Is as X,ks as Y,Lt as a,A3 as b,an as c,DW as d}; diff --git a/pkg/ui/frontend/dist/assets/date-utils-B6syNIuD.js b/pkg/ui/frontend/dist/assets/date-utils-B6syNIuD.js new file mode 100644 index 0000000000000..a80c5673dc8f6 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/date-utils-B6syNIuD.js @@ -0,0 +1,5 @@ +var Ir=Object.defineProperty;var Rr=(a,r,t)=>r in a?Ir(a,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[r]=t;var y=(a,r,t)=>Rr(a,typeof r!="symbol"?r+"":r,t);import{c as Z}from"./ui-utils-BNSC_Jv-.js";import{r as v,R as Fr,b as m,d as Lr}from"./react-core-D_V7s-9r.js";import{s as Wr,j as Ge,t as Ar,v as ft,w as Hr,x as $r,y as Qr,z as Br}from"./radix-core-ByqQ8fsu.js";function C(a){const r=Object.prototype.toString.call(a);return a instanceof Date||typeof a=="object"&&r==="[object Date]"?new a.constructor(+a):typeof a=="number"||r==="[object Number]"||typeof a=="string"||r==="[object String]"?new Date(a):new Date(NaN)}function oe(a,r){return a instanceof Date?new a.constructor(r):new Date(r)}function qr(a,r){const t=C(a);return isNaN(r)?oe(a,NaN):(r&&t.setDate(t.getDate()+r),t)}function Kr(a,r){const t=C(a);if(isNaN(r))return oe(a,NaN);if(!r)return t;const e=t.getDate(),n=oe(a,t.getTime());n.setMonth(t.getMonth()+r+1,0);const s=n.getDate();return e>=s?n:(t.setFullYear(n.getFullYear(),n.getMonth(),e),t)}function ze(a,r){const{years:t=0,months:e=0,weeks:n=0,days:s=0,hours:o=0,minutes:i=0,seconds:c=0}=r,u=C(a),l=e||t?Kr(u,e+t*12):u,d=s||n?qr(l,s+n*7):l,f=i+o*60,h=(c+f*60)*1e3;return oe(a,d.getTime()+h)}const Jn=6048e5,Vr=864e5,it=6e4,rn=36e5,mn=525600,Qe=43200,xt=1440;let Ur={};function Le(){return Ur}function ct(a,r){var i,c,u,l;const t=Le(),e=(r==null?void 0:r.weekStartsOn)??((c=(i=r==null?void 0:r.locale)==null?void 0:i.options)==null?void 0:c.weekStartsOn)??t.weekStartsOn??((l=(u=t.locale)==null?void 0:u.options)==null?void 0:l.weekStartsOn)??0,n=C(a),s=n.getDay(),o=(s<e?7:0)+s-e;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function St(a){return ct(a,{weekStartsOn:1})}function er(a){const r=C(a),t=r.getFullYear(),e=oe(a,0);e.setFullYear(t+1,0,4),e.setHours(0,0,0,0);const n=St(e),s=oe(a,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const o=St(s);return r.getTime()>=n.getTime()?t+1:r.getTime()>=o.getTime()?t:t-1}function gn(a){const r=C(a);return r.setHours(0,0,0,0),r}function qe(a){const r=C(a),t=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return t.setUTCFullYear(r.getFullYear()),+a-+t}function tr(a,r){const t=gn(a),e=gn(r),n=+t-qe(t),s=+e-qe(e);return Math.round((n-s)/Vr)}function jr(a){const r=er(a),t=oe(a,0);return t.setFullYear(r,0,4),t.setHours(0,0,0,0),St(t)}function Ne(a,r){const t=C(a),e=C(r),n=t.getTime()-e.getTime();return n<0?-1:n>0?1:n}function nr(a){return oe(a,Date.now())}function Xr(a){return a instanceof Date||typeof a=="object"&&Object.prototype.toString.call(a)==="[object Date]"}function Gr(a){if(!Xr(a)&&typeof a!="number")return!1;const r=C(a);return!isNaN(Number(r))}function zr(a,r){const t=C(a),e=C(r),n=t.getFullYear()-e.getFullYear(),s=t.getMonth()-e.getMonth();return n*12+s}function Zr(a,r){const t=C(a),e=C(r);return t.getFullYear()-e.getFullYear()}function Jr(a,r){const t=C(a),e=C(r),n=wn(t,e),s=Math.abs(tr(t,e));t.setDate(t.getDate()-n*s);const o=+(wn(t,e)===-n),i=n*(s-o);return i===0?0:i}function wn(a,r){const t=a.getFullYear()-r.getFullYear()||a.getMonth()-r.getMonth()||a.getDate()-r.getDate()||a.getHours()-r.getHours()||a.getMinutes()-r.getMinutes()||a.getSeconds()-r.getSeconds()||a.getMilliseconds()-r.getMilliseconds();return t<0?-1:t>0?1:t}function Ft(a){return r=>{const e=(a?Math[a]:Math.trunc)(r);return e===0?0:e}}function an(a,r){return+C(a)-+C(r)}function ea(a,r,t){const e=an(a,r)/rn;return Ft(t==null?void 0:t.roundingMethod)(e)}function ta(a,r,t){const e=an(a,r)/it;return Ft(t==null?void 0:t.roundingMethod)(e)}function na(a){const r=C(a);return r.setHours(23,59,59,999),r}function ra(a){const r=C(a),t=r.getMonth();return r.setFullYear(r.getFullYear(),t+1,0),r.setHours(23,59,59,999),r}function aa(a){const r=C(a);return+na(r)==+ra(r)}function rr(a,r){const t=C(a),e=C(r),n=Ne(t,e),s=Math.abs(zr(t,e));let o;if(s<1)o=0;else{t.getMonth()===1&&t.getDate()>27&&t.setDate(30),t.setMonth(t.getMonth()-n*s);let i=Ne(t,e)===-n;aa(C(a))&&s===1&&Ne(a,e)===1&&(i=!1),o=n*(s-Number(i))}return o===0?0:o}function ar(a,r,t){const e=an(a,r)/1e3;return Ft(t==null?void 0:t.roundingMethod)(e)}function sa(a,r){const t=C(a),e=C(r),n=Ne(t,e),s=Math.abs(Zr(t,e));t.setFullYear(1584),e.setFullYear(1584);const o=Ne(t,e)===-n,i=n*(s-+o);return i===0?0:i}function oa(a){const r=C(a),t=oe(a,0);return t.setFullYear(r.getFullYear(),0,1),t.setHours(0,0,0,0),t}const ia={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},ca=(a,r,t)=>{let e;const n=ia[a];return typeof n=="string"?e=n:r===1?e=n.one:e=n.other.replace("{{count}}",r.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+e:e+" ago":e};function Bt(a){return(r={})=>{const t=r.width?String(r.width):a.defaultWidth;return a.formats[t]||a.formats[a.defaultWidth]}}const ua={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},la={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},da={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},fa={date:Bt({formats:ua,defaultWidth:"full"}),time:Bt({formats:la,defaultWidth:"full"}),dateTime:Bt({formats:da,defaultWidth:"full"})},pa={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ha=(a,r,t,e)=>pa[a];function Ze(a){return(r,t)=>{const e=t!=null&&t.context?String(t.context):"standalone";let n;if(e==="formatting"&&a.formattingValues){const o=a.defaultFormattingWidth||a.defaultWidth,i=t!=null&&t.width?String(t.width):o;n=a.formattingValues[i]||a.formattingValues[o]}else{const o=a.defaultWidth,i=t!=null&&t.width?String(t.width):a.defaultWidth;n=a.values[i]||a.values[o]}const s=a.argumentCallback?a.argumentCallback(r):r;return n[s]}}const ma={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ga={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},wa={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Da={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},ya={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},va={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},ba=(a,r)=>{const t=Number(a),e=t%100;if(e>20||e<10)switch(e%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},ka={ordinalNumber:ba,era:Ze({values:ma,defaultWidth:"wide"}),quarter:Ze({values:ga,defaultWidth:"wide",argumentCallback:a=>a-1}),month:Ze({values:wa,defaultWidth:"wide"}),day:Ze({values:Da,defaultWidth:"wide"}),dayPeriod:Ze({values:ya,defaultWidth:"wide",formattingValues:va,defaultFormattingWidth:"wide"})};function Je(a){return(r,t={})=>{const e=t.width,n=e&&a.matchPatterns[e]||a.matchPatterns[a.defaultMatchWidth],s=r.match(n);if(!s)return null;const o=s[0],i=e&&a.parsePatterns[e]||a.parsePatterns[a.defaultParseWidth],c=Array.isArray(i)?Ma(i,d=>d.test(o)):_a(i,d=>d.test(o));let u;u=a.valueCallback?a.valueCallback(c):c,u=t.valueCallback?t.valueCallback(u):u;const l=r.slice(o.length);return{value:u,rest:l}}}function _a(a,r){for(const t in a)if(Object.prototype.hasOwnProperty.call(a,t)&&r(a[t]))return t}function Ma(a,r){for(let t=0;t<a.length;t++)if(r(a[t]))return t}function xa(a){return(r,t={})=>{const e=r.match(a.matchPattern);if(!e)return null;const n=e[0],s=r.match(a.parsePattern);if(!s)return null;let o=a.valueCallback?a.valueCallback(s[0]):s[0];o=t.valueCallback?t.valueCallback(o):o;const i=r.slice(n.length);return{value:o,rest:i}}}const Sa=/^(\d+)(th|st|nd|rd)?/i,Ca=/\d+/i,Pa={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Ta={any:[/^b/i,/^(a|c)/i]},Oa={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Ea={any:[/1/i,/2/i,/3/i,/4/i]},Na={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Ya={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Ia={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Ra={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Fa={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},La={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Wa={ordinalNumber:xa({matchPattern:Sa,parsePattern:Ca,valueCallback:a=>parseInt(a,10)}),era:Je({matchPatterns:Pa,defaultMatchWidth:"wide",parsePatterns:Ta,defaultParseWidth:"any"}),quarter:Je({matchPatterns:Oa,defaultMatchWidth:"wide",parsePatterns:Ea,defaultParseWidth:"any",valueCallback:a=>a+1}),month:Je({matchPatterns:Na,defaultMatchWidth:"wide",parsePatterns:Ya,defaultParseWidth:"any"}),day:Je({matchPatterns:Ia,defaultMatchWidth:"wide",parsePatterns:Ra,defaultParseWidth:"any"}),dayPeriod:Je({matchPatterns:Fa,defaultMatchWidth:"any",parsePatterns:La,defaultParseWidth:"any"})},Lt={code:"en-US",formatDistance:ca,formatLong:fa,formatRelative:ha,localize:ka,match:Wa,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Aa(a){const r=C(a);return tr(r,oa(r))+1}function Ha(a){const r=C(a),t=+St(r)-+jr(r);return Math.round(t/Jn)+1}function sr(a,r){var l,d,f,p;const t=C(a),e=t.getFullYear(),n=Le(),s=(r==null?void 0:r.firstWeekContainsDate)??((d=(l=r==null?void 0:r.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??n.firstWeekContainsDate??((p=(f=n.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,o=oe(a,0);o.setFullYear(e+1,0,s),o.setHours(0,0,0,0);const i=ct(o,r),c=oe(a,0);c.setFullYear(e,0,s),c.setHours(0,0,0,0);const u=ct(c,r);return t.getTime()>=i.getTime()?e+1:t.getTime()>=u.getTime()?e:e-1}function $a(a,r){var i,c,u,l;const t=Le(),e=(r==null?void 0:r.firstWeekContainsDate)??((c=(i=r==null?void 0:r.locale)==null?void 0:i.options)==null?void 0:c.firstWeekContainsDate)??t.firstWeekContainsDate??((l=(u=t.locale)==null?void 0:u.options)==null?void 0:l.firstWeekContainsDate)??1,n=sr(a,r),s=oe(a,0);return s.setFullYear(n,0,e),s.setHours(0,0,0,0),ct(s,r)}function Qa(a,r){const t=C(a),e=+ct(t,r)-+$a(t,r);return Math.round(e/Jn)+1}function T(a,r){const t=a<0?"-":"",e=Math.abs(a).toString().padStart(r,"0");return t+e}const _e={y(a,r){const t=a.getFullYear(),e=t>0?t:1-t;return T(r==="yy"?e%100:e,r.length)},M(a,r){const t=a.getMonth();return r==="M"?String(t+1):T(t+1,2)},d(a,r){return T(a.getDate(),r.length)},a(a,r){const t=a.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(a,r){return T(a.getHours()%12||12,r.length)},H(a,r){return T(a.getHours(),r.length)},m(a,r){return T(a.getMinutes(),r.length)},s(a,r){return T(a.getSeconds(),r.length)},S(a,r){const t=r.length,e=a.getMilliseconds(),n=Math.trunc(e*Math.pow(10,t-3));return T(n,r.length)}},Ae={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Dn={G:function(a,r,t){const e=a.getFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return t.era(e,{width:"abbreviated"});case"GGGGG":return t.era(e,{width:"narrow"});case"GGGG":default:return t.era(e,{width:"wide"})}},y:function(a,r,t){if(r==="yo"){const e=a.getFullYear(),n=e>0?e:1-e;return t.ordinalNumber(n,{unit:"year"})}return _e.y(a,r)},Y:function(a,r,t,e){const n=sr(a,e),s=n>0?n:1-n;if(r==="YY"){const o=s%100;return T(o,2)}return r==="Yo"?t.ordinalNumber(s,{unit:"year"}):T(s,r.length)},R:function(a,r){const t=er(a);return T(t,r.length)},u:function(a,r){const t=a.getFullYear();return T(t,r.length)},Q:function(a,r,t){const e=Math.ceil((a.getMonth()+1)/3);switch(r){case"Q":return String(e);case"QQ":return T(e,2);case"Qo":return t.ordinalNumber(e,{unit:"quarter"});case"QQQ":return t.quarter(e,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(e,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(e,{width:"wide",context:"formatting"})}},q:function(a,r,t){const e=Math.ceil((a.getMonth()+1)/3);switch(r){case"q":return String(e);case"qq":return T(e,2);case"qo":return t.ordinalNumber(e,{unit:"quarter"});case"qqq":return t.quarter(e,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(e,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(e,{width:"wide",context:"standalone"})}},M:function(a,r,t){const e=a.getMonth();switch(r){case"M":case"MM":return _e.M(a,r);case"Mo":return t.ordinalNumber(e+1,{unit:"month"});case"MMM":return t.month(e,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(e,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(e,{width:"wide",context:"formatting"})}},L:function(a,r,t){const e=a.getMonth();switch(r){case"L":return String(e+1);case"LL":return T(e+1,2);case"Lo":return t.ordinalNumber(e+1,{unit:"month"});case"LLL":return t.month(e,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(e,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(e,{width:"wide",context:"standalone"})}},w:function(a,r,t,e){const n=Qa(a,e);return r==="wo"?t.ordinalNumber(n,{unit:"week"}):T(n,r.length)},I:function(a,r,t){const e=Ha(a);return r==="Io"?t.ordinalNumber(e,{unit:"week"}):T(e,r.length)},d:function(a,r,t){return r==="do"?t.ordinalNumber(a.getDate(),{unit:"date"}):_e.d(a,r)},D:function(a,r,t){const e=Aa(a);return r==="Do"?t.ordinalNumber(e,{unit:"dayOfYear"}):T(e,r.length)},E:function(a,r,t){const e=a.getDay();switch(r){case"E":case"EE":case"EEE":return t.day(e,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(e,{width:"short",context:"formatting"});case"EEEE":default:return t.day(e,{width:"wide",context:"formatting"})}},e:function(a,r,t,e){const n=a.getDay(),s=(n-e.weekStartsOn+8)%7||7;switch(r){case"e":return String(s);case"ee":return T(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});case"eeee":default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(a,r,t,e){const n=a.getDay(),s=(n-e.weekStartsOn+8)%7||7;switch(r){case"c":return String(s);case"cc":return T(s,r.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});case"cccc":default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(a,r,t){const e=a.getDay(),n=e===0?7:e;switch(r){case"i":return String(n);case"ii":return T(n,r.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(e,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(e,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(e,{width:"short",context:"formatting"});case"iiii":default:return t.day(e,{width:"wide",context:"formatting"})}},a:function(a,r,t){const n=a.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(a,r,t){const e=a.getHours();let n;switch(e===12?n=Ae.noon:e===0?n=Ae.midnight:n=e/12>=1?"pm":"am",r){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(a,r,t){const e=a.getHours();let n;switch(e>=17?n=Ae.evening:e>=12?n=Ae.afternoon:e>=4?n=Ae.morning:n=Ae.night,r){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(a,r,t){if(r==="ho"){let e=a.getHours()%12;return e===0&&(e=12),t.ordinalNumber(e,{unit:"hour"})}return _e.h(a,r)},H:function(a,r,t){return r==="Ho"?t.ordinalNumber(a.getHours(),{unit:"hour"}):_e.H(a,r)},K:function(a,r,t){const e=a.getHours()%12;return r==="Ko"?t.ordinalNumber(e,{unit:"hour"}):T(e,r.length)},k:function(a,r,t){let e=a.getHours();return e===0&&(e=24),r==="ko"?t.ordinalNumber(e,{unit:"hour"}):T(e,r.length)},m:function(a,r,t){return r==="mo"?t.ordinalNumber(a.getMinutes(),{unit:"minute"}):_e.m(a,r)},s:function(a,r,t){return r==="so"?t.ordinalNumber(a.getSeconds(),{unit:"second"}):_e.s(a,r)},S:function(a,r){return _e.S(a,r)},X:function(a,r,t){const e=a.getTimezoneOffset();if(e===0)return"Z";switch(r){case"X":return vn(e);case"XXXX":case"XX":return Te(e);case"XXXXX":case"XXX":default:return Te(e,":")}},x:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"x":return vn(e);case"xxxx":case"xx":return Te(e);case"xxxxx":case"xxx":default:return Te(e,":")}},O:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+yn(e,":");case"OOOO":default:return"GMT"+Te(e,":")}},z:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+yn(e,":");case"zzzz":default:return"GMT"+Te(e,":")}},t:function(a,r,t){const e=Math.trunc(a.getTime()/1e3);return T(e,r.length)},T:function(a,r,t){const e=a.getTime();return T(e,r.length)}};function yn(a,r=""){const t=a>0?"-":"+",e=Math.abs(a),n=Math.trunc(e/60),s=e%60;return s===0?t+String(n):t+String(n)+r+T(s,2)}function vn(a,r){return a%60===0?(a>0?"-":"+")+T(Math.abs(a)/60,2):Te(a,r)}function Te(a,r=""){const t=a>0?"-":"+",e=Math.abs(a),n=T(Math.trunc(e/60),2),s=T(e%60,2);return t+n+r+s}const bn=(a,r)=>{switch(a){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},or=(a,r)=>{switch(a){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},Ba=(a,r)=>{const t=a.match(/(P+)(p+)?/)||[],e=t[1],n=t[2];if(!n)return bn(a,r);let s;switch(e){case"P":s=r.dateTime({width:"short"});break;case"PP":s=r.dateTime({width:"medium"});break;case"PPP":s=r.dateTime({width:"long"});break;case"PPPP":default:s=r.dateTime({width:"full"});break}return s.replace("{{date}}",bn(e,r)).replace("{{time}}",or(n,r))},qa={p:or,P:Ba},Ka=/^D+$/,Va=/^Y+$/,Ua=["D","DD","YY","YYYY"];function ja(a){return Ka.test(a)}function Xa(a){return Va.test(a)}function Ga(a,r,t){const e=za(a,r,t);if(console.warn(e),Ua.includes(a))throw new RangeError(e)}function za(a,r,t){const e=a[0]==="Y"?"years":"days of the month";return`Use \`${a.toLowerCase()}\` instead of \`${a}\` (in \`${r}\`) for formatting ${e} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Za=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ja=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,es=/^'([^]*?)'?$/,ts=/''/g,ns=/[a-zA-Z]/;function ou(a,r,t){var l,d,f,p;const e=Le(),n=e.locale??Lt,s=e.firstWeekContainsDate??((d=(l=e.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??1,o=e.weekStartsOn??((p=(f=e.locale)==null?void 0:f.options)==null?void 0:p.weekStartsOn)??0,i=C(a);if(!Gr(i))throw new RangeError("Invalid time value");let c=r.match(Ja).map(h=>{const g=h[0];if(g==="p"||g==="P"){const w=qa[g];return w(h,n.formatLong)}return h}).join("").match(Za).map(h=>{if(h==="''")return{isToken:!1,value:"'"};const g=h[0];if(g==="'")return{isToken:!1,value:rs(h)};if(Dn[g])return{isToken:!0,value:h};if(g.match(ns))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:h}});n.localize.preprocessor&&(c=n.localize.preprocessor(i,c));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:n};return c.map(h=>{if(!h.isToken)return h.value;const g=h.value;(Xa(g)||ja(g))&&Ga(g,r,String(a));const w=Dn[g[0]];return w(i,g,n.localize,u)}).join("")}function rs(a){const r=a.match(es);return r?r[1].replace(ts,"'"):a}function as(a,r,t){const e=Le(),n=(t==null?void 0:t.locale)??e.locale??Lt,s=2520,o=Ne(a,r);if(isNaN(o))throw new RangeError("Invalid time value");const i=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:o});let c,u;o>0?(c=C(r),u=C(a)):(c=C(a),u=C(r));const l=ar(u,c),d=(qe(u)-qe(c))/1e3,f=Math.round((l-d)/60);let p;if(f<2)return t!=null&&t.includeSeconds?l<5?n.formatDistance("lessThanXSeconds",5,i):l<10?n.formatDistance("lessThanXSeconds",10,i):l<20?n.formatDistance("lessThanXSeconds",20,i):l<40?n.formatDistance("halfAMinute",0,i):l<60?n.formatDistance("lessThanXMinutes",1,i):n.formatDistance("xMinutes",1,i):f===0?n.formatDistance("lessThanXMinutes",1,i):n.formatDistance("xMinutes",f,i);if(f<45)return n.formatDistance("xMinutes",f,i);if(f<90)return n.formatDistance("aboutXHours",1,i);if(f<xt){const h=Math.round(f/60);return n.formatDistance("aboutXHours",h,i)}else{if(f<s)return n.formatDistance("xDays",1,i);if(f<Qe){const h=Math.round(f/xt);return n.formatDistance("xDays",h,i)}else if(f<Qe*2)return p=Math.round(f/Qe),n.formatDistance("aboutXMonths",p,i)}if(p=rr(u,c),p<12){const h=Math.round(f/Qe);return n.formatDistance("xMonths",h,i)}else{const h=p%12,g=Math.trunc(p/12);return h<3?n.formatDistance("aboutXYears",g,i):h<9?n.formatDistance("overXYears",g,i):n.formatDistance("almostXYears",g+1,i)}}function ss(a,r,t){const e=Le(),n=(t==null?void 0:t.locale)??e.locale??Lt,s=Ne(a,r);if(isNaN(s))throw new RangeError("Invalid time value");const o=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:s});let i,c;s>0?(i=C(r),c=C(a)):(i=C(a),c=C(r));const u=Ft((t==null?void 0:t.roundingMethod)??"round"),l=c.getTime()-i.getTime(),d=l/it,f=qe(c)-qe(i),p=(l-f)/it,h=t==null?void 0:t.unit;let g;if(h?g=h:d<1?g="second":d<60?g="minute":d<xt?g="hour":p<Qe?g="day":p<mn?g="month":g="year",g==="second"){const w=u(l/1e3);return n.formatDistance("xSeconds",w,o)}else if(g==="minute"){const w=u(d);return n.formatDistance("xMinutes",w,o)}else if(g==="hour"){const w=u(d/60);return n.formatDistance("xHours",w,o)}else if(g==="day"){const w=u(p/xt);return n.formatDistance("xDays",w,o)}else if(g==="month"){const w=u(p/Qe);return w===12&&h!=="month"?n.formatDistance("xYears",1,o):n.formatDistance("xMonths",w,o)}else{const w=u(p/mn);return n.formatDistance("xYears",w,o)}}function iu(a,r){return as(a,nr(a),r)}function cu(a,r){return ss(a,nr(a),r)}const os=["years","months","weeks","days","hours","minutes","seconds"];function uu(a,r){const t=Le(),e=(r==null?void 0:r.locale)??t.locale??Lt,n=(r==null?void 0:r.format)??os,s=(r==null?void 0:r.zero)??!1,o=(r==null?void 0:r.delimiter)??" ";return e.formatDistance?n.reduce((c,u)=>{const l=`x${u.replace(/(^.)/,f=>f.toUpperCase())}`,d=a[u];return d!==void 0&&(s||a[u])?c.concat(e.formatDistance(l,d)):c},[]).join(o):""}function lu(a,r){const t=C(a);if(isNaN(t.getTime()))throw new RangeError("Invalid time value");const e=(r==null?void 0:r.representation)??"complete";let n="",s="";const o="-",i=":";if(e!=="time"){const c=T(t.getDate(),2),u=T(t.getMonth()+1,2);n=`${T(t.getFullYear(),4)}${o}${u}${o}${c}`}if(e!=="date"){const c=t.getTimezoneOffset();if(c!==0){const h=Math.abs(c),g=T(Math.trunc(h/60),2),w=T(h%60,2);s=`${c<0?"+":"-"}${g}:${w}`}else s="Z";const u=T(t.getHours(),2),l=T(t.getMinutes(),2),d=T(t.getSeconds(),2),f=n===""?"":"T",p=[u,l,d].join(i);n=`${n}${f}${p}${s}`}return n}function du(a){return C(a*1e3)}function fu(a){const r=C(a.start),t=C(a.end),e={},n=sa(t,r);n&&(e.years=n);const s=ze(r,{years:e.years}),o=rr(t,s);o&&(e.months=o);const i=ze(s,{months:e.months}),c=Jr(t,i);c&&(e.days=c);const u=ze(i,{days:e.days}),l=ea(t,u);l&&(e.hours=l);const d=ze(u,{hours:e.hours}),f=ta(t,d);f&&(e.minutes=f);const p=ze(d,{minutes:e.minutes}),h=ar(t,p);return h&&(e.seconds=h),e}function pu(a,r){const e=ls(a);let n;if(e.date){const c=ds(e.date,2);n=fs(c.restDateString,c.year)}if(!n||isNaN(n.getTime()))return new Date(NaN);const s=n.getTime();let o=0,i;if(e.time&&(o=ps(e.time),isNaN(o)))return new Date(NaN);if(e.timezone){if(i=hs(e.timezone),isNaN(i))return new Date(NaN)}else{const c=new Date(s+o),u=new Date(0);return u.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),u.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),u}return new Date(s+o+i)}const pt={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},is=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,cs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,us=/^([+-])(\d{2})(?::?(\d{2}))?$/;function ls(a){const r={},t=a.split(pt.dateTimeDelimiter);let e;if(t.length>2)return r;if(/:/.test(t[0])?e=t[0]:(r.date=t[0],e=t[1],pt.timeZoneDelimiter.test(r.date)&&(r.date=a.split(pt.timeZoneDelimiter)[0],e=a.substr(r.date.length,a.length))),e){const n=pt.timezone.exec(e);n?(r.time=e.replace(n[1],""),r.timezone=n[1]):r.time=e}return r}function ds(a,r){const t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+r)+"})|(\\d{2}|[+-]\\d{"+(2+r)+"})$)"),e=a.match(t);if(!e)return{year:NaN,restDateString:""};const n=e[1]?parseInt(e[1]):null,s=e[2]?parseInt(e[2]):null;return{year:s===null?n:s*100,restDateString:a.slice((e[1]||e[2]).length)}}function fs(a,r){if(r===null)return new Date(NaN);const t=a.match(is);if(!t)return new Date(NaN);const e=!!t[4],n=et(t[1]),s=et(t[2])-1,o=et(t[3]),i=et(t[4]),c=et(t[5])-1;if(e)return ys(r,i,c)?ms(r,i,c):new Date(NaN);{const u=new Date(0);return!ws(r,s,o)||!Ds(r,n)?new Date(NaN):(u.setUTCFullYear(r,s,Math.max(n,o)),u)}}function et(a){return a?parseInt(a):1}function ps(a){const r=a.match(cs);if(!r)return NaN;const t=qt(r[1]),e=qt(r[2]),n=qt(r[3]);return vs(t,e,n)?t*rn+e*it+n*1e3:NaN}function qt(a){return a&&parseFloat(a.replace(",","."))||0}function hs(a){if(a==="Z")return 0;const r=a.match(us);if(!r)return 0;const t=r[1]==="+"?-1:1,e=parseInt(r[2]),n=r[3]&&parseInt(r[3])||0;return bs(e,n)?t*(e*rn+n*it):NaN}function ms(a,r,t){const e=new Date(0);e.setUTCFullYear(a,0,4);const n=e.getUTCDay()||7,s=(r-1)*7+t+1-n;return e.setUTCDate(e.getUTCDate()+s),e}const gs=[31,null,31,30,31,30,31,31,30,31,30,31];function ir(a){return a%400===0||a%4===0&&a%100!==0}function ws(a,r,t){return r>=0&&r<=11&&t>=1&&t<=(gs[r]||(ir(a)?29:28))}function Ds(a,r){return r>=1&&r<=(ir(a)?366:365)}function ys(a,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function vs(a,r,t){return a===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&a>=0&&a<25}function bs(a,r){return r>=0&&r<=59}const cr=6048e5,ks=864e5,Wt=6e4,At=36e5,_s=1e3,kn=Symbol.for("constructDateFrom");function W(a,r){return typeof a=="function"?a(r):a&&typeof a=="object"&&kn in a?a[kn](r):a instanceof Date?new a.constructor(r):new Date(r)}function b(a,r){return W(r||a,a)}function ce(a,r,t){const e=b(a,t==null?void 0:t.in);return isNaN(r)?W((t==null?void 0:t.in)||a,NaN):(r&&e.setDate(e.getDate()+r),e)}function ue(a,r,t){const e=b(a,t==null?void 0:t.in);if(isNaN(r))return W(a,NaN);if(!r)return e;const n=e.getDate(),s=W(a,e.getTime());s.setMonth(e.getMonth()+r+1,0);const o=s.getDate();return n>=o?s:(e.setFullYear(s.getFullYear(),s.getMonth(),n),e)}function ur(a,r,t){return W(a,+b(a)+r)}function Ms(a,r,t){return ur(a,r*At)}let xs={};function We(){return xs}function be(a,r){var i,c,u,l;const t=We(),e=(r==null?void 0:r.weekStartsOn)??((c=(i=r==null?void 0:r.locale)==null?void 0:i.options)==null?void 0:c.weekStartsOn)??t.weekStartsOn??((l=(u=t.locale)==null?void 0:u.options)==null?void 0:l.weekStartsOn)??0,n=b(a,r==null?void 0:r.in),s=n.getDay(),o=(s<e?7:0)+s-e;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Ke(a,r){return be(a,{...r,weekStartsOn:1})}function lr(a,r){const t=b(a,r==null?void 0:r.in),e=t.getFullYear(),n=W(t,0);n.setFullYear(e+1,0,4),n.setHours(0,0,0,0);const s=Ke(n),o=W(t,0);o.setFullYear(e,0,4),o.setHours(0,0,0,0);const i=Ke(o);return t.getTime()>=s.getTime()?e+1:t.getTime()>=i.getTime()?e:e-1}function Ct(a){const r=b(a),t=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return t.setUTCFullYear(r.getFullYear()),+a-+t}function ke(a,...r){const t=W.bind(null,r.find(e=>typeof e=="object"));return r.map(t)}function Re(a,r){const t=b(a,r==null?void 0:r.in);return t.setHours(0,0,0,0),t}function Ve(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r),s=Re(e),o=Re(n),i=+s-Ct(s),c=+o-Ct(o);return Math.round((i-c)/ks)}function Ss(a,r){const t=lr(a,r),e=W(a,0);return e.setFullYear(t,0,4),e.setHours(0,0,0,0),Ke(e)}function Zt(a,r,t){const e=b(a,t==null?void 0:t.in);return e.setTime(e.getTime()+r*Wt),e}function sn(a,r,t){return ue(a,r*3,t)}function Cs(a,r,t){return ur(a,r*1e3)}function Pt(a,r,t){return ce(a,r*7,t)}function ge(a,r,t){return ue(a,r*12,t)}function _n(a,r){let t,e=r==null?void 0:r.in;return a.forEach(n=>{!e&&typeof n=="object"&&(e=W.bind(null,n));const s=b(n,e);(!t||t<s||isNaN(+s))&&(t=s)}),W(e,t||NaN)}function Mn(a,r){let t,e=r==null?void 0:r.in;return a.forEach(n=>{!e&&typeof n=="object"&&(e=W.bind(null,n));const s=b(n,e);(!t||t>s||isNaN(+s))&&(t=s)}),W(e,t||NaN)}function Ps(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r);return+Re(e)==+Re(n)}function we(a){return a instanceof Date||typeof a=="object"&&Object.prototype.toString.call(a)==="[object Date]"}function Tt(a){return!(!we(a)&&typeof a!="number"||isNaN(+b(a)))}function Ot(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r),s=e.getFullYear()-n.getFullYear(),o=e.getMonth()-n.getMonth();return s*12+o}function Ye(a,r){const t=b(a,r==null?void 0:r.in);return Math.trunc(t.getMonth()/3)+1}function Et(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r),s=e.getFullYear()-n.getFullYear(),o=Ye(e)-Ye(n);return s*4+o}function Nt(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r);return e.getFullYear()-n.getFullYear()}function Ts(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r),s=xn(e,n),o=Math.abs(Ve(e,n));e.setDate(e.getDate()-s*o);const i=+(xn(e,n)===-s),c=s*(o-i);return c===0?0:c}function xn(a,r){const t=a.getFullYear()-r.getFullYear()||a.getMonth()-r.getMonth()||a.getDate()-r.getDate()||a.getHours()-r.getHours()||a.getMinutes()-r.getMinutes()||a.getSeconds()-r.getSeconds()||a.getMilliseconds()-r.getMilliseconds();return t<0?-1:t>0?1:t}function dr(a,r){const t=b(a,r==null?void 0:r.in);return t.setHours(23,59,59,999),t}function fr(a,r){const t=b(a,r==null?void 0:r.in),e=t.getMonth();return t.setFullYear(t.getFullYear(),e+1,0),t.setHours(23,59,59,999),t}function Jt(a,r){const t=b(a,r==null?void 0:r.in),e=t.getMonth(),n=e-e%3;return t.setMonth(n,1),t.setHours(0,0,0,0),t}function pr(a,r){const t=b(a,r==null?void 0:r.in);return t.setDate(1),t.setHours(0,0,0,0),t}function hr(a,r){const t=b(a,r==null?void 0:r.in),e=t.getFullYear();return t.setFullYear(e+1,0,0),t.setHours(23,59,59,999),t}function Ht(a,r){const t=b(a,r==null?void 0:r.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}function Os(a,r){var i,c;const t=We(),e=t.weekStartsOn??((c=(i=t.locale)==null?void 0:i.options)==null?void 0:c.weekStartsOn)??0,n=b(a,r==null?void 0:r.in),s=n.getDay(),o=(s<e?-7:0)+6-(s-e);return n.setDate(n.getDate()+o),n.setHours(23,59,59,999),n}const Es={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ns=(a,r,t)=>{let e;const n=Es[a];return typeof n=="string"?e=n:r===1?e=n.one:e=n.other.replace("{{count}}",r.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+e:e+" ago":e};function Kt(a){return(r={})=>{const t=r.width?String(r.width):a.defaultWidth;return a.formats[t]||a.formats[a.defaultWidth]}}const Ys={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Is={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Rs={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Fs={date:Kt({formats:Ys,defaultWidth:"full"}),time:Kt({formats:Is,defaultWidth:"full"}),dateTime:Kt({formats:Rs,defaultWidth:"full"})},Ls={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Ws=(a,r,t,e)=>Ls[a];function tt(a){return(r,t)=>{const e=t!=null&&t.context?String(t.context):"standalone";let n;if(e==="formatting"&&a.formattingValues){const o=a.defaultFormattingWidth||a.defaultWidth,i=t!=null&&t.width?String(t.width):o;n=a.formattingValues[i]||a.formattingValues[o]}else{const o=a.defaultWidth,i=t!=null&&t.width?String(t.width):a.defaultWidth;n=a.values[i]||a.values[o]}const s=a.argumentCallback?a.argumentCallback(r):r;return n[s]}}const As={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Hs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},$s={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Qs={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Bs={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},qs={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Ks=(a,r)=>{const t=Number(a),e=t%100;if(e>20||e<10)switch(e%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},Vs={ordinalNumber:Ks,era:tt({values:As,defaultWidth:"wide"}),quarter:tt({values:Hs,defaultWidth:"wide",argumentCallback:a=>a-1}),month:tt({values:$s,defaultWidth:"wide"}),day:tt({values:Qs,defaultWidth:"wide"}),dayPeriod:tt({values:Bs,defaultWidth:"wide",formattingValues:qs,defaultFormattingWidth:"wide"})};function nt(a){return(r,t={})=>{const e=t.width,n=e&&a.matchPatterns[e]||a.matchPatterns[a.defaultMatchWidth],s=r.match(n);if(!s)return null;const o=s[0],i=e&&a.parsePatterns[e]||a.parsePatterns[a.defaultParseWidth],c=Array.isArray(i)?js(i,d=>d.test(o)):Us(i,d=>d.test(o));let u;u=a.valueCallback?a.valueCallback(c):c,u=t.valueCallback?t.valueCallback(u):u;const l=r.slice(o.length);return{value:u,rest:l}}}function Us(a,r){for(const t in a)if(Object.prototype.hasOwnProperty.call(a,t)&&r(a[t]))return t}function js(a,r){for(let t=0;t<a.length;t++)if(r(a[t]))return t}function Xs(a){return(r,t={})=>{const e=r.match(a.matchPattern);if(!e)return null;const n=e[0],s=r.match(a.parsePattern);if(!s)return null;let o=a.valueCallback?a.valueCallback(s[0]):s[0];o=t.valueCallback?t.valueCallback(o):o;const i=r.slice(n.length);return{value:o,rest:i}}}const Gs=/^(\d+)(th|st|nd|rd)?/i,zs=/\d+/i,Zs={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Js={any:[/^b/i,/^(a|c)/i]},eo={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},to={any:[/1/i,/2/i,/3/i,/4/i]},no={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},ro={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},ao={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},so={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},oo={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},io={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},co={ordinalNumber:Xs({matchPattern:Gs,parsePattern:zs,valueCallback:a=>parseInt(a,10)}),era:nt({matchPatterns:Zs,defaultMatchWidth:"wide",parsePatterns:Js,defaultParseWidth:"any"}),quarter:nt({matchPatterns:eo,defaultMatchWidth:"wide",parsePatterns:to,defaultParseWidth:"any",valueCallback:a=>a+1}),month:nt({matchPatterns:no,defaultMatchWidth:"wide",parsePatterns:ro,defaultParseWidth:"any"}),day:nt({matchPatterns:ao,defaultMatchWidth:"wide",parsePatterns:so,defaultParseWidth:"any"}),dayPeriod:nt({matchPatterns:oo,defaultMatchWidth:"any",parsePatterns:io,defaultParseWidth:"any"})},mr={code:"en-US",formatDistance:Ns,formatLong:Fs,formatRelative:Ws,localize:Vs,match:co,options:{weekStartsOn:0,firstWeekContainsDate:1}};function uo(a,r){const t=b(a,r==null?void 0:r.in);return Ve(t,Ht(t))+1}function on(a,r){const t=b(a,r==null?void 0:r.in),e=+Ke(t)-+Ss(t);return Math.round(e/cr)+1}function cn(a,r){var l,d,f,p;const t=b(a,r==null?void 0:r.in),e=t.getFullYear(),n=We(),s=(r==null?void 0:r.firstWeekContainsDate)??((d=(l=r==null?void 0:r.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??n.firstWeekContainsDate??((p=(f=n.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,o=W((r==null?void 0:r.in)||a,0);o.setFullYear(e+1,0,s),o.setHours(0,0,0,0);const i=be(o,r),c=W((r==null?void 0:r.in)||a,0);c.setFullYear(e,0,s),c.setHours(0,0,0,0);const u=be(c,r);return+t>=+i?e+1:+t>=+u?e:e-1}function lo(a,r){var i,c,u,l;const t=We(),e=(r==null?void 0:r.firstWeekContainsDate)??((c=(i=r==null?void 0:r.locale)==null?void 0:i.options)==null?void 0:c.firstWeekContainsDate)??t.firstWeekContainsDate??((l=(u=t.locale)==null?void 0:u.options)==null?void 0:l.firstWeekContainsDate)??1,n=cn(a,r),s=W((r==null?void 0:r.in)||a,0);return s.setFullYear(n,0,e),s.setHours(0,0,0,0),be(s,r)}function gr(a,r){const t=b(a,r==null?void 0:r.in),e=+be(t,r)-+lo(t,r);return Math.round(e/cr)+1}function L(a,r){const t=a<0?"-":"",e=Math.abs(a).toString().padStart(r,"0");return t+e}const Me={y(a,r){const t=a.getFullYear(),e=t>0?t:1-t;return L(r==="yy"?e%100:e,r.length)},M(a,r){const t=a.getMonth();return r==="M"?String(t+1):L(t+1,2)},d(a,r){return L(a.getDate(),r.length)},a(a,r){const t=a.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(a,r){return L(a.getHours()%12||12,r.length)},H(a,r){return L(a.getHours(),r.length)},m(a,r){return L(a.getMinutes(),r.length)},s(a,r){return L(a.getSeconds(),r.length)},S(a,r){const t=r.length,e=a.getMilliseconds(),n=Math.trunc(e*Math.pow(10,t-3));return L(n,r.length)}},He={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Sn={G:function(a,r,t){const e=a.getFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return t.era(e,{width:"abbreviated"});case"GGGGG":return t.era(e,{width:"narrow"});case"GGGG":default:return t.era(e,{width:"wide"})}},y:function(a,r,t){if(r==="yo"){const e=a.getFullYear(),n=e>0?e:1-e;return t.ordinalNumber(n,{unit:"year"})}return Me.y(a,r)},Y:function(a,r,t,e){const n=cn(a,e),s=n>0?n:1-n;if(r==="YY"){const o=s%100;return L(o,2)}return r==="Yo"?t.ordinalNumber(s,{unit:"year"}):L(s,r.length)},R:function(a,r){const t=lr(a);return L(t,r.length)},u:function(a,r){const t=a.getFullYear();return L(t,r.length)},Q:function(a,r,t){const e=Math.ceil((a.getMonth()+1)/3);switch(r){case"Q":return String(e);case"QQ":return L(e,2);case"Qo":return t.ordinalNumber(e,{unit:"quarter"});case"QQQ":return t.quarter(e,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(e,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(e,{width:"wide",context:"formatting"})}},q:function(a,r,t){const e=Math.ceil((a.getMonth()+1)/3);switch(r){case"q":return String(e);case"qq":return L(e,2);case"qo":return t.ordinalNumber(e,{unit:"quarter"});case"qqq":return t.quarter(e,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(e,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(e,{width:"wide",context:"standalone"})}},M:function(a,r,t){const e=a.getMonth();switch(r){case"M":case"MM":return Me.M(a,r);case"Mo":return t.ordinalNumber(e+1,{unit:"month"});case"MMM":return t.month(e,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(e,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(e,{width:"wide",context:"formatting"})}},L:function(a,r,t){const e=a.getMonth();switch(r){case"L":return String(e+1);case"LL":return L(e+1,2);case"Lo":return t.ordinalNumber(e+1,{unit:"month"});case"LLL":return t.month(e,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(e,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(e,{width:"wide",context:"standalone"})}},w:function(a,r,t,e){const n=gr(a,e);return r==="wo"?t.ordinalNumber(n,{unit:"week"}):L(n,r.length)},I:function(a,r,t){const e=on(a);return r==="Io"?t.ordinalNumber(e,{unit:"week"}):L(e,r.length)},d:function(a,r,t){return r==="do"?t.ordinalNumber(a.getDate(),{unit:"date"}):Me.d(a,r)},D:function(a,r,t){const e=uo(a);return r==="Do"?t.ordinalNumber(e,{unit:"dayOfYear"}):L(e,r.length)},E:function(a,r,t){const e=a.getDay();switch(r){case"E":case"EE":case"EEE":return t.day(e,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(e,{width:"short",context:"formatting"});case"EEEE":default:return t.day(e,{width:"wide",context:"formatting"})}},e:function(a,r,t,e){const n=a.getDay(),s=(n-e.weekStartsOn+8)%7||7;switch(r){case"e":return String(s);case"ee":return L(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});case"eeee":default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(a,r,t,e){const n=a.getDay(),s=(n-e.weekStartsOn+8)%7||7;switch(r){case"c":return String(s);case"cc":return L(s,r.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});case"cccc":default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(a,r,t){const e=a.getDay(),n=e===0?7:e;switch(r){case"i":return String(n);case"ii":return L(n,r.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(e,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(e,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(e,{width:"short",context:"formatting"});case"iiii":default:return t.day(e,{width:"wide",context:"formatting"})}},a:function(a,r,t){const n=a.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(a,r,t){const e=a.getHours();let n;switch(e===12?n=He.noon:e===0?n=He.midnight:n=e/12>=1?"pm":"am",r){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(a,r,t){const e=a.getHours();let n;switch(e>=17?n=He.evening:e>=12?n=He.afternoon:e>=4?n=He.morning:n=He.night,r){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(a,r,t){if(r==="ho"){let e=a.getHours()%12;return e===0&&(e=12),t.ordinalNumber(e,{unit:"hour"})}return Me.h(a,r)},H:function(a,r,t){return r==="Ho"?t.ordinalNumber(a.getHours(),{unit:"hour"}):Me.H(a,r)},K:function(a,r,t){const e=a.getHours()%12;return r==="Ko"?t.ordinalNumber(e,{unit:"hour"}):L(e,r.length)},k:function(a,r,t){let e=a.getHours();return e===0&&(e=24),r==="ko"?t.ordinalNumber(e,{unit:"hour"}):L(e,r.length)},m:function(a,r,t){return r==="mo"?t.ordinalNumber(a.getMinutes(),{unit:"minute"}):Me.m(a,r)},s:function(a,r,t){return r==="so"?t.ordinalNumber(a.getSeconds(),{unit:"second"}):Me.s(a,r)},S:function(a,r){return Me.S(a,r)},X:function(a,r,t){const e=a.getTimezoneOffset();if(e===0)return"Z";switch(r){case"X":return Pn(e);case"XXXX":case"XX":return Oe(e);case"XXXXX":case"XXX":default:return Oe(e,":")}},x:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"x":return Pn(e);case"xxxx":case"xx":return Oe(e);case"xxxxx":case"xxx":default:return Oe(e,":")}},O:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+Cn(e,":");case"OOOO":default:return"GMT"+Oe(e,":")}},z:function(a,r,t){const e=a.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+Cn(e,":");case"zzzz":default:return"GMT"+Oe(e,":")}},t:function(a,r,t){const e=Math.trunc(+a/1e3);return L(e,r.length)},T:function(a,r,t){return L(+a,r.length)}};function Cn(a,r=""){const t=a>0?"-":"+",e=Math.abs(a),n=Math.trunc(e/60),s=e%60;return s===0?t+String(n):t+String(n)+r+L(s,2)}function Pn(a,r){return a%60===0?(a>0?"-":"+")+L(Math.abs(a)/60,2):Oe(a,r)}function Oe(a,r=""){const t=a>0?"-":"+",e=Math.abs(a),n=L(Math.trunc(e/60),2),s=L(e%60,2);return t+n+r+s}const Tn=(a,r)=>{switch(a){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},wr=(a,r)=>{switch(a){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},fo=(a,r)=>{const t=a.match(/(P+)(p+)?/)||[],e=t[1],n=t[2];if(!n)return Tn(a,r);let s;switch(e){case"P":s=r.dateTime({width:"short"});break;case"PP":s=r.dateTime({width:"medium"});break;case"PPP":s=r.dateTime({width:"long"});break;case"PPPP":default:s=r.dateTime({width:"full"});break}return s.replace("{{date}}",Tn(e,r)).replace("{{time}}",wr(n,r))},en={p:wr,P:fo},po=/^D+$/,ho=/^Y+$/,mo=["D","DD","YY","YYYY"];function go(a){return po.test(a)}function wo(a){return ho.test(a)}function Do(a,r,t){const e=yo(a,r,t);if(console.warn(e),mo.includes(a))throw new RangeError(e)}function yo(a,r,t){const e=a[0]==="Y"?"years":"days of the month";return`Use \`${a.toLowerCase()}\` instead of \`${a}\` (in \`${r}\`) for formatting ${e} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const vo=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,bo=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ko=/^'([^]*?)'?$/,_o=/''/g,Mo=/[a-zA-Z]/;function On(a,r,t){var l,d,f,p,h,g,w,k;const e=We(),n=(t==null?void 0:t.locale)??e.locale??mr,s=(t==null?void 0:t.firstWeekContainsDate)??((d=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??e.firstWeekContainsDate??((p=(f=e.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,o=(t==null?void 0:t.weekStartsOn)??((g=(h=t==null?void 0:t.locale)==null?void 0:h.options)==null?void 0:g.weekStartsOn)??e.weekStartsOn??((k=(w=e.locale)==null?void 0:w.options)==null?void 0:k.weekStartsOn)??0,i=b(a,t==null?void 0:t.in);if(!Tt(i))throw new RangeError("Invalid time value");let c=r.match(bo).map(S=>{const x=S[0];if(x==="p"||x==="P"){const N=en[x];return N(S,n.formatLong)}return S}).join("").match(vo).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const x=S[0];if(x==="'")return{isToken:!1,value:xo(S)};if(Sn[x])return{isToken:!0,value:S};if(x.match(Mo))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");return{isToken:!1,value:S}});n.localize.preprocessor&&(c=n.localize.preprocessor(i,c));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:n};return c.map(S=>{if(!S.isToken)return S.value;const x=S.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&wo(x)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&go(x))&&Do(x,r,String(a));const N=Sn[x[0]];return N(i,x,n.localize,u)}).join("")}function xo(a){const r=a.match(ko);return r?r[1].replace(_o,"'"):a}function En(a,r){return b(a,r==null?void 0:r.in).getDate()}function So(a,r){return b(a,r==null?void 0:r.in).getDay()}function Co(a,r){const t=b(a,r==null?void 0:r.in),e=t.getFullYear(),n=t.getMonth(),s=W(t,0);return s.setFullYear(e,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Po(){return Object.assign({},We())}function De(a,r){return b(a,r==null?void 0:r.in).getHours()}function To(a,r){const t=b(a,r==null?void 0:r.in).getDay();return t===0?7:t}function ye(a,r){return b(a,r==null?void 0:r.in).getMinutes()}function te(a,r){return b(a,r==null?void 0:r.in).getMonth()}function Se(a){return b(a).getSeconds()}function tn(a){return+b(a)}function P(a,r){return b(a,r==null?void 0:r.in).getFullYear()}function Pe(a,r){return+b(a)>+b(r)}function Fe(a,r){return+b(a)<+b(r)}function Oo(a,r){return+b(a)==+b(r)}function Eo(a,r){const t=No(r)?new r(0):W(r,0);return t.setFullYear(a.getFullYear(),a.getMonth(),a.getDate()),t.setHours(a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()),t}function No(a){var r;return typeof a=="function"&&((r=a.prototype)==null?void 0:r.constructor)===a}const Yo=10;class Dr{constructor(){y(this,"subPriority",0)}validate(r,t){return!0}}class Io extends Dr{constructor(r,t,e,n,s){super(),this.value=r,this.validateValue=t,this.setValue=e,this.priority=n,s&&(this.subPriority=s)}validate(r,t){return this.validateValue(r,this.value,t)}set(r,t,e){return this.setValue(r,t,this.value,e)}}class Ro extends Dr{constructor(t,e){super();y(this,"priority",Yo);y(this,"subPriority",-1);this.context=t||(n=>W(e,n))}set(t,e){return e.timestampIsSet?t:W(t,Eo(t,this.context))}}class Y{run(r,t,e,n){const s=this.parse(r,t,e,n);return s?{setter:new Io(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(r,t,e){return!0}}class Fo extends Y{constructor(){super(...arguments);y(this,"priority",140);y(this,"incompatibleTokens",["R","u","t","T"])}parse(t,e,n){switch(e){case"G":case"GG":case"GGG":return n.era(t,{width:"abbreviated"})||n.era(t,{width:"narrow"});case"GGGGG":return n.era(t,{width:"narrow"});case"GGGG":default:return n.era(t,{width:"wide"})||n.era(t,{width:"abbreviated"})||n.era(t,{width:"narrow"})}}set(t,e,n){return e.era=n,t.setFullYear(n,0,1),t.setHours(0,0,0,0),t}}const U={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},pe={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function j(a,r){return a&&{value:r(a.value),rest:a.rest}}function B(a,r){const t=r.match(a);return t?{value:parseInt(t[0],10),rest:r.slice(t[0].length)}:null}function he(a,r){const t=r.match(a);if(!t)return null;if(t[0]==="Z")return{value:0,rest:r.slice(1)};const e=t[1]==="+"?1:-1,n=t[2]?parseInt(t[2],10):0,s=t[3]?parseInt(t[3],10):0,o=t[5]?parseInt(t[5],10):0;return{value:e*(n*At+s*Wt+o*_s),rest:r.slice(t[0].length)}}function yr(a){return B(U.anyDigitsSigned,a)}function V(a,r){switch(a){case 1:return B(U.singleDigit,r);case 2:return B(U.twoDigits,r);case 3:return B(U.threeDigits,r);case 4:return B(U.fourDigits,r);default:return B(new RegExp("^\\d{1,"+a+"}"),r)}}function Yt(a,r){switch(a){case 1:return B(U.singleDigitSigned,r);case 2:return B(U.twoDigitsSigned,r);case 3:return B(U.threeDigitsSigned,r);case 4:return B(U.fourDigitsSigned,r);default:return B(new RegExp("^-?\\d{1,"+a+"}"),r)}}function un(a){switch(a){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function vr(a,r){const t=r>0,e=t?r:1-r;let n;if(e<=50)n=a||100;else{const s=e+50,o=Math.trunc(s/100)*100,i=a>=s%100;n=a+o-(i?100:0)}return t?n:1-n}function br(a){return a%400===0||a%4===0&&a%100!==0}class Lo extends Y{constructor(){super(...arguments);y(this,"priority",130);y(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(t,e,n){const s=o=>({year:o,isTwoDigitYear:e==="yy"});switch(e){case"y":return j(V(4,t),s);case"yo":return j(n.ordinalNumber(t,{unit:"year"}),s);default:return j(V(e.length,t),s)}}validate(t,e){return e.isTwoDigitYear||e.year>0}set(t,e,n){const s=t.getFullYear();if(n.isTwoDigitYear){const i=vr(n.year,s);return t.setFullYear(i,0,1),t.setHours(0,0,0,0),t}const o=!("era"in e)||e.era===1?n.year:1-n.year;return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}}class Wo extends Y{constructor(){super(...arguments);y(this,"priority",130);y(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(t,e,n){const s=o=>({year:o,isTwoDigitYear:e==="YY"});switch(e){case"Y":return j(V(4,t),s);case"Yo":return j(n.ordinalNumber(t,{unit:"year"}),s);default:return j(V(e.length,t),s)}}validate(t,e){return e.isTwoDigitYear||e.year>0}set(t,e,n,s){const o=cn(t,s);if(n.isTwoDigitYear){const c=vr(n.year,o);return t.setFullYear(c,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),be(t,s)}const i=!("era"in e)||e.era===1?n.year:1-n.year;return t.setFullYear(i,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),be(t,s)}}class Ao extends Y{constructor(){super(...arguments);y(this,"priority",130);y(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(t,e){return Yt(e==="R"?4:e.length,t)}set(t,e,n){const s=W(t,0);return s.setFullYear(n,0,4),s.setHours(0,0,0,0),Ke(s)}}class Ho extends Y{constructor(){super(...arguments);y(this,"priority",130);y(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(t,e){return Yt(e==="u"?4:e.length,t)}set(t,e,n){return t.setFullYear(n,0,1),t.setHours(0,0,0,0),t}}class $o extends Y{constructor(){super(...arguments);y(this,"priority",120);y(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,e,n){switch(e){case"Q":case"QQ":return V(e.length,t);case"Qo":return n.ordinalNumber(t,{unit:"quarter"});case"QQQ":return n.quarter(t,{width:"abbreviated",context:"formatting"})||n.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return n.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(t,{width:"wide",context:"formatting"})||n.quarter(t,{width:"abbreviated",context:"formatting"})||n.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,e){return e>=1&&e<=4}set(t,e,n){return t.setMonth((n-1)*3,1),t.setHours(0,0,0,0),t}}class Qo extends Y{constructor(){super(...arguments);y(this,"priority",120);y(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,e,n){switch(e){case"q":case"qq":return V(e.length,t);case"qo":return n.ordinalNumber(t,{unit:"quarter"});case"qqq":return n.quarter(t,{width:"abbreviated",context:"standalone"})||n.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return n.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(t,{width:"wide",context:"standalone"})||n.quarter(t,{width:"abbreviated",context:"standalone"})||n.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,e){return e>=1&&e<=4}set(t,e,n){return t.setMonth((n-1)*3,1),t.setHours(0,0,0,0),t}}class Bo extends Y{constructor(){super(...arguments);y(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);y(this,"priority",110)}parse(t,e,n){const s=o=>o-1;switch(e){case"M":return j(B(U.month,t),s);case"MM":return j(V(2,t),s);case"Mo":return j(n.ordinalNumber(t,{unit:"month"}),s);case"MMM":return n.month(t,{width:"abbreviated",context:"formatting"})||n.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return n.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(t,{width:"wide",context:"formatting"})||n.month(t,{width:"abbreviated",context:"formatting"})||n.month(t,{width:"narrow",context:"formatting"})}}validate(t,e){return e>=0&&e<=11}set(t,e,n){return t.setMonth(n,1),t.setHours(0,0,0,0),t}}class qo extends Y{constructor(){super(...arguments);y(this,"priority",110);y(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(t,e,n){const s=o=>o-1;switch(e){case"L":return j(B(U.month,t),s);case"LL":return j(V(2,t),s);case"Lo":return j(n.ordinalNumber(t,{unit:"month"}),s);case"LLL":return n.month(t,{width:"abbreviated",context:"standalone"})||n.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return n.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(t,{width:"wide",context:"standalone"})||n.month(t,{width:"abbreviated",context:"standalone"})||n.month(t,{width:"narrow",context:"standalone"})}}validate(t,e){return e>=0&&e<=11}set(t,e,n){return t.setMonth(n,1),t.setHours(0,0,0,0),t}}function Ko(a,r,t){const e=b(a,t==null?void 0:t.in),n=gr(e,t)-r;return e.setDate(e.getDate()-n*7),b(e,t==null?void 0:t.in)}class Vo extends Y{constructor(){super(...arguments);y(this,"priority",100);y(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(t,e,n){switch(e){case"w":return B(U.week,t);case"wo":return n.ordinalNumber(t,{unit:"week"});default:return V(e.length,t)}}validate(t,e){return e>=1&&e<=53}set(t,e,n,s){return be(Ko(t,n,s),s)}}function Uo(a,r,t){const e=b(a,t==null?void 0:t.in),n=on(e,t)-r;return e.setDate(e.getDate()-n*7),e}class jo extends Y{constructor(){super(...arguments);y(this,"priority",100);y(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(t,e,n){switch(e){case"I":return B(U.week,t);case"Io":return n.ordinalNumber(t,{unit:"week"});default:return V(e.length,t)}}validate(t,e){return e>=1&&e<=53}set(t,e,n){return Ke(Uo(t,n))}}const Xo=[31,28,31,30,31,30,31,31,30,31,30,31],Go=[31,29,31,30,31,30,31,31,30,31,30,31];class zo extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"subPriority",1);y(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(t,e,n){switch(e){case"d":return B(U.date,t);case"do":return n.ordinalNumber(t,{unit:"date"});default:return V(e.length,t)}}validate(t,e){const n=t.getFullYear(),s=br(n),o=t.getMonth();return s?e>=1&&e<=Go[o]:e>=1&&e<=Xo[o]}set(t,e,n){return t.setDate(n),t.setHours(0,0,0,0),t}}class Zo extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"subpriority",1);y(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(t,e,n){switch(e){case"D":case"DD":return B(U.dayOfYear,t);case"Do":return n.ordinalNumber(t,{unit:"date"});default:return V(e.length,t)}}validate(t,e){const n=t.getFullYear();return br(n)?e>=1&&e<=366:e>=1&&e<=365}set(t,e,n){return t.setMonth(0,n),t.setHours(0,0,0,0),t}}function ln(a,r,t){var d,f,p,h;const e=We(),n=(t==null?void 0:t.weekStartsOn)??((f=(d=t==null?void 0:t.locale)==null?void 0:d.options)==null?void 0:f.weekStartsOn)??e.weekStartsOn??((h=(p=e.locale)==null?void 0:p.options)==null?void 0:h.weekStartsOn)??0,s=b(a,t==null?void 0:t.in),o=s.getDay(),c=(r%7+7)%7,u=7-n,l=r<0||r>6?r-(o+u)%7:(c+u)%7-(o+u)%7;return ce(s,l,t)}class Jo extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(t,e,n){switch(e){case"E":case"EE":case"EEE":return n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return n.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return n.day(t,{width:"wide",context:"formatting"})||n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"})}}validate(t,e){return e>=0&&e<=6}set(t,e,n,s){return t=ln(t,n,s),t.setHours(0,0,0,0),t}}class ei extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(t,e,n,s){const o=i=>{const c=Math.floor((i-1)/7)*7;return(i+s.weekStartsOn+6)%7+c};switch(e){case"e":case"ee":return j(V(e.length,t),o);case"eo":return j(n.ordinalNumber(t,{unit:"day"}),o);case"eee":return n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"eeeee":return n.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return n.day(t,{width:"wide",context:"formatting"})||n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"})}}validate(t,e){return e>=0&&e<=6}set(t,e,n,s){return t=ln(t,n,s),t.setHours(0,0,0,0),t}}class ti extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(t,e,n,s){const o=i=>{const c=Math.floor((i-1)/7)*7;return(i+s.weekStartsOn+6)%7+c};switch(e){case"c":case"cc":return j(V(e.length,t),o);case"co":return j(n.ordinalNumber(t,{unit:"day"}),o);case"ccc":return n.day(t,{width:"abbreviated",context:"standalone"})||n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"});case"ccccc":return n.day(t,{width:"narrow",context:"standalone"});case"cccccc":return n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return n.day(t,{width:"wide",context:"standalone"})||n.day(t,{width:"abbreviated",context:"standalone"})||n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"})}}validate(t,e){return e>=0&&e<=6}set(t,e,n,s){return t=ln(t,n,s),t.setHours(0,0,0,0),t}}function ni(a,r,t){const e=b(a,t==null?void 0:t.in),n=To(e,t),s=r-n;return ce(e,s,t)}class ri extends Y{constructor(){super(...arguments);y(this,"priority",90);y(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(t,e,n){const s=o=>o===0?7:o;switch(e){case"i":case"ii":return V(e.length,t);case"io":return n.ordinalNumber(t,{unit:"day"});case"iii":return j(n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"}),s);case"iiiii":return j(n.day(t,{width:"narrow",context:"formatting"}),s);case"iiiiii":return j(n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"}),s);case"iiii":default:return j(n.day(t,{width:"wide",context:"formatting"})||n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"}),s)}}validate(t,e){return e>=1&&e<=7}set(t,e,n){return t=ni(t,n),t.setHours(0,0,0,0),t}}class ai extends Y{constructor(){super(...arguments);y(this,"priority",80);y(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(t,e,n){switch(e){case"a":case"aa":case"aaa":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,e,n){return t.setHours(un(n),0,0,0),t}}class si extends Y{constructor(){super(...arguments);y(this,"priority",80);y(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(t,e,n){switch(e){case"b":case"bb":case"bbb":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,e,n){return t.setHours(un(n),0,0,0),t}}class oi extends Y{constructor(){super(...arguments);y(this,"priority",80);y(this,"incompatibleTokens",["a","b","t","T"])}parse(t,e,n){switch(e){case"B":case"BB":case"BBB":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,e,n){return t.setHours(un(n),0,0,0),t}}class ii extends Y{constructor(){super(...arguments);y(this,"priority",70);y(this,"incompatibleTokens",["H","K","k","t","T"])}parse(t,e,n){switch(e){case"h":return B(U.hour12h,t);case"ho":return n.ordinalNumber(t,{unit:"hour"});default:return V(e.length,t)}}validate(t,e){return e>=1&&e<=12}set(t,e,n){const s=t.getHours()>=12;return s&&n<12?t.setHours(n+12,0,0,0):!s&&n===12?t.setHours(0,0,0,0):t.setHours(n,0,0,0),t}}class ci extends Y{constructor(){super(...arguments);y(this,"priority",70);y(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(t,e,n){switch(e){case"H":return B(U.hour23h,t);case"Ho":return n.ordinalNumber(t,{unit:"hour"});default:return V(e.length,t)}}validate(t,e){return e>=0&&e<=23}set(t,e,n){return t.setHours(n,0,0,0),t}}class ui extends Y{constructor(){super(...arguments);y(this,"priority",70);y(this,"incompatibleTokens",["h","H","k","t","T"])}parse(t,e,n){switch(e){case"K":return B(U.hour11h,t);case"Ko":return n.ordinalNumber(t,{unit:"hour"});default:return V(e.length,t)}}validate(t,e){return e>=0&&e<=11}set(t,e,n){return t.getHours()>=12&&n<12?t.setHours(n+12,0,0,0):t.setHours(n,0,0,0),t}}class li extends Y{constructor(){super(...arguments);y(this,"priority",70);y(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(t,e,n){switch(e){case"k":return B(U.hour24h,t);case"ko":return n.ordinalNumber(t,{unit:"hour"});default:return V(e.length,t)}}validate(t,e){return e>=1&&e<=24}set(t,e,n){const s=n<=24?n%24:n;return t.setHours(s,0,0,0),t}}class di extends Y{constructor(){super(...arguments);y(this,"priority",60);y(this,"incompatibleTokens",["t","T"])}parse(t,e,n){switch(e){case"m":return B(U.minute,t);case"mo":return n.ordinalNumber(t,{unit:"minute"});default:return V(e.length,t)}}validate(t,e){return e>=0&&e<=59}set(t,e,n){return t.setMinutes(n,0,0),t}}class fi extends Y{constructor(){super(...arguments);y(this,"priority",50);y(this,"incompatibleTokens",["t","T"])}parse(t,e,n){switch(e){case"s":return B(U.second,t);case"so":return n.ordinalNumber(t,{unit:"second"});default:return V(e.length,t)}}validate(t,e){return e>=0&&e<=59}set(t,e,n){return t.setSeconds(n,0),t}}class pi extends Y{constructor(){super(...arguments);y(this,"priority",30);y(this,"incompatibleTokens",["t","T"])}parse(t,e){const n=s=>Math.trunc(s*Math.pow(10,-e.length+3));return j(V(e.length,t),n)}set(t,e,n){return t.setMilliseconds(n),t}}class hi extends Y{constructor(){super(...arguments);y(this,"priority",10);y(this,"incompatibleTokens",["t","T","x"])}parse(t,e){switch(e){case"X":return he(pe.basicOptionalMinutes,t);case"XX":return he(pe.basic,t);case"XXXX":return he(pe.basicOptionalSeconds,t);case"XXXXX":return he(pe.extendedOptionalSeconds,t);case"XXX":default:return he(pe.extended,t)}}set(t,e,n){return e.timestampIsSet?t:W(t,t.getTime()-Ct(t)-n)}}class mi extends Y{constructor(){super(...arguments);y(this,"priority",10);y(this,"incompatibleTokens",["t","T","X"])}parse(t,e){switch(e){case"x":return he(pe.basicOptionalMinutes,t);case"xx":return he(pe.basic,t);case"xxxx":return he(pe.basicOptionalSeconds,t);case"xxxxx":return he(pe.extendedOptionalSeconds,t);case"xxx":default:return he(pe.extended,t)}}set(t,e,n){return e.timestampIsSet?t:W(t,t.getTime()-Ct(t)-n)}}class gi extends Y{constructor(){super(...arguments);y(this,"priority",40);y(this,"incompatibleTokens","*")}parse(t){return yr(t)}set(t,e,n){return[W(t,n*1e3),{timestampIsSet:!0}]}}class wi extends Y{constructor(){super(...arguments);y(this,"priority",20);y(this,"incompatibleTokens","*")}parse(t){return yr(t)}set(t,e,n){return[W(t,n),{timestampIsSet:!0}]}}const Di={G:new Fo,y:new Lo,Y:new Wo,R:new Ao,u:new Ho,Q:new $o,q:new Qo,M:new Bo,L:new qo,w:new Vo,I:new jo,d:new zo,D:new Zo,E:new Jo,e:new ei,c:new ti,i:new ri,a:new ai,b:new si,B:new oi,h:new ii,H:new ci,K:new ui,k:new li,m:new di,s:new fi,S:new pi,X:new hi,x:new mi,t:new gi,T:new wi},yi=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,vi=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,bi=/^'([^]*?)'?$/,ki=/''/g,_i=/\S/,Mi=/[a-zA-Z]/;function xi(a,r,t,e){var w,k,S,x,N,q,$,I;const n=()=>W((e==null?void 0:e.in)||t,NaN),s=Po(),o=(e==null?void 0:e.locale)??s.locale??mr,i=(e==null?void 0:e.firstWeekContainsDate)??((k=(w=e==null?void 0:e.locale)==null?void 0:w.options)==null?void 0:k.firstWeekContainsDate)??s.firstWeekContainsDate??((x=(S=s.locale)==null?void 0:S.options)==null?void 0:x.firstWeekContainsDate)??1,c=(e==null?void 0:e.weekStartsOn)??((q=(N=e==null?void 0:e.locale)==null?void 0:N.options)==null?void 0:q.weekStartsOn)??s.weekStartsOn??((I=($=s.locale)==null?void 0:$.options)==null?void 0:I.weekStartsOn)??0;if(!r)return a?n():b(t,e==null?void 0:e.in);const u={firstWeekContainsDate:i,weekStartsOn:c,locale:o},l=[new Ro(e==null?void 0:e.in,t)],d=r.match(vi).map(_=>{const M=_[0];if(M in en){const F=en[M];return F(_,o.formatLong)}return _}).join("").match(yi),f=[];for(let _ of d){const M=_[0],F=Di[M];if(F){const{incompatibleTokens:X}=F;if(Array.isArray(X)){const J=f.find(le=>X.includes(le.token)||le.token===M);if(J)throw new RangeError(`The format string mustn't contain \`${J.fullToken}\` and \`${_}\` at the same time`)}else if(F.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${_}\` and any other token at the same time`);f.push({token:M,fullToken:_});const K=F.run(a,_,o.match,u);if(!K)return n();l.push(K.setter),a=K.rest}else{if(M.match(Mi))throw new RangeError("Format string contains an unescaped latin alphabet character `"+M+"`");if(_==="''"?_="'":M==="'"&&(_=Si(_)),a.indexOf(_)===0)a=a.slice(_.length);else return n()}}if(a.length>0&&_i.test(a))return n();const p=l.map(_=>_.priority).sort((_,M)=>M-_).filter((_,M,F)=>F.indexOf(_)===M).map(_=>l.filter(M=>M.priority===_).sort((M,F)=>F.subPriority-M.subPriority)).map(_=>_[0]);let h=b(t,e==null?void 0:e.in);if(isNaN(+h))return n();const g={};for(const _ of p){if(!_.validate(h,u))return n();const M=_.set(h,g,u);Array.isArray(M)?(h=M[0],Object.assign(g,M[1])):h=M}return h}function Si(a){return a.match(bi)[1].replace(ki,"'")}function Ci(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r);return e.getFullYear()===n.getFullYear()&&e.getMonth()===n.getMonth()}function Pi(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r);return+Jt(e)==+Jt(n)}function Ti(a,r,t){const[e,n]=ke(t==null?void 0:t.in,a,r);return e.getFullYear()===n.getFullYear()}function ut(a,r,t){const e=+b(a,t==null?void 0:t.in),[n,s]=[+b(r.start,t==null?void 0:t.in),+b(r.end,t==null?void 0:t.in)].sort((o,i)=>o-i);return e>=n&&e<=s}function Oi(a,r,t){return ce(a,-1,t)}function Ei(a,r){const t=()=>W(r==null?void 0:r.in,NaN),n=Ri(a);let s;if(n.date){const u=Fi(n.date,2);s=Li(u.restDateString,u.year)}if(!s||isNaN(+s))return t();const o=+s;let i=0,c;if(n.time&&(i=Wi(n.time),isNaN(i)))return t();if(n.timezone){if(c=Ai(n.timezone),isNaN(c))return t()}else{const u=new Date(o+i),l=b(0,r==null?void 0:r.in);return l.setFullYear(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),l.setHours(u.getUTCHours(),u.getUTCMinutes(),u.getUTCSeconds(),u.getUTCMilliseconds()),l}return b(o+i+c,r==null?void 0:r.in)}const ht={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Ni=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Yi=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,Ii=/^([+-])(\d{2})(?::?(\d{2}))?$/;function Ri(a){const r={},t=a.split(ht.dateTimeDelimiter);let e;if(t.length>2)return r;if(/:/.test(t[0])?e=t[0]:(r.date=t[0],e=t[1],ht.timeZoneDelimiter.test(r.date)&&(r.date=a.split(ht.timeZoneDelimiter)[0],e=a.substr(r.date.length,a.length))),e){const n=ht.timezone.exec(e);n?(r.time=e.replace(n[1],""),r.timezone=n[1]):r.time=e}return r}function Fi(a,r){const t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+r)+"})|(\\d{2}|[+-]\\d{"+(2+r)+"})$)"),e=a.match(t);if(!e)return{year:NaN,restDateString:""};const n=e[1]?parseInt(e[1]):null,s=e[2]?parseInt(e[2]):null;return{year:s===null?n:s*100,restDateString:a.slice((e[1]||e[2]).length)}}function Li(a,r){if(r===null)return new Date(NaN);const t=a.match(Ni);if(!t)return new Date(NaN);const e=!!t[4],n=rt(t[1]),s=rt(t[2])-1,o=rt(t[3]),i=rt(t[4]),c=rt(t[5])-1;if(e)return qi(r,i,c)?Hi(r,i,c):new Date(NaN);{const u=new Date(0);return!Qi(r,s,o)||!Bi(r,n)?new Date(NaN):(u.setUTCFullYear(r,s,Math.max(n,o)),u)}}function rt(a){return a?parseInt(a):1}function Wi(a){const r=a.match(Yi);if(!r)return NaN;const t=Vt(r[1]),e=Vt(r[2]),n=Vt(r[3]);return Ki(t,e,n)?t*At+e*Wt+n*1e3:NaN}function Vt(a){return a&&parseFloat(a.replace(",","."))||0}function Ai(a){if(a==="Z")return 0;const r=a.match(Ii);if(!r)return 0;const t=r[1]==="+"?-1:1,e=parseInt(r[2]),n=r[3]&&parseInt(r[3])||0;return Vi(e,n)?t*(e*At+n*Wt):NaN}function Hi(a,r,t){const e=new Date(0);e.setUTCFullYear(a,0,4);const n=e.getUTCDay()||7,s=(r-1)*7+t+1-n;return e.setUTCDate(e.getUTCDate()+s),e}const $i=[31,null,31,30,31,30,31,31,30,31,30,31];function kr(a){return a%400===0||a%4===0&&a%100!==0}function Qi(a,r,t){return r>=0&&r<=11&&t>=1&&t<=($i[r]||(kr(a)?29:28))}function Bi(a,r){return r>=1&&r<=(kr(a)?366:365)}function qi(a,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function Ki(a,r,t){return a===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&a>=0&&a<25}function Vi(a,r){return r>=0&&r<=59}function ae(a,r,t){const e=b(a,t==null?void 0:t.in),n=e.getFullYear(),s=e.getDate(),o=W(a,0);o.setFullYear(n,r,15),o.setHours(0,0,0,0);const i=Co(o);return e.setMonth(r,Math.min(s,i)),e}function vt(a,r,t){const e=b(a,t==null?void 0:t.in);return e.setHours(r),e}function bt(a,r,t){const e=b(a,t==null?void 0:t.in);return e.setMinutes(r),e}function $e(a,r,t){const e=b(a,t==null?void 0:t.in),n=Math.trunc(e.getMonth()/3)+1,s=r-n;return ae(e,e.getMonth()+s*3)}function kt(a,r,t){const e=b(a,t==null?void 0:t.in);return e.setSeconds(r),e}function de(a,r,t){const e=b(a,t==null?void 0:t.in);return isNaN(+e)?W(a,NaN):(e.setFullYear(r),e)}function Ie(a,r,t){return ue(a,-r,t)}function _r(a,r,t){return sn(a,-1,t)}function Nn(a,r,t){return Pt(a,-1,t)}function Ue(a,r,t){return ge(a,-r,t)}const Mr={...Fr},Ui=Mr.useInsertionEffect,ji=Ui||(a=>a());function Xi(a){const r=v.useRef(()=>{});return ji(()=>{r.current=a}),v.useCallback(function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return r.current==null?void 0:r.current(...e)},[])}var It=typeof document<"u"?v.useLayoutEffect:v.useEffect;let Yn=!1,Gi=0;const In=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+Gi++;function zi(){const[a,r]=v.useState(()=>Yn?In():void 0);return It(()=>{a==null&&r(In())},[]),v.useEffect(()=>{Yn=!0},[]),a}const Zi=Mr.useId,xr=Zi||zi,Ji=v.forwardRef(function(r,t){const{context:{placement:e,elements:{floating:n},middlewareData:{arrow:s,shift:o}},width:i=14,height:c=7,tipRadius:u=0,strokeWidth:l=0,staticOffset:d,stroke:f,d:p,style:{transform:h,...g}={},...w}=r,k=xr(),[S,x]=v.useState(!1);if(It(()=>{if(!n)return;Wr(n).direction==="rtl"&&x(!0)},[n]),!n)return null;const[N,q]=e.split("-"),$=N==="top"||N==="bottom";let I=d;($&&o!=null&&o.x||!$&&o!=null&&o.y)&&(I=null);const _=l*2,M=_/2,F=i/2*(u/-8+1),X=c/2*u/4,K=!!p,J=I&&q==="end"?"bottom":"top";let le=I&&q==="end"?"right":"left";I&&S&&(le=q==="end"?"left":"right");const G=(s==null?void 0:s.x)!=null?I||s.x:"",A=(s==null?void 0:s.y)!=null?I||s.y:"",Q=p||"M0,0"+(" H"+i)+(" L"+(i-F)+","+(c-X))+(" Q"+i/2+","+c+" "+F+","+(c-X))+" Z",ne={top:K?"rotate(180deg)":"",left:K?"rotate(90deg)":"rotate(-90deg)",bottom:K?"":"rotate(180deg)",right:K?"rotate(-90deg)":"rotate(90deg)"}[N];return Ge.jsxs("svg",{...w,"aria-hidden":!0,ref:t,width:K?i:i+_,height:i,viewBox:"0 0 "+i+" "+(c>i?c:i),style:{position:"absolute",pointerEvents:"none",[le]:G,[J]:A,[N]:$||K?"100%":"calc(100% - "+_/2+"px)",transform:[ne,h].filter(Xe=>!!Xe).join(" "),...g},children:[_>0&&Ge.jsx("path",{clipPath:"url(#"+k+")",fill:"none",stroke:f,strokeWidth:_+(p?0:1),d:Q}),Ge.jsx("path",{stroke:_&&!p?w.fill:"none",d:Q}),Ge.jsx("clipPath",{id:k,children:Ge.jsx("rect",{x:-M,y:M*(K?-1:1),width:i+_,height:i})})]})});function ec(){const a=new Map;return{emit(r,t){var e;(e=a.get(r))==null||e.forEach(n=>n(t))},on(r,t){a.set(r,[...a.get(r)||[],t])},off(r,t){var e;a.set(r,((e=a.get(r))==null?void 0:e.filter(n=>n!==t))||[])}}}const tc=v.createContext(null),nc=v.createContext(null),rc=()=>{var a;return((a=v.useContext(tc))==null?void 0:a.id)||null},ac=()=>v.useContext(nc);function sc(a){const{open:r=!1,onOpenChange:t,elements:e}=a,n=xr(),s=v.useRef({}),[o]=v.useState(()=>ec()),i=rc()!=null,[c,u]=v.useState(e.reference),l=Xi((p,h,g)=>{s.current.openEvent=p?h:void 0,o.emit("openchange",{open:p,event:h,reason:g,nested:i}),t==null||t(p,h,g)}),d=v.useMemo(()=>({setPositionReference:u}),[]),f=v.useMemo(()=>({reference:c||e.reference||null,floating:e.floating||null,domReference:e.reference}),[c,e.reference,e.floating]);return v.useMemo(()=>({dataRef:s,open:r,onOpenChange:l,elements:f,events:o,floatingId:n,refs:d}),[r,l,f,o,n,d])}function oc(a){a===void 0&&(a={});const{nodeId:r}=a,t=sc({...a,elements:{reference:null,floating:null,...a.elements}}),e=a.rootContext||t,n=e.elements,[s,o]=v.useState(null),[i,c]=v.useState(null),l=(n==null?void 0:n.domReference)||s,d=v.useRef(null),f=ac();It(()=>{l&&(d.current=l)},[l]);const p=Ar({...a,elements:{...n,...i&&{reference:i}}}),h=v.useCallback(x=>{const N=ft(x)?{getBoundingClientRect:()=>x.getBoundingClientRect(),contextElement:x}:x;c(N),p.refs.setReference(N)},[p.refs]),g=v.useCallback(x=>{(ft(x)||x===null)&&(d.current=x,o(x)),(ft(p.refs.reference.current)||p.refs.reference.current===null||x!==null&&!ft(x))&&p.refs.setReference(x)},[p.refs]),w=v.useMemo(()=>({...p.refs,setReference:g,setPositionReference:h,domReference:d}),[p.refs,g,h]),k=v.useMemo(()=>({...p.elements,domReference:l}),[p.elements,l]),S=v.useMemo(()=>({...p,...e,refs:w,elements:k,nodeId:r}),[p,w,k,r,e]);return It(()=>{e.dataRef.current.floatingContext=S;const x=f==null?void 0:f.nodesRef.current.find(N=>N.id===r);x&&(x.context=S)}),v.useMemo(()=>({...p,context:S,refs:w,elements:k}),[p,w,k,S])}/*! + react-datepicker v8.0.0 + https://github.com/Hacker0x01/react-datepicker + Released under the MIT License. +*/var nn=function(r,t){return nn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])},nn(r,t)};function z(a,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");nn(a,r);function t(){this.constructor=a}a.prototype=r===null?Object.create(r):(t.prototype=r.prototype,new t)}var E=function(){return E=Object.assign||function(t){for(var e,n=1,s=arguments.length;n<s;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},E.apply(this,arguments)};function me(a,r,t){if(t||arguments.length===2)for(var e=0,n=r.length,s;e<n;e++)(s||!(e in r))&&(s||(s=Array.prototype.slice.call(r,0,e)),s[e]=r[e]);return a.concat(s||Array.prototype.slice.call(r))}var ic=function(a){var r=a.showTimeSelectOnly,t=r===void 0?!1:r,e=a.showTime,n=e===void 0?!1:e,s=a.className,o=a.children,i=t?"Choose Time":"Choose Date".concat(n?" and Time":"");return m.createElement("div",{className:s,role:"dialog","aria-label":i,"aria-modal":"true"},o)},cc=function(a,r){var t=v.useRef(null),e=v.useRef(a);e.current=a;var n=v.useCallback(function(s){var o,i=s.composed&&s.composedPath&&s.composedPath().find(function(c){return c instanceof Node})||s.target;t.current&&!t.current.contains(i)&&(r&&i instanceof HTMLElement&&i.classList.contains(r)||(o=e.current)===null||o===void 0||o.call(e,s))},[r]);return v.useEffect(function(){return document.addEventListener("mousedown",n),function(){document.removeEventListener("mousedown",n)}},[n]),t},$t=function(a){var r=a.children,t=a.onClickOutside,e=a.className,n=a.containerRef,s=a.style,o=a.ignoreClass,i=cc(t,o);return m.createElement("div",{className:e,style:s,ref:function(c){i.current=c,n&&(n.current=c)}},r)},D;(function(a){a.ArrowUp="ArrowUp",a.ArrowDown="ArrowDown",a.ArrowLeft="ArrowLeft",a.ArrowRight="ArrowRight",a.PageUp="PageUp",a.PageDown="PageDown",a.Home="Home",a.End="End",a.Enter="Enter",a.Space=" ",a.Tab="Tab",a.Escape="Escape",a.Backspace="Backspace",a.X="x"})(D||(D={}));function Sr(){var a=typeof window<"u"?window:globalThis;return a}var lt=12;function R(a){if(a==null)return new Date;var r=typeof a=="string"?Ei(a):b(a);return Qt(r)?r:new Date}function Ut(a,r,t,e,n){n===void 0&&(n=R());for(var s=je(t)||je(dn()),o=Array.isArray(r)?r:[r],i=0,c=o;i<c.length;i++){var u=c[i],l=xi(a,u,n,{locale:s,useAdditionalWeekYearTokens:!0,useAdditionalDayOfYearTokens:!0});if(Qt(l)&&(!e||a===H(l,u,t)))return l}return null}function Qt(a,r){return Tt(a)&&!Fe(a,new Date("1/1/1800"))}function H(a,r,t){if(t==="en")return On(a,r,{useAdditionalWeekYearTokens:!0,useAdditionalDayOfYearTokens:!0});var e=t?je(t):void 0;return t&&!e&&console.warn('A locale object was not found for the provided string ["'.concat(t,'"].')),e=e||je(dn()),On(a,r,{locale:e,useAdditionalWeekYearTokens:!0,useAdditionalDayOfYearTokens:!0})}function re(a,r){var t=r.dateFormat,e=r.locale,n=Array.isArray(t)&&t.length>0?t[0]:t;return a&&H(a,n,e)||""}function uc(a,r,t){if(!a)return"";var e=re(a,t),n=r?re(r,t):"";return"".concat(e," - ").concat(n)}function lc(a,r){if(!(a!=null&&a.length))return"";var t=a[0]?re(a[0],r):"";if(a.length===1)return t;if(a.length===2&&a[1]){var e=re(a[1],r);return"".concat(t,", ").concat(e)}var n=a.length-1;return"".concat(t," (+").concat(n,")")}function jt(a,r){var t=r.hour,e=t===void 0?0:t,n=r.minute,s=n===void 0?0:n,o=r.second,i=o===void 0?0:o;return vt(bt(kt(a,i),s),e)}function dc(a){return on(a)}function fc(a,r){return H(a,"ddd",r)}function _t(a){return Re(a)}function Ce(a,r,t){var e=je(r||dn());return be(a,{locale:e,weekStartsOn:t})}function ve(a){return pr(a)}function st(a){return Ht(a)}function Rn(a){return Jt(a)}function Fn(){return Re(R())}function Ln(a){return dr(a)}function pc(a){return Os(a)}function hc(a){return fr(a)}function fe(a,r){return a&&r?Ti(a,r):!a&&!r}function ee(a,r){return a&&r?Ci(a,r):!a&&!r}function Rt(a,r){return a&&r?Pi(a,r):!a&&!r}function O(a,r){return a&&r?Ps(a,r):!a&&!r}function Ee(a,r){return a&&r?Oo(a,r):!a&&!r}function ot(a,r,t){var e,n=Re(r),s=dr(t);try{e=ut(a,{start:n,end:s})}catch{e=!1}return e}function dn(){var a=Sr();return a.__localeId__}function je(a){if(typeof a=="string"){var r=Sr();return r.__localeData__?r.__localeData__[a]:void 0}else return a}function mc(a,r,t){return r(H(a,"EEEE",t))}function gc(a,r){return H(a,"EEEEEE",r)}function wc(a,r){return H(a,"EEE",r)}function fn(a,r){return H(ae(R(),a),"LLLL",r)}function Cr(a,r){return H(ae(R(),a),"LLL",r)}function Dc(a,r){return H($e(R(),a),"QQQ",r)}function se(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.maxDate,s=t.excludeDates,o=t.excludeDateIntervals,i=t.includeDates,c=t.includeDateIntervals,u=t.filterDate;return dt(a,{minDate:e,maxDate:n})||s&&s.some(function(l){return l instanceof Date?O(a,l):O(a,l.date)})||o&&o.some(function(l){var d=l.start,f=l.end;return ut(a,{start:d,end:f})})||i&&!i.some(function(l){return O(a,l)})||c&&!c.some(function(l){var d=l.start,f=l.end;return ut(a,{start:d,end:f})})||u&&!u(R(a))||!1}function pn(a,r){var t=r===void 0?{}:r,e=t.excludeDates,n=t.excludeDateIntervals;return n&&n.length>0?n.some(function(s){var o=s.start,i=s.end;return ut(a,{start:o,end:i})}):e&&e.some(function(s){var o;return s instanceof Date?O(a,s):O(a,(o=s.date)!==null&&o!==void 0?o:new Date)})||!1}function Pr(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.maxDate,s=t.excludeDates,o=t.includeDates,i=t.filterDate;return dt(a,{minDate:e?pr(e):void 0,maxDate:n?fr(n):void 0})||(s==null?void 0:s.some(function(c){return ee(a,c instanceof Date?c:c.date)}))||o&&!o.some(function(c){return ee(a,c)})||i&&!i(R(a))||!1}function mt(a,r,t,e){var n=P(a),s=te(a),o=P(r),i=te(r),c=P(e);return n===o&&n===c?s<=t&&t<=i:n<o?c===n&&s<=t||c===o&&i>=t||c<o&&c>n:!1}function yc(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.maxDate,s=t.excludeDates,o=t.includeDates;return dt(a,{minDate:e,maxDate:n})||s&&s.some(function(i){return ee(i instanceof Date?i:i.date,a)})||o&&!o.some(function(i){return ee(i,a)})||!1}function gt(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.maxDate,s=t.excludeDates,o=t.includeDates,i=t.filterDate;return dt(a,{minDate:e,maxDate:n})||(s==null?void 0:s.some(function(c){return Rt(a,c instanceof Date?c:c.date)}))||o&&!o.some(function(c){return Rt(a,c)})||i&&!i(R(a))||!1}function wt(a,r,t){if(!r||!t||!Tt(r)||!Tt(t))return!1;var e=P(r),n=P(t);return e<=a&&n>=a}function Mt(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.maxDate,s=t.excludeDates,o=t.includeDates,i=t.filterDate,c=new Date(a,0,1);return dt(c,{minDate:e?Ht(e):void 0,maxDate:n?hr(n):void 0})||(s==null?void 0:s.some(function(u){return fe(c,u instanceof Date?u:u.date)}))||o&&!o.some(function(u){return fe(c,u)})||i&&!i(R(c))||!1}function Dt(a,r,t,e){var n=P(a),s=Ye(a),o=P(r),i=Ye(r),c=P(e);return n===o&&n===c?s<=t&&t<=i:n<o?c===n&&s<=t||c===o&&i>=t||c<o&&c>n:!1}function dt(a,r){var t,e=r===void 0?{}:r,n=e.minDate,s=e.maxDate;return(t=n&&Ve(a,n)<0||s&&Ve(a,s)>0)!==null&&t!==void 0?t:!1}function Wn(a,r){return r.some(function(t){return De(t)===De(a)&&ye(t)===ye(a)&&Se(t)===Se(a)})}function An(a,r){var t=r===void 0?{}:r,e=t.excludeTimes,n=t.includeTimes,s=t.filterTime;return e&&Wn(a,e)||n&&!Wn(a,n)||s&&!s(a)||!1}function Hn(a,r){var t=r.minTime,e=r.maxTime;if(!t||!e)throw new Error("Both minTime and maxTime props required");var n=R();n=vt(n,De(a)),n=bt(n,ye(a)),n=kt(n,Se(a));var s=R();s=vt(s,De(t)),s=bt(s,ye(t)),s=kt(s,Se(t));var o=R();o=vt(o,De(e)),o=bt(o,ye(e)),o=kt(o,Se(e));var i;try{i=!ut(n,{start:s,end:o})}catch{i=!1}return i}function $n(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.includeDates,s=Ie(a,1);return e&&Ot(e,s)>0||n&&n.every(function(o){return Ot(o,s)>0})||!1}function Qn(a,r){var t=r===void 0?{}:r,e=t.maxDate,n=t.includeDates,s=ue(a,1);return e&&Ot(s,e)>0||n&&n.every(function(o){return Ot(s,o)>0})||!1}function vc(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.includeDates,s=Ht(a),o=_r(s);return e&&Et(e,o)>0||n&&n.every(function(i){return Et(i,o)>0})||!1}function bc(a,r){var t=r===void 0?{}:r,e=t.maxDate,n=t.includeDates,s=hr(a),o=sn(s,1);return e&&Et(o,e)>0||n&&n.every(function(i){return Et(o,i)>0})||!1}function Bn(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.includeDates,s=Ue(a,1);return e&&Nt(e,s)>0||n&&n.every(function(o){return Nt(o,s)>0})||!1}function kc(a,r){var t=r===void 0?{}:r,e=t.minDate,n=t.yearItemNumber,s=n===void 0?lt:n,o=st(Ue(a,s)),i=xe(o,s).endPeriod,c=e&&P(e);return c&&c>i||!1}function qn(a,r){var t=r===void 0?{}:r,e=t.maxDate,n=t.includeDates,s=ge(a,1);return e&&Nt(s,e)>0||n&&n.every(function(o){return Nt(s,o)>0})||!1}function _c(a,r){var t=r===void 0?{}:r,e=t.maxDate,n=t.yearItemNumber,s=n===void 0?lt:n,o=ge(a,s),i=xe(o,s).startPeriod,c=e&&P(e);return c&&c<i||!1}function Tr(a){var r=a.minDate,t=a.includeDates;if(t&&r){var e=t.filter(function(n){return Ve(n,r)>=0});return Mn(e)}else return t?Mn(t):r}function Or(a){var r=a.maxDate,t=a.includeDates;if(t&&r){var e=t.filter(function(n){return Ve(n,r)<=0});return _n(e)}else return t?_n(t):r}function Kn(a,r){var t;a===void 0&&(a=[]),r===void 0&&(r="react-datepicker__day--highlighted");for(var e=new Map,n=0,s=a.length;n<s;n++){var o=a[n];if(we(o)){var i=H(o,"MM.dd.yyyy"),c=e.get(i)||[];c.includes(r)||(c.push(r),e.set(i,c))}else if(typeof o=="object"){var u=Object.keys(o),l=(t=u[0])!==null&&t!==void 0?t:"",d=o[l];if(typeof l=="string"&&Array.isArray(d))for(var f=0,p=d.length;f<p;f++){var h=d[f];if(h){var i=H(h,"MM.dd.yyyy"),c=e.get(i)||[];c.includes(l)||(c.push(l),e.set(i,c))}}}}return e}function Mc(a,r){return a.length!==r.length?!1:a.every(function(t,e){return t===r[e]})}function xc(a,r){a===void 0&&(a=[]),r===void 0&&(r="react-datepicker__day--holidays");var t=new Map;return a.forEach(function(e){var n=e.date,s=e.holidayName;if(we(n)){var o=H(n,"MM.dd.yyyy"),i=t.get(o)||{className:"",holidayNames:[]};if(!("className"in i&&i.className===r&&Mc(i.holidayNames,[s]))){i.className=r;var c=i.holidayNames;i.holidayNames=c?me(me([],c,!0),[s],!1):[s],t.set(o,i)}}}),t}function Sc(a,r,t,e,n){for(var s=n.length,o=[],i=0;i<s;i++){var c=a,u=n[i];u&&(c=Ms(c,De(u)),c=Zt(c,ye(u)),c=Cs(c,Se(u)));var l=Zt(a,(t+1)*e);Pe(c,r)&&Fe(c,l)&&u!=null&&o.push(u)}return o}function Vn(a){return a<10?"0".concat(a):"".concat(a)}function xe(a,r){r===void 0&&(r=lt);var t=Math.ceil(P(a)/r)*r,e=t-(r-1);return{startPeriod:e,endPeriod:t}}function Cc(a){var r=new Date(a.getFullYear(),a.getMonth(),a.getDate()),t=new Date(a.getFullYear(),a.getMonth(),a.getDate(),24);return Math.round((+t-+r)/36e5)}function Un(a){var r=a.getSeconds(),t=a.getMilliseconds();return b(a.getTime()-r*1e3-t)}function Pc(a,r){return Un(a).getTime()===Un(r).getTime()}function jn(a){if(!we(a))throw new Error("Invalid date");var r=new Date(a);return r.setHours(0,0,0,0),r}function Xn(a,r){if(!we(a)||!we(r))throw new Error("Invalid date received");var t=jn(a),e=jn(r);return Fe(t,e)}function Er(a){return a.key===D.Space}var Tc=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.inputRef=m.createRef(),e.onTimeChange=function(n){var s,o;e.setState({time:n});var i=e.props.date,c=i instanceof Date&&!isNaN(+i),u=c?i:new Date;if(n!=null&&n.includes(":")){var l=n.split(":"),d=l[0],f=l[1];u.setHours(Number(d)),u.setMinutes(Number(f))}(o=(s=e.props).onChange)===null||o===void 0||o.call(s,u)},e.renderTimeInput=function(){var n=e.state.time,s=e.props,o=s.date,i=s.timeString,c=s.customTimeInput;return c?v.cloneElement(c,{date:o,value:n,onChange:e.onTimeChange}):m.createElement("input",{type:"time",className:"react-datepicker-time__input",placeholder:"Time",name:"time-input",ref:e.inputRef,onClick:function(){var u;(u=e.inputRef.current)===null||u===void 0||u.focus()},required:!0,value:n,onChange:function(u){e.onTimeChange(u.target.value||i)}})},e.state={time:e.props.timeString},e}return r.getDerivedStateFromProps=function(t,e){return t.timeString!==e.time?{time:t.timeString}:null},r.prototype.render=function(){return m.createElement("div",{className:"react-datepicker__input-time-container"},m.createElement("div",{className:"react-datepicker-time__caption"},this.props.timeInputLabel),m.createElement("div",{className:"react-datepicker-time__input-container"},m.createElement("div",{className:"react-datepicker-time__input"},this.renderTimeInput())))},r}(v.Component),Oc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.dayEl=v.createRef(),t.handleClick=function(e){!t.isDisabled()&&t.props.onClick&&t.props.onClick(e)},t.handleMouseEnter=function(e){!t.isDisabled()&&t.props.onMouseEnter&&t.props.onMouseEnter(e)},t.handleOnKeyDown=function(e){var n,s,o=e.key;o===D.Space&&(e.preventDefault(),e.key=D.Enter),(s=(n=t.props).handleOnKeyDown)===null||s===void 0||s.call(n,e)},t.isSameDay=function(e){return O(t.props.day,e)},t.isKeyboardSelected=function(){var e;if(t.props.disabledKeyboardNavigation)return!1;var n=t.props.selectsMultiple?(e=t.props.selectedDates)===null||e===void 0?void 0:e.some(function(o){return t.isSameDayOrWeek(o)}):t.isSameDayOrWeek(t.props.selected),s=t.props.preSelection&&t.isDisabled(t.props.preSelection);return!n&&t.isSameDayOrWeek(t.props.preSelection)&&!s},t.isDisabled=function(e){return e===void 0&&(e=t.props.day),se(e,{minDate:t.props.minDate,maxDate:t.props.maxDate,excludeDates:t.props.excludeDates,excludeDateIntervals:t.props.excludeDateIntervals,includeDateIntervals:t.props.includeDateIntervals,includeDates:t.props.includeDates,filterDate:t.props.filterDate})},t.isExcluded=function(){return pn(t.props.day,{excludeDates:t.props.excludeDates,excludeDateIntervals:t.props.excludeDateIntervals})},t.isStartOfWeek=function(){return O(t.props.day,Ce(t.props.day,t.props.locale,t.props.calendarStartDay))},t.isSameWeek=function(e){return t.props.showWeekPicker&&O(e,Ce(t.props.day,t.props.locale,t.props.calendarStartDay))},t.isSameDayOrWeek=function(e){return t.isSameDay(e)||t.isSameWeek(e)},t.getHighLightedClass=function(){var e=t.props,n=e.day,s=e.highlightDates;if(!s)return!1;var o=H(n,"MM.dd.yyyy");return s.get(o)},t.getHolidaysClass=function(){var e,n=t.props,s=n.day,o=n.holidays;if(!o)return[void 0];var i=H(s,"MM.dd.yyyy");return o.has(i)?[(e=o.get(i))===null||e===void 0?void 0:e.className]:[void 0]},t.isInRange=function(){var e=t.props,n=e.day,s=e.startDate,o=e.endDate;return!s||!o?!1:ot(n,s,o)},t.isInSelectingRange=function(){var e,n=t.props,s=n.day,o=n.selectsStart,i=n.selectsEnd,c=n.selectsRange,u=n.selectsDisabledDaysInRange,l=n.startDate,d=n.endDate,f=(e=t.props.selectingDate)!==null&&e!==void 0?e:t.props.preSelection;return!(o||i||c)||!f||!u&&t.isDisabled()?!1:o&&d&&(Fe(f,d)||Ee(f,d))?ot(s,f,d):i&&l&&(Pe(f,l)||Ee(f,l))||c&&l&&!d&&(Pe(f,l)||Ee(f,l))?ot(s,l,f):!1},t.isSelectingRangeStart=function(){var e;if(!t.isInSelectingRange())return!1;var n=t.props,s=n.day,o=n.startDate,i=n.selectsStart,c=(e=t.props.selectingDate)!==null&&e!==void 0?e:t.props.preSelection;return i?O(s,c):O(s,o)},t.isSelectingRangeEnd=function(){var e;if(!t.isInSelectingRange())return!1;var n=t.props,s=n.day,o=n.endDate,i=n.selectsEnd,c=n.selectsRange,u=(e=t.props.selectingDate)!==null&&e!==void 0?e:t.props.preSelection;return i||c?O(s,u):O(s,o)},t.isRangeStart=function(){var e=t.props,n=e.day,s=e.startDate,o=e.endDate;return!s||!o?!1:O(s,n)},t.isRangeEnd=function(){var e=t.props,n=e.day,s=e.startDate,o=e.endDate;return!s||!o?!1:O(o,n)},t.isWeekend=function(){var e=So(t.props.day);return e===0||e===6},t.isAfterMonth=function(){return t.props.month!==void 0&&(t.props.month+1)%12===te(t.props.day)},t.isBeforeMonth=function(){return t.props.month!==void 0&&(te(t.props.day)+1)%12===t.props.month},t.isCurrentDay=function(){return t.isSameDay(R())},t.isSelected=function(){var e;return t.props.selectsMultiple?(e=t.props.selectedDates)===null||e===void 0?void 0:e.some(function(n){return t.isSameDayOrWeek(n)}):t.isSameDayOrWeek(t.props.selected)},t.getClassNames=function(e){var n=t.props.dayClassName?t.props.dayClassName(e):void 0;return Z("react-datepicker__day",n,"react-datepicker__day--"+fc(t.props.day),{"react-datepicker__day--disabled":t.isDisabled(),"react-datepicker__day--excluded":t.isExcluded(),"react-datepicker__day--selected":t.isSelected(),"react-datepicker__day--keyboard-selected":t.isKeyboardSelected(),"react-datepicker__day--range-start":t.isRangeStart(),"react-datepicker__day--range-end":t.isRangeEnd(),"react-datepicker__day--in-range":t.isInRange(),"react-datepicker__day--in-selecting-range":t.isInSelectingRange(),"react-datepicker__day--selecting-range-start":t.isSelectingRangeStart(),"react-datepicker__day--selecting-range-end":t.isSelectingRangeEnd(),"react-datepicker__day--today":t.isCurrentDay(),"react-datepicker__day--weekend":t.isWeekend(),"react-datepicker__day--outside-month":t.isAfterMonth()||t.isBeforeMonth()},t.getHighLightedClass(),t.getHolidaysClass())},t.getAriaLabel=function(){var e=t.props,n=e.day,s=e.ariaLabelPrefixWhenEnabled,o=s===void 0?"Choose":s,i=e.ariaLabelPrefixWhenDisabled,c=i===void 0?"Not available":i,u=t.isDisabled()||t.isExcluded()?c:o;return"".concat(u," ").concat(H(n,"PPPP",t.props.locale))},t.getTitle=function(){var e=t.props,n=e.day,s=e.holidays,o=s===void 0?new Map:s,i=e.excludeDates,c=H(n,"MM.dd.yyyy"),u=[];return o.has(c)&&u.push.apply(u,o.get(c).holidayNames),t.isExcluded()&&u.push(i==null?void 0:i.filter(function(l){return l instanceof Date?O(l,n):O(l==null?void 0:l.date,n)}).map(function(l){if(!(l instanceof Date))return l==null?void 0:l.message})),u.join(", ")},t.getTabIndex=function(){var e=t.props.selected,n=t.props.preSelection,s=!(t.props.showWeekPicker&&(t.props.showWeekNumber||!t.isStartOfWeek()))&&(t.isKeyboardSelected()||t.isSameDay(e)&&O(n,e))?0:-1;return s},t.handleFocusDay=function(){var e;t.shouldFocusDay()&&((e=t.dayEl.current)===null||e===void 0||e.focus({preventScroll:!0}))},t.renderDayContents=function(){return t.props.monthShowsDuplicateDaysEnd&&t.isAfterMonth()||t.props.monthShowsDuplicateDaysStart&&t.isBeforeMonth()?null:t.props.renderDayContents?t.props.renderDayContents(En(t.props.day),t.props.day):En(t.props.day)},t.render=function(){return m.createElement("div",{ref:t.dayEl,className:t.getClassNames(t.props.day),onKeyDown:t.handleOnKeyDown,onClick:t.handleClick,onMouseEnter:t.props.usePointerEvent?void 0:t.handleMouseEnter,onPointerEnter:t.props.usePointerEvent?t.handleMouseEnter:void 0,tabIndex:t.getTabIndex(),"aria-label":t.getAriaLabel(),role:"option",title:t.getTitle(),"aria-disabled":t.isDisabled(),"aria-current":t.isCurrentDay()?"date":void 0,"aria-selected":t.isSelected()||t.isInRange()},t.renderDayContents(),t.getTitle()!==""&&m.createElement("span",{className:"overlay"},t.getTitle()))},t}return r.prototype.componentDidMount=function(){this.handleFocusDay()},r.prototype.componentDidUpdate=function(){this.handleFocusDay()},r.prototype.shouldFocusDay=function(){var t=!1;return this.getTabIndex()===0&&this.isSameDay(this.props.preSelection)&&((!document.activeElement||document.activeElement===document.body)&&(t=!0),this.props.inline&&!this.props.shouldFocusDayInline&&(t=!1),this.isDayActiveElement()&&(t=!0),this.isDuplicateDay()&&(t=!1)),t},r.prototype.isDayActiveElement=function(){var t,e,n;return((e=(t=this.props.containerRef)===null||t===void 0?void 0:t.current)===null||e===void 0?void 0:e.contains(document.activeElement))&&((n=document.activeElement)===null||n===void 0?void 0:n.classList.contains("react-datepicker__day"))},r.prototype.isDuplicateDay=function(){return this.props.monthShowsDuplicateDaysEnd&&this.isAfterMonth()||this.props.monthShowsDuplicateDaysStart&&this.isBeforeMonth()},r}(v.Component),Ec=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.weekNumberEl=v.createRef(),t.handleClick=function(e){t.props.onClick&&t.props.onClick(e)},t.handleOnKeyDown=function(e){var n,s,o=e.key;o===D.Space&&(e.preventDefault(),e.key=D.Enter),(s=(n=t.props).handleOnKeyDown)===null||s===void 0||s.call(n,e)},t.isKeyboardSelected=function(){return!t.props.disabledKeyboardNavigation&&!O(t.props.date,t.props.selected)&&O(t.props.date,t.props.preSelection)},t.getTabIndex=function(){return t.props.showWeekPicker&&t.props.showWeekNumber&&(t.isKeyboardSelected()||O(t.props.date,t.props.selected)&&O(t.props.preSelection,t.props.selected))?0:-1},t.handleFocusWeekNumber=function(e){var n=!1;t.getTabIndex()===0&&!(e!=null&&e.isInputFocused)&&O(t.props.date,t.props.preSelection)&&((!document.activeElement||document.activeElement===document.body)&&(n=!0),t.props.inline&&!t.props.shouldFocusDayInline&&(n=!1),t.props.containerRef&&t.props.containerRef.current&&t.props.containerRef.current.contains(document.activeElement)&&document.activeElement&&document.activeElement.classList.contains("react-datepicker__week-number")&&(n=!0)),n&&t.weekNumberEl.current&&t.weekNumberEl.current.focus({preventScroll:!0})},t}return Object.defineProperty(r,"defaultProps",{get:function(){return{ariaLabelPrefix:"week "}},enumerable:!1,configurable:!0}),r.prototype.componentDidMount=function(){this.handleFocusWeekNumber()},r.prototype.componentDidUpdate=function(t){this.handleFocusWeekNumber(t)},r.prototype.render=function(){var t=this.props,e=t.weekNumber,n=t.isWeekDisabled,s=t.ariaLabelPrefix,o=s===void 0?r.defaultProps.ariaLabelPrefix:s,i=t.onClick,c={"react-datepicker__week-number":!0,"react-datepicker__week-number--clickable":!!i&&!n,"react-datepicker__week-number--selected":!!i&&O(this.props.date,this.props.selected)};return m.createElement("div",{ref:this.weekNumberEl,className:Z(c),"aria-label":"".concat(o," ").concat(this.props.weekNumber),onClick:this.handleClick,onKeyDown:this.handleOnKeyDown,tabIndex:this.getTabIndex()},e)},r}(v.Component),Nc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.isDisabled=function(e){return se(e,{minDate:t.props.minDate,maxDate:t.props.maxDate,excludeDates:t.props.excludeDates,excludeDateIntervals:t.props.excludeDateIntervals,includeDateIntervals:t.props.includeDateIntervals,includeDates:t.props.includeDates,filterDate:t.props.filterDate})},t.handleDayClick=function(e,n){t.props.onDayClick&&t.props.onDayClick(e,n)},t.handleDayMouseEnter=function(e){t.props.onDayMouseEnter&&t.props.onDayMouseEnter(e)},t.handleWeekClick=function(e,n,s){for(var o,i,c,u=new Date(e),l=0;l<7;l++){var d=new Date(e);d.setDate(d.getDate()+l);var f=!t.isDisabled(d);if(f){u=d;break}}typeof t.props.onWeekSelect=="function"&&t.props.onWeekSelect(u,n,s),t.props.showWeekPicker&&t.handleDayClick(u,s),((o=t.props.shouldCloseOnSelect)!==null&&o!==void 0?o:r.defaultProps.shouldCloseOnSelect)&&((c=(i=t.props).setOpen)===null||c===void 0||c.call(i,!1))},t.formatWeekNumber=function(e){return t.props.formatWeekNumber?t.props.formatWeekNumber(e):dc(e)},t.isWeekDisabled=function(){for(var e=t.startOfWeek(),n=ce(e,6),s=new Date(e);s<=n;){if(!t.isDisabled(s))return!1;s=ce(s,1)}return!0},t.renderDays=function(){var e=t.startOfWeek(),n=[],s=t.formatWeekNumber(e);if(t.props.showWeekNumber){var o=t.props.onWeekSelect||t.props.showWeekPicker?t.handleWeekClick.bind(t,e,s):void 0;n.push(m.createElement(Ec,E({key:"W"},r.defaultProps,t.props,{weekNumber:s,isWeekDisabled:t.isWeekDisabled(),date:e,onClick:o})))}return n.concat([0,1,2,3,4,5,6].map(function(i){var c=ce(e,i);return m.createElement(Oc,E({},r.defaultProps,t.props,{ariaLabelPrefixWhenEnabled:t.props.chooseDayAriaLabelPrefix,ariaLabelPrefixWhenDisabled:t.props.disabledDayAriaLabelPrefix,key:c.valueOf(),day:c,onClick:t.handleDayClick.bind(t,c),onMouseEnter:t.handleDayMouseEnter.bind(t,c)}))}))},t.startOfWeek=function(){return Ce(t.props.day,t.props.locale,t.props.calendarStartDay)},t.isKeyboardSelected=function(){return!t.props.disabledKeyboardNavigation&&!O(t.startOfWeek(),t.props.selected)&&O(t.startOfWeek(),t.props.preSelection)},t}return Object.defineProperty(r,"defaultProps",{get:function(){return{shouldCloseOnSelect:!0}},enumerable:!1,configurable:!0}),r.prototype.render=function(){var t={"react-datepicker__week":!0,"react-datepicker__week--selected":O(this.startOfWeek(),this.props.selected),"react-datepicker__week--keyboard-selected":this.isKeyboardSelected()};return m.createElement("div",{className:Z(t)},this.renderDays())},r}(v.Component),at,Yc=6,Be={TWO_COLUMNS:"two_columns",THREE_COLUMNS:"three_columns",FOUR_COLUMNS:"four_columns"},Xt=(at={},at[Be.TWO_COLUMNS]={grid:[[0,1],[2,3],[4,5],[6,7],[8,9],[10,11]],verticalNavigationOffset:2},at[Be.THREE_COLUMNS]={grid:[[0,1,2],[3,4,5],[6,7,8],[9,10,11]],verticalNavigationOffset:3},at[Be.FOUR_COLUMNS]={grid:[[0,1,2,3],[4,5,6,7],[8,9,10,11]],verticalNavigationOffset:4},at),yt=1;function Gn(a,r){return a?Be.FOUR_COLUMNS:r?Be.TWO_COLUMNS:Be.THREE_COLUMNS}var Ic=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.MONTH_REFS=me([],Array(12),!0).map(function(){return v.createRef()}),t.QUARTER_REFS=me([],Array(4),!0).map(function(){return v.createRef()}),t.isDisabled=function(e){return se(e,{minDate:t.props.minDate,maxDate:t.props.maxDate,excludeDates:t.props.excludeDates,excludeDateIntervals:t.props.excludeDateIntervals,includeDateIntervals:t.props.includeDateIntervals,includeDates:t.props.includeDates,filterDate:t.props.filterDate})},t.isExcluded=function(e){return pn(e,{excludeDates:t.props.excludeDates,excludeDateIntervals:t.props.excludeDateIntervals})},t.handleDayClick=function(e,n){var s,o;(o=(s=t.props).onDayClick)===null||o===void 0||o.call(s,e,n,t.props.orderInDisplay)},t.handleDayMouseEnter=function(e){var n,s;(s=(n=t.props).onDayMouseEnter)===null||s===void 0||s.call(n,e)},t.handleMouseLeave=function(){var e,n;(n=(e=t.props).onMouseLeave)===null||n===void 0||n.call(e)},t.isRangeStartMonth=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate;return!o||!i?!1:ee(ae(s,e),o)},t.isRangeStartQuarter=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate;return!o||!i?!1:Rt($e(s,e),o)},t.isRangeEndMonth=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate;return!o||!i?!1:ee(ae(s,e),i)},t.isRangeEndQuarter=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate;return!o||!i?!1:Rt($e(s,e),i)},t.isInSelectingRangeMonth=function(e){var n,s=t.props,o=s.day,i=s.selectsStart,c=s.selectsEnd,u=s.selectsRange,l=s.startDate,d=s.endDate,f=(n=t.props.selectingDate)!==null&&n!==void 0?n:t.props.preSelection;return!(i||c||u)||!f?!1:i&&d?mt(f,d,e,o):c&&l||u&&l&&!d?mt(l,f,e,o):!1},t.isSelectingMonthRangeStart=function(e){var n;if(!t.isInSelectingRangeMonth(e))return!1;var s=t.props,o=s.day,i=s.startDate,c=s.selectsStart,u=ae(o,e),l=(n=t.props.selectingDate)!==null&&n!==void 0?n:t.props.preSelection;return c?ee(u,l):ee(u,i)},t.isSelectingMonthRangeEnd=function(e){var n;if(!t.isInSelectingRangeMonth(e))return!1;var s=t.props,o=s.day,i=s.endDate,c=s.selectsEnd,u=s.selectsRange,l=ae(o,e),d=(n=t.props.selectingDate)!==null&&n!==void 0?n:t.props.preSelection;return c||u?ee(l,d):ee(l,i)},t.isInSelectingRangeQuarter=function(e){var n,s=t.props,o=s.day,i=s.selectsStart,c=s.selectsEnd,u=s.selectsRange,l=s.startDate,d=s.endDate,f=(n=t.props.selectingDate)!==null&&n!==void 0?n:t.props.preSelection;return!(i||c||u)||!f?!1:i&&d?Dt(f,d,e,o):c&&l||u&&l&&!d?Dt(l,f,e,o):!1},t.isWeekInMonth=function(e){var n=t.props.day,s=ce(e,6);return ee(e,n)||ee(s,n)},t.isCurrentMonth=function(e,n){return P(e)===P(R())&&n===te(R())},t.isCurrentQuarter=function(e,n){return P(e)===P(R())&&n===Ye(R())},t.isSelectedMonth=function(e,n,s){return te(s)===n&&P(e)===P(s)},t.isSelectMonthInList=function(e,n,s){return s.some(function(o){return t.isSelectedMonth(e,n,o)})},t.isSelectedQuarter=function(e,n,s){return Ye(e)===n&&P(e)===P(s)},t.renderWeeks=function(){for(var e=[],n=t.props.fixedHeight,s=0,o=!1,i=Ce(ve(t.props.day),t.props.locale,t.props.calendarStartDay),c=function(h){return t.props.showWeekPicker?Ce(h,t.props.locale,t.props.calendarStartDay):t.props.preSelection},u=function(h){return t.props.showWeekPicker?Ce(h,t.props.locale,t.props.calendarStartDay):t.props.selected},l=t.props.selected?u(t.props.selected):void 0,d=t.props.preSelection?c(t.props.preSelection):void 0;e.push(m.createElement(Nc,E({},t.props,{ariaLabelPrefix:t.props.weekAriaLabelPrefix,key:s,day:i,month:te(t.props.day),onDayClick:t.handleDayClick,onDayMouseEnter:t.handleDayMouseEnter,selected:l,preSelection:d,showWeekNumber:t.props.showWeekNumbers}))),!o;){s++,i=Pt(i,1);var f=n&&s>=Yc,p=!n&&!t.isWeekInMonth(i);if(f||p)if(t.props.peekNextMonth)o=!0;else break}return e},t.onMonthClick=function(e,n){var s=t.isMonthDisabledForLabelDate(n),o=s.isDisabled,i=s.labelDate;o||t.handleDayClick(ve(i),e)},t.onMonthMouseEnter=function(e){var n=t.isMonthDisabledForLabelDate(e),s=n.isDisabled,o=n.labelDate;s||t.handleDayMouseEnter(ve(o))},t.handleMonthNavigation=function(e,n){var s,o,i,c;(o=(s=t.props).setPreSelection)===null||o===void 0||o.call(s,n),(c=(i=t.MONTH_REFS[e])===null||i===void 0?void 0:i.current)===null||c===void 0||c.focus()},t.handleKeyboardNavigation=function(e,n,s){var o,i=t.props,c=i.selected,u=i.preSelection,l=i.setPreSelection,d=i.minDate,f=i.maxDate,p=i.showFourColumnMonthYearPicker,h=i.showTwoColumnMonthYearPicker;if(u){var g=Gn(p,h),w=t.getVerticalOffset(g),k=(o=Xt[g])===null||o===void 0?void 0:o.grid,S=function(I,_,M){var F,X,K=_,J=M;switch(I){case D.ArrowRight:K=ue(_,yt),J=M===11?0:M+yt;break;case D.ArrowLeft:K=Ie(_,yt),J=M===0?11:M-yt;break;case D.ArrowUp:K=Ie(_,w),J=!((F=k==null?void 0:k[0])===null||F===void 0)&&F.includes(M)?M+12-w:M-w;break;case D.ArrowDown:K=ue(_,w),J=!((X=k==null?void 0:k[k.length-1])===null||X===void 0)&&X.includes(M)?M-12+w:M+w;break}return{newCalculatedDate:K,newCalculatedMonth:J}},x=function(I,_,M){for(var F=40,X=I,K=!1,J=0,le=S(X,_,M),G=le.newCalculatedDate,A=le.newCalculatedMonth;!K;){if(J>=F){G=_,A=M;break}if(d&&G<d){X=D.ArrowRight;var Q=S(X,G,A);G=Q.newCalculatedDate,A=Q.newCalculatedMonth}if(f&&G>f){X=D.ArrowLeft;var Q=S(X,G,A);G=Q.newCalculatedDate,A=Q.newCalculatedMonth}if(yc(G,t.props)){var Q=S(X,G,A);G=Q.newCalculatedDate,A=Q.newCalculatedMonth}else K=!0;J++}return{newCalculatedDate:G,newCalculatedMonth:A}};if(n===D.Enter){t.isMonthDisabled(s)||(t.onMonthClick(e,s),l==null||l(c));return}var N=x(n,u,s),q=N.newCalculatedDate,$=N.newCalculatedMonth;switch(n){case D.ArrowRight:case D.ArrowLeft:case D.ArrowUp:case D.ArrowDown:t.handleMonthNavigation($,q);break}}},t.getVerticalOffset=function(e){var n,s;return(s=(n=Xt[e])===null||n===void 0?void 0:n.verticalNavigationOffset)!==null&&s!==void 0?s:0},t.onMonthKeyDown=function(e,n){var s=t.props,o=s.disabledKeyboardNavigation,i=s.handleOnMonthKeyDown,c=e.key;c!==D.Tab&&e.preventDefault(),o||t.handleKeyboardNavigation(e,c,n),i&&i(e)},t.onQuarterClick=function(e,n){var s=$e(t.props.day,n);gt(s,t.props)||t.handleDayClick(Rn(s),e)},t.onQuarterMouseEnter=function(e){var n=$e(t.props.day,e);gt(n,t.props)||t.handleDayMouseEnter(Rn(n))},t.handleQuarterNavigation=function(e,n){var s,o,i,c;t.isDisabled(n)||t.isExcluded(n)||((o=(s=t.props).setPreSelection)===null||o===void 0||o.call(s,n),(c=(i=t.QUARTER_REFS[e-1])===null||i===void 0?void 0:i.current)===null||c===void 0||c.focus())},t.onQuarterKeyDown=function(e,n){var s,o,i=e.key;if(!t.props.disabledKeyboardNavigation)switch(i){case D.Enter:t.onQuarterClick(e,n),(o=(s=t.props).setPreSelection)===null||o===void 0||o.call(s,t.props.selected);break;case D.ArrowRight:if(!t.props.preSelection)break;t.handleQuarterNavigation(n===4?1:n+1,sn(t.props.preSelection,1));break;case D.ArrowLeft:if(!t.props.preSelection)break;t.handleQuarterNavigation(n===1?4:n-1,_r(t.props.preSelection));break}},t.isMonthDisabledForLabelDate=function(e){var n,s=t.props,o=s.day,i=s.minDate,c=s.maxDate,u=s.excludeDates,l=s.includeDates,d=ae(o,e);return{isDisabled:(n=(i||c||u||l)&&Pr(d,t.props))!==null&&n!==void 0?n:!1,labelDate:d}},t.isMonthDisabled=function(e){var n=t.isMonthDisabledForLabelDate(e).isDisabled;return n},t.getMonthClassNames=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate,c=n.preSelection,u=n.monthClassName,l=u?u(ae(s,e)):void 0,d=t.getSelection();return Z("react-datepicker__month-text","react-datepicker__month-".concat(e),l,{"react-datepicker__month-text--disabled":t.isMonthDisabled(e),"react-datepicker__month-text--selected":d?t.isSelectMonthInList(s,e,d):void 0,"react-datepicker__month-text--keyboard-selected":!t.props.disabledKeyboardNavigation&&c&&t.isSelectedMonth(s,e,c)&&!t.isMonthDisabled(e),"react-datepicker__month-text--in-selecting-range":t.isInSelectingRangeMonth(e),"react-datepicker__month-text--in-range":o&&i?mt(o,i,e,s):void 0,"react-datepicker__month-text--range-start":t.isRangeStartMonth(e),"react-datepicker__month-text--range-end":t.isRangeEndMonth(e),"react-datepicker__month-text--selecting-range-start":t.isSelectingMonthRangeStart(e),"react-datepicker__month-text--selecting-range-end":t.isSelectingMonthRangeEnd(e),"react-datepicker__month-text--today":t.isCurrentMonth(s,e)})},t.getTabIndex=function(e){if(t.props.preSelection==null)return"-1";var n=te(t.props.preSelection),s=t.isMonthDisabledForLabelDate(n).isDisabled,o=e===n&&!(s||t.props.disabledKeyboardNavigation)?"0":"-1";return o},t.getQuarterTabIndex=function(e){if(t.props.preSelection==null)return"-1";var n=Ye(t.props.preSelection),s=gt(t.props.day,t.props),o=e===n&&!(s||t.props.disabledKeyboardNavigation)?"0":"-1";return o},t.getAriaLabel=function(e){var n=t.props,s=n.chooseDayAriaLabelPrefix,o=s===void 0?"Choose":s,i=n.disabledDayAriaLabelPrefix,c=i===void 0?"Not available":i,u=n.day,l=n.locale,d=ae(u,e),f=t.isDisabled(d)||t.isExcluded(d)?c:o;return"".concat(f," ").concat(H(d,"MMMM yyyy",l))},t.getQuarterClassNames=function(e){var n=t.props,s=n.day,o=n.startDate,i=n.endDate,c=n.selected,u=n.minDate,l=n.maxDate,d=n.excludeDates,f=n.includeDates,p=n.filterDate,h=n.preSelection,g=n.disabledKeyboardNavigation,w=(u||l||d||f||p)&&gt($e(s,e),t.props);return Z("react-datepicker__quarter-text","react-datepicker__quarter-".concat(e),{"react-datepicker__quarter-text--disabled":w,"react-datepicker__quarter-text--selected":c?t.isSelectedQuarter(s,e,c):void 0,"react-datepicker__quarter-text--keyboard-selected":!g&&h&&t.isSelectedQuarter(s,e,h)&&!w,"react-datepicker__quarter-text--in-selecting-range":t.isInSelectingRangeQuarter(e),"react-datepicker__quarter-text--in-range":o&&i?Dt(o,i,e,s):void 0,"react-datepicker__quarter-text--range-start":t.isRangeStartQuarter(e),"react-datepicker__quarter-text--range-end":t.isRangeEndQuarter(e)})},t.getMonthContent=function(e){var n=t.props,s=n.showFullMonthYearPicker,o=n.renderMonthContent,i=n.locale,c=n.day,u=Cr(e,i),l=fn(e,i);return o?o(e,u,l,c):s?l:u},t.getQuarterContent=function(e){var n,s=t.props,o=s.renderQuarterContent,i=s.locale,c=Dc(e,i);return(n=o==null?void 0:o(e,c))!==null&&n!==void 0?n:c},t.renderMonths=function(){var e,n=t.props,s=n.showTwoColumnMonthYearPicker,o=n.showFourColumnMonthYearPicker,i=n.day,c=n.selected,u=(e=Xt[Gn(o,s)])===null||e===void 0?void 0:e.grid;return u==null?void 0:u.map(function(l,d){return m.createElement("div",{className:"react-datepicker__month-wrapper",key:d},l.map(function(f,p){return m.createElement("div",{ref:t.MONTH_REFS[f],key:p,onClick:function(h){t.onMonthClick(h,f)},onKeyDown:function(h){Er(h)&&(h.preventDefault(),h.key=D.Enter),t.onMonthKeyDown(h,f)},onMouseEnter:t.props.usePointerEvent?void 0:function(){return t.onMonthMouseEnter(f)},onPointerEnter:t.props.usePointerEvent?function(){return t.onMonthMouseEnter(f)}:void 0,tabIndex:Number(t.getTabIndex(f)),className:t.getMonthClassNames(f),"aria-disabled":t.isMonthDisabled(f),role:"option","aria-label":t.getAriaLabel(f),"aria-current":t.isCurrentMonth(i,f)?"date":void 0,"aria-selected":c?t.isSelectedMonth(i,f,c):void 0},t.getMonthContent(f))}))})},t.renderQuarters=function(){var e=t.props,n=e.day,s=e.selected,o=[1,2,3,4];return m.createElement("div",{className:"react-datepicker__quarter-wrapper"},o.map(function(i,c){return m.createElement("div",{key:c,ref:t.QUARTER_REFS[c],role:"option",onClick:function(u){t.onQuarterClick(u,i)},onKeyDown:function(u){t.onQuarterKeyDown(u,i)},onMouseEnter:t.props.usePointerEvent?void 0:function(){return t.onQuarterMouseEnter(i)},onPointerEnter:t.props.usePointerEvent?function(){return t.onQuarterMouseEnter(i)}:void 0,className:t.getQuarterClassNames(i),"aria-selected":s?t.isSelectedQuarter(n,i,s):void 0,tabIndex:Number(t.getQuarterTabIndex(i)),"aria-current":t.isCurrentQuarter(n,i)?"date":void 0},t.getQuarterContent(i))}))},t.getClassNames=function(){var e=t.props,n=e.selectingDate,s=e.selectsStart,o=e.selectsEnd,i=e.showMonthYearPicker,c=e.showQuarterYearPicker,u=e.showWeekPicker;return Z("react-datepicker__month",{"react-datepicker__month--selecting-range":n&&(s||o)},{"react-datepicker__monthPicker":i},{"react-datepicker__quarterPicker":c},{"react-datepicker__weekPicker":u})},t}return r.prototype.getSelection=function(){var t=this.props,e=t.selected,n=t.selectedDates,s=t.selectsMultiple;if(s)return n;if(e)return[e]},r.prototype.render=function(){var t=this.props,e=t.showMonthYearPicker,n=t.showQuarterYearPicker,s=t.day,o=t.ariaLabelPrefix,i=o===void 0?"Month ":o,c=i?i.trim()+" ":"";return m.createElement("div",{className:this.getClassNames(),onMouseLeave:this.props.usePointerEvent?void 0:this.handleMouseLeave,onPointerLeave:this.props.usePointerEvent?this.handleMouseLeave:void 0,"aria-label":"".concat(c).concat(H(s,"MMMM, yyyy",this.props.locale)),role:"listbox"},e?this.renderMonths():n?this.renderQuarters():this.renderWeeks())},r}(v.Component),Rc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.isSelectedMonth=function(e){return t.props.month===e},t.renderOptions=function(){return t.props.monthNames.map(function(e,n){return m.createElement("div",{className:t.isSelectedMonth(n)?"react-datepicker__month-option react-datepicker__month-option--selected_month":"react-datepicker__month-option",key:e,onClick:t.onChange.bind(t,n),"aria-selected":t.isSelectedMonth(n)?"true":void 0},t.isSelectedMonth(n)?m.createElement("span",{className:"react-datepicker__month-option--selected"},"✓"):"",e)})},t.onChange=function(e){return t.props.onChange(e)},t.handleClickOutside=function(){return t.props.onCancel()},t}return r.prototype.render=function(){return m.createElement($t,{className:"react-datepicker__month-dropdown",onClickOutside:this.handleClickOutside},this.renderOptions())},r}(v.Component),Fc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.state={dropdownVisible:!1},t.renderSelectOptions=function(e){return e.map(function(n,s){return m.createElement("option",{key:n,value:s},n)})},t.renderSelectMode=function(e){return m.createElement("select",{value:t.props.month,className:"react-datepicker__month-select",onChange:function(n){return t.onChange(parseInt(n.target.value))}},t.renderSelectOptions(e))},t.renderReadView=function(e,n){return m.createElement("div",{key:"read",style:{visibility:e?"visible":"hidden"},className:"react-datepicker__month-read-view",onClick:t.toggleDropdown},m.createElement("span",{className:"react-datepicker__month-read-view--down-arrow"}),m.createElement("span",{className:"react-datepicker__month-read-view--selected-month"},n[t.props.month]))},t.renderDropdown=function(e){return m.createElement(Rc,E({key:"dropdown"},t.props,{monthNames:e,onChange:t.onChange,onCancel:t.toggleDropdown}))},t.renderScrollMode=function(e){var n=t.state.dropdownVisible,s=[t.renderReadView(!n,e)];return n&&s.unshift(t.renderDropdown(e)),s},t.onChange=function(e){t.toggleDropdown(),e!==t.props.month&&t.props.onChange(e)},t.toggleDropdown=function(){return t.setState({dropdownVisible:!t.state.dropdownVisible})},t}return r.prototype.render=function(){var t=this,e=[0,1,2,3,4,5,6,7,8,9,10,11].map(this.props.useShortMonthInDropdown?function(s){return Cr(s,t.props.locale)}:function(s){return fn(s,t.props.locale)}),n;switch(this.props.dropdownMode){case"scroll":n=this.renderScrollMode(e);break;case"select":n=this.renderSelectMode(e);break}return m.createElement("div",{className:"react-datepicker__month-dropdown-container react-datepicker__month-dropdown-container--".concat(this.props.dropdownMode)},n)},r}(v.Component);function Lc(a,r){for(var t=[],e=ve(a),n=ve(r);!Pe(e,n);)t.push(R(e)),e=ue(e,1);return t}var Wc=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.renderOptions=function(){return e.state.monthYearsList.map(function(n){var s=tn(n),o=fe(e.props.date,n)&&ee(e.props.date,n);return m.createElement("div",{className:o?"react-datepicker__month-year-option--selected_month-year":"react-datepicker__month-year-option",key:s,onClick:e.onChange.bind(e,s),"aria-selected":o?"true":void 0},o?m.createElement("span",{className:"react-datepicker__month-year-option--selected"},"✓"):"",H(n,e.props.dateFormat,e.props.locale))})},e.onChange=function(n){return e.props.onChange(n)},e.handleClickOutside=function(){e.props.onCancel()},e.state={monthYearsList:Lc(e.props.minDate,e.props.maxDate)},e}return r.prototype.render=function(){var t=Z({"react-datepicker__month-year-dropdown":!0,"react-datepicker__month-year-dropdown--scrollable":this.props.scrollableMonthYearDropdown});return m.createElement($t,{className:t,onClickOutside:this.handleClickOutside},this.renderOptions())},r}(v.Component),Ac=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.state={dropdownVisible:!1},t.renderSelectOptions=function(){for(var e=ve(t.props.minDate),n=ve(t.props.maxDate),s=[];!Pe(e,n);){var o=tn(e);s.push(m.createElement("option",{key:o,value:o},H(e,t.props.dateFormat,t.props.locale))),e=ue(e,1)}return s},t.onSelectChange=function(e){t.onChange(parseInt(e.target.value))},t.renderSelectMode=function(){return m.createElement("select",{value:tn(ve(t.props.date)),className:"react-datepicker__month-year-select",onChange:t.onSelectChange},t.renderSelectOptions())},t.renderReadView=function(e){var n=H(t.props.date,t.props.dateFormat,t.props.locale);return m.createElement("div",{key:"read",style:{visibility:e?"visible":"hidden"},className:"react-datepicker__month-year-read-view",onClick:t.toggleDropdown},m.createElement("span",{className:"react-datepicker__month-year-read-view--down-arrow"}),m.createElement("span",{className:"react-datepicker__month-year-read-view--selected-month-year"},n))},t.renderDropdown=function(){return m.createElement(Wc,E({key:"dropdown"},t.props,{onChange:t.onChange,onCancel:t.toggleDropdown}))},t.renderScrollMode=function(){var e=t.state.dropdownVisible,n=[t.renderReadView(!e)];return e&&n.unshift(t.renderDropdown()),n},t.onChange=function(e){t.toggleDropdown();var n=R(e);fe(t.props.date,n)&&ee(t.props.date,n)||t.props.onChange(n)},t.toggleDropdown=function(){return t.setState({dropdownVisible:!t.state.dropdownVisible})},t}return r.prototype.render=function(){var t;switch(this.props.dropdownMode){case"scroll":t=this.renderScrollMode();break;case"select":t=this.renderSelectMode();break}return m.createElement("div",{className:"react-datepicker__month-year-dropdown-container react-datepicker__month-year-dropdown-container--".concat(this.props.dropdownMode)},t)},r}(v.Component),Hc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.state={height:null},t.scrollToTheSelectedTime=function(){requestAnimationFrame(function(){var e,n,s;t.list&&(t.list.scrollTop=(s=t.centerLi&&r.calcCenterPosition(t.props.monthRef?t.props.monthRef.clientHeight-((n=(e=t.header)===null||e===void 0?void 0:e.clientHeight)!==null&&n!==void 0?n:0):t.list.clientHeight,t.centerLi))!==null&&s!==void 0?s:0)})},t.handleClick=function(e){var n,s;(t.props.minTime||t.props.maxTime)&&Hn(e,t.props)||(t.props.excludeTimes||t.props.includeTimes||t.props.filterTime)&&An(e,t.props)||(s=(n=t.props).onChange)===null||s===void 0||s.call(n,e)},t.isSelectedTime=function(e){return t.props.selected&&Pc(t.props.selected,e)},t.isDisabledTime=function(e){return(t.props.minTime||t.props.maxTime)&&Hn(e,t.props)||(t.props.excludeTimes||t.props.includeTimes||t.props.filterTime)&&An(e,t.props)},t.liClasses=function(e){var n,s=["react-datepicker__time-list-item",t.props.timeClassName?t.props.timeClassName(e):void 0];return t.isSelectedTime(e)&&s.push("react-datepicker__time-list-item--selected"),t.isDisabledTime(e)&&s.push("react-datepicker__time-list-item--disabled"),t.props.injectTimes&&(De(e)*3600+ye(e)*60+Se(e))%(((n=t.props.intervals)!==null&&n!==void 0?n:r.defaultProps.intervals)*60)!==0&&s.push("react-datepicker__time-list-item--injected"),s.join(" ")},t.handleOnKeyDown=function(e,n){var s,o;e.key===D.Space&&(e.preventDefault(),e.key=D.Enter),(e.key===D.ArrowUp||e.key===D.ArrowLeft)&&e.target instanceof HTMLElement&&e.target.previousSibling&&(e.preventDefault(),e.target.previousSibling instanceof HTMLElement&&e.target.previousSibling.focus()),(e.key===D.ArrowDown||e.key===D.ArrowRight)&&e.target instanceof HTMLElement&&e.target.nextSibling&&(e.preventDefault(),e.target.nextSibling instanceof HTMLElement&&e.target.nextSibling.focus()),e.key===D.Enter&&t.handleClick(n),(o=(s=t.props).handleOnKeyDown)===null||o===void 0||o.call(s,e)},t.renderTimes=function(){for(var e,n=[],s=typeof t.props.format=="string"?t.props.format:"p",o=(e=t.props.intervals)!==null&&e!==void 0?e:r.defaultProps.intervals,i=t.props.selected||t.props.openToDate||R(),c=_t(i),u=t.props.injectTimes&&t.props.injectTimes.sort(function(w,k){return w.getTime()-k.getTime()}),l=60*Cc(i),d=l/o,f=0;f<d;f++){var p=Zt(c,f*o);if(n.push(p),u){var h=Sc(c,p,f,o,u);n=n.concat(h)}}var g=n.reduce(function(w,k){return k.getTime()<=i.getTime()?k:w},n[0]);return n.map(function(w){return m.createElement("li",{key:w.valueOf(),onClick:t.handleClick.bind(t,w),className:t.liClasses(w),ref:function(k){w===g&&(t.centerLi=k)},onKeyDown:function(k){t.handleOnKeyDown(k,w)},tabIndex:w===g?0:-1,role:"option","aria-selected":t.isSelectedTime(w)?"true":void 0,"aria-disabled":t.isDisabledTime(w)?"true":void 0},H(w,s,t.props.locale))})},t.renderTimeCaption=function(){return t.props.showTimeCaption===!1?m.createElement(m.Fragment,null):m.createElement("div",{className:"react-datepicker__header react-datepicker__header--time ".concat(t.props.showTimeSelectOnly?"react-datepicker__header--time--only":""),ref:function(e){t.header=e}},m.createElement("div",{className:"react-datepicker-time__header"},t.props.timeCaption))},t}return Object.defineProperty(r,"defaultProps",{get:function(){return{intervals:30,todayButton:null,timeCaption:"Time",showTimeCaption:!0}},enumerable:!1,configurable:!0}),r.prototype.componentDidMount=function(){this.scrollToTheSelectedTime(),this.props.monthRef&&this.header&&this.setState({height:this.props.monthRef.clientHeight-this.header.clientHeight})},r.prototype.render=function(){var t=this,e,n=this.state.height;return m.createElement("div",{className:"react-datepicker__time-container ".concat(((e=this.props.todayButton)!==null&&e!==void 0?e:r.defaultProps.todayButton)?"react-datepicker__time-container--with-today-button":"")},this.renderTimeCaption(),m.createElement("div",{className:"react-datepicker__time"},m.createElement("div",{className:"react-datepicker__time-box"},m.createElement("ul",{className:"react-datepicker__time-list",ref:function(s){t.list=s},style:n?{height:n}:{},role:"listbox","aria-label":this.props.timeCaption},this.renderTimes()))))},r.calcCenterPosition=function(t,e){return e.offsetTop-(t/2-e.clientHeight/2)},r}(v.Component),zn=3,$c=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.YEAR_REFS=me([],Array(e.props.yearItemNumber),!0).map(function(){return v.createRef()}),e.isDisabled=function(n){return se(n,{minDate:e.props.minDate,maxDate:e.props.maxDate,excludeDates:e.props.excludeDates,includeDates:e.props.includeDates,filterDate:e.props.filterDate})},e.isExcluded=function(n){return pn(n,{excludeDates:e.props.excludeDates})},e.selectingDate=function(){var n;return(n=e.props.selectingDate)!==null&&n!==void 0?n:e.props.preSelection},e.updateFocusOnPaginate=function(n){var s=function(){var o,i;(i=(o=e.YEAR_REFS[n])===null||o===void 0?void 0:o.current)===null||i===void 0||i.focus()};window.requestAnimationFrame(s)},e.handleYearClick=function(n,s){e.props.onDayClick&&e.props.onDayClick(n,s)},e.handleYearNavigation=function(n,s){var o,i,c,u,l=e.props,d=l.date,f=l.yearItemNumber;if(!(d===void 0||f===void 0)){var p=xe(d,f).startPeriod;e.isDisabled(s)||e.isExcluded(s)||((i=(o=e.props).setPreSelection)===null||i===void 0||i.call(o,s),n-p<0?e.updateFocusOnPaginate(f-(p-n)):n-p>=f?e.updateFocusOnPaginate(Math.abs(f-(n-p))):(u=(c=e.YEAR_REFS[n-p])===null||c===void 0?void 0:c.current)===null||u===void 0||u.focus())}},e.isSameDay=function(n,s){return O(n,s)},e.isCurrentYear=function(n){return n===P(R())},e.isRangeStart=function(n){return e.props.startDate&&e.props.endDate&&fe(de(R(),n),e.props.startDate)},e.isRangeEnd=function(n){return e.props.startDate&&e.props.endDate&&fe(de(R(),n),e.props.endDate)},e.isInRange=function(n){return wt(n,e.props.startDate,e.props.endDate)},e.isInSelectingRange=function(n){var s=e.props,o=s.selectsStart,i=s.selectsEnd,c=s.selectsRange,u=s.startDate,l=s.endDate;return!(o||i||c)||!e.selectingDate()?!1:o&&l?wt(n,e.selectingDate(),l):i&&u||c&&u&&!l?wt(n,u,e.selectingDate()):!1},e.isSelectingRangeStart=function(n){var s;if(!e.isInSelectingRange(n))return!1;var o=e.props,i=o.startDate,c=o.selectsStart,u=de(R(),n);return c?fe(u,(s=e.selectingDate())!==null&&s!==void 0?s:null):fe(u,i??null)},e.isSelectingRangeEnd=function(n){var s;if(!e.isInSelectingRange(n))return!1;var o=e.props,i=o.endDate,c=o.selectsEnd,u=o.selectsRange,l=de(R(),n);return c||u?fe(l,(s=e.selectingDate())!==null&&s!==void 0?s:null):fe(l,i??null)},e.isKeyboardSelected=function(n){if(!(e.props.date===void 0||e.props.selected==null||e.props.preSelection==null)){var s=e.props,o=s.minDate,i=s.maxDate,c=s.excludeDates,u=s.includeDates,l=s.filterDate,d=st(de(e.props.date,n)),f=(o||i||c||u||l)&&Mt(n,e.props);return!e.props.disabledKeyboardNavigation&&!e.props.inline&&!O(d,st(e.props.selected))&&O(d,st(e.props.preSelection))&&!f}},e.onYearClick=function(n,s){var o=e.props.date;o!==void 0&&e.handleYearClick(st(de(o,s)),n)},e.onYearKeyDown=function(n,s){var o,i,c=n.key,u=e.props,l=u.date,d=u.yearItemNumber,f=u.handleOnKeyDown;if(c!==D.Tab&&n.preventDefault(),!e.props.disabledKeyboardNavigation)switch(c){case D.Enter:if(e.props.selected==null)break;e.onYearClick(n,s),(i=(o=e.props).setPreSelection)===null||i===void 0||i.call(o,e.props.selected);break;case D.ArrowRight:if(e.props.preSelection==null)break;e.handleYearNavigation(s+1,ge(e.props.preSelection,1));break;case D.ArrowLeft:if(e.props.preSelection==null)break;e.handleYearNavigation(s-1,Ue(e.props.preSelection,1));break;case D.ArrowUp:{if(l===void 0||d===void 0||e.props.preSelection==null)break;var p=xe(l,d).startPeriod,h=zn,g=s-h;if(g<p){var w=d%h;s>=p&&s<p+w?h=w:h+=w,g=s-h}e.handleYearNavigation(g,Ue(e.props.preSelection,h));break}case D.ArrowDown:{if(l===void 0||d===void 0||e.props.preSelection==null)break;var k=xe(l,d).endPeriod,h=zn,g=s+h;if(g>k){var w=d%h;s<=k&&s>k-w?h=w:h+=w,g=s+h}e.handleYearNavigation(g,ge(e.props.preSelection,h));break}}f&&f(n)},e.getYearClassNames=function(n){var s=e.props,o=s.date,i=s.minDate,c=s.maxDate,u=s.selected,l=s.excludeDates,d=s.includeDates,f=s.filterDate,p=s.yearClassName;return Z("react-datepicker__year-text","react-datepicker__year-".concat(n),o?p==null?void 0:p(de(o,n)):void 0,{"react-datepicker__year-text--selected":u?n===P(u):void 0,"react-datepicker__year-text--disabled":(i||c||l||d||f)&&Mt(n,e.props),"react-datepicker__year-text--keyboard-selected":e.isKeyboardSelected(n),"react-datepicker__year-text--range-start":e.isRangeStart(n),"react-datepicker__year-text--range-end":e.isRangeEnd(n),"react-datepicker__year-text--in-range":e.isInRange(n),"react-datepicker__year-text--in-selecting-range":e.isInSelectingRange(n),"react-datepicker__year-text--selecting-range-start":e.isSelectingRangeStart(n),"react-datepicker__year-text--selecting-range-end":e.isSelectingRangeEnd(n),"react-datepicker__year-text--today":e.isCurrentYear(n)})},e.getYearTabIndex=function(n){if(e.props.disabledKeyboardNavigation||e.props.preSelection==null)return"-1";var s=P(e.props.preSelection),o=Mt(n,e.props);return n===s&&!o?"0":"-1"},e.getYearContent=function(n){return e.props.renderYearContent?e.props.renderYearContent(n):n},e}return r.prototype.render=function(){var t=this,e=[],n=this.props,s=n.date,o=n.yearItemNumber,i=n.onYearMouseEnter,c=n.onYearMouseLeave;if(s===void 0)return null;for(var u=xe(s,o),l=u.startPeriod,d=u.endPeriod,f=function(g){e.push(m.createElement("div",{ref:p.YEAR_REFS[g-l],onClick:function(w){t.onYearClick(w,g)},onKeyDown:function(w){Er(w)&&(w.preventDefault(),w.key=D.Enter),t.onYearKeyDown(w,g)},tabIndex:Number(p.getYearTabIndex(g)),className:p.getYearClassNames(g),onMouseEnter:p.props.usePointerEvent?void 0:function(w){return i(w,g)},onPointerEnter:p.props.usePointerEvent?function(w){return i(w,g)}:void 0,onMouseLeave:p.props.usePointerEvent?void 0:function(w){return c(w,g)},onPointerLeave:p.props.usePointerEvent?function(w){return c(w,g)}:void 0,key:g,"aria-current":p.isCurrentYear(g)?"date":void 0},p.getYearContent(g)))},p=this,h=l;h<=d;h++)f(h);return m.createElement("div",{className:"react-datepicker__year"},m.createElement("div",{className:"react-datepicker__year-wrapper",onMouseLeave:this.props.usePointerEvent?void 0:this.props.clearSelectingDate,onPointerLeave:this.props.usePointerEvent?this.props.clearSelectingDate:void 0},e))},r}(v.Component);function Qc(a,r,t,e){for(var n=[],s=0;s<2*r+1;s++){var o=a+r-s,i=!0;t&&(i=P(t)<=o),e&&i&&(i=P(e)>=o),i&&n.push(o)}return n}var Bc=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;e.renderOptions=function(){var i=e.props.year,c=e.state.yearsList.map(function(d){return m.createElement("div",{className:i===d?"react-datepicker__year-option react-datepicker__year-option--selected_year":"react-datepicker__year-option",key:d,onClick:e.onChange.bind(e,d),"aria-selected":i===d?"true":void 0},i===d?m.createElement("span",{className:"react-datepicker__year-option--selected"},"✓"):"",d)}),u=e.props.minDate?P(e.props.minDate):null,l=e.props.maxDate?P(e.props.maxDate):null;return(!l||!e.state.yearsList.find(function(d){return d===l}))&&c.unshift(m.createElement("div",{className:"react-datepicker__year-option",key:"upcoming",onClick:e.incrementYears},m.createElement("a",{className:"react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-upcoming"}))),(!u||!e.state.yearsList.find(function(d){return d===u}))&&c.push(m.createElement("div",{className:"react-datepicker__year-option",key:"previous",onClick:e.decrementYears},m.createElement("a",{className:"react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-previous"}))),c},e.onChange=function(i){e.props.onChange(i)},e.handleClickOutside=function(){e.props.onCancel()},e.shiftYears=function(i){var c=e.state.yearsList.map(function(u){return u+i});e.setState({yearsList:c})},e.incrementYears=function(){return e.shiftYears(1)},e.decrementYears=function(){return e.shiftYears(-1)};var n=t.yearDropdownItemNumber,s=t.scrollableYearDropdown,o=n||(s?10:5);return e.state={yearsList:Qc(e.props.year,o,e.props.minDate,e.props.maxDate)},e.dropdownRef=v.createRef(),e}return r.prototype.componentDidMount=function(){var t=this.dropdownRef.current;if(t){var e=t.children?Array.from(t.children):null,n=e?e.find(function(s){return s.ariaSelected}):null;t.scrollTop=n&&n instanceof HTMLElement?n.offsetTop+(n.clientHeight-t.clientHeight)/2:(t.scrollHeight-t.clientHeight)/2}},r.prototype.render=function(){var t=Z({"react-datepicker__year-dropdown":!0,"react-datepicker__year-dropdown--scrollable":this.props.scrollableYearDropdown});return m.createElement($t,{className:t,containerRef:this.dropdownRef,onClickOutside:this.handleClickOutside},this.renderOptions())},r}(v.Component),qc=function(a){z(r,a);function r(){var t=a!==null&&a.apply(this,arguments)||this;return t.state={dropdownVisible:!1},t.renderSelectOptions=function(){for(var e=t.props.minDate?P(t.props.minDate):1900,n=t.props.maxDate?P(t.props.maxDate):2100,s=[],o=e;o<=n;o++)s.push(m.createElement("option",{key:o,value:o},o));return s},t.onSelectChange=function(e){t.onChange(parseInt(e.target.value))},t.renderSelectMode=function(){return m.createElement("select",{value:t.props.year,className:"react-datepicker__year-select",onChange:t.onSelectChange},t.renderSelectOptions())},t.renderReadView=function(e){return m.createElement("div",{key:"read",style:{visibility:e?"visible":"hidden"},className:"react-datepicker__year-read-view",onClick:function(n){return t.toggleDropdown(n)}},m.createElement("span",{className:"react-datepicker__year-read-view--down-arrow"}),m.createElement("span",{className:"react-datepicker__year-read-view--selected-year"},t.props.year))},t.renderDropdown=function(){return m.createElement(Bc,E({key:"dropdown"},t.props,{onChange:t.onChange,onCancel:t.toggleDropdown}))},t.renderScrollMode=function(){var e=t.state.dropdownVisible,n=[t.renderReadView(!e)];return e&&n.unshift(t.renderDropdown()),n},t.onChange=function(e){t.toggleDropdown(),e!==t.props.year&&t.props.onChange(e)},t.toggleDropdown=function(e){t.setState({dropdownVisible:!t.state.dropdownVisible},function(){t.props.adjustDateOnChange&&t.handleYearChange(t.props.date,e)})},t.handleYearChange=function(e,n){var s;(s=t.onSelect)===null||s===void 0||s.call(t,e,n),t.setOpen()},t.onSelect=function(e,n){var s,o;(o=(s=t.props).onSelect)===null||o===void 0||o.call(s,e,n)},t.setOpen=function(){var e,n;(n=(e=t.props).setOpen)===null||n===void 0||n.call(e,!0)},t}return r.prototype.render=function(){var t;switch(this.props.dropdownMode){case"scroll":t=this.renderScrollMode();break;case"select":t=this.renderSelectMode();break}return m.createElement("div",{className:"react-datepicker__year-dropdown-container react-datepicker__year-dropdown-container--".concat(this.props.dropdownMode)},t)},r}(v.Component),Kc=["react-datepicker__year-select","react-datepicker__month-select","react-datepicker__month-year-select"],Vc=function(a){var r=(a.className||"").split(/\s+/);return Kc.some(function(t){return r.indexOf(t)>=0})},Uc=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.monthContainer=void 0,e.handleClickOutside=function(n){e.props.onClickOutside(n)},e.setClickOutsideRef=function(){return e.containerRef.current},e.handleDropdownFocus=function(n){var s,o;Vc(n.target)&&((o=(s=e.props).onDropdownFocus)===null||o===void 0||o.call(s,n))},e.getDateInView=function(){var n=e.props,s=n.preSelection,o=n.selected,i=n.openToDate,c=Tr(e.props),u=Or(e.props),l=R(),d=i||o||s;return d||(c&&Fe(l,c)?c:u&&Pe(l,u)?u:l)},e.increaseMonth=function(){e.setState(function(n){var s=n.date;return{date:ue(s,1)}},function(){return e.handleMonthChange(e.state.date)})},e.decreaseMonth=function(){e.setState(function(n){var s=n.date;return{date:Ie(s,1)}},function(){return e.handleMonthChange(e.state.date)})},e.handleDayClick=function(n,s,o){e.props.onSelect(n,s,o),e.props.setPreSelection&&e.props.setPreSelection(n)},e.handleDayMouseEnter=function(n){e.setState({selectingDate:n}),e.props.onDayMouseEnter&&e.props.onDayMouseEnter(n)},e.handleMonthMouseLeave=function(){e.setState({selectingDate:void 0}),e.props.onMonthMouseLeave&&e.props.onMonthMouseLeave()},e.handleYearMouseEnter=function(n,s){e.setState({selectingDate:de(R(),s)}),e.props.onYearMouseEnter&&e.props.onYearMouseEnter(n,s)},e.handleYearMouseLeave=function(n,s){e.props.onYearMouseLeave&&e.props.onYearMouseLeave(n,s)},e.handleYearChange=function(n){var s,o,i,c;(o=(s=e.props).onYearChange)===null||o===void 0||o.call(s,n),e.setState({isRenderAriaLiveMessage:!0}),e.props.adjustDateOnChange&&(e.props.onSelect(n),(c=(i=e.props).setOpen)===null||c===void 0||c.call(i,!0)),e.props.setPreSelection&&e.props.setPreSelection(n)},e.getEnabledPreSelectionDateForMonth=function(n){if(!se(n,e.props))return n;for(var s=ve(n),o=hc(n),i=Ts(o,s),c=null,u=0;u<=i;u++){var l=ce(s,u);if(!se(l,e.props)){c=l;break}}return c},e.handleMonthChange=function(n){var s,o,i,c=(s=e.getEnabledPreSelectionDateForMonth(n))!==null&&s!==void 0?s:n;e.handleCustomMonthChange(c),e.props.adjustDateOnChange&&(e.props.onSelect(c),(i=(o=e.props).setOpen)===null||i===void 0||i.call(o,!0)),e.props.setPreSelection&&e.props.setPreSelection(c)},e.handleCustomMonthChange=function(n){var s,o;(o=(s=e.props).onMonthChange)===null||o===void 0||o.call(s,n),e.setState({isRenderAriaLiveMessage:!0})},e.handleMonthYearChange=function(n){e.handleYearChange(n),e.handleMonthChange(n)},e.changeYear=function(n){e.setState(function(s){var o=s.date;return{date:de(o,Number(n))}},function(){return e.handleYearChange(e.state.date)})},e.changeMonth=function(n){e.setState(function(s){var o=s.date;return{date:ae(o,Number(n))}},function(){return e.handleMonthChange(e.state.date)})},e.changeMonthYear=function(n){e.setState(function(s){var o=s.date;return{date:de(ae(o,te(n)),P(n))}},function(){return e.handleMonthYearChange(e.state.date)})},e.header=function(n){n===void 0&&(n=e.state.date);var s=Ce(n,e.props.locale,e.props.calendarStartDay),o=[];return e.props.showWeekNumbers&&o.push(m.createElement("div",{key:"W",className:"react-datepicker__day-name"},e.props.weekLabel||"#")),o.concat([0,1,2,3,4,5,6].map(function(i){var c=ce(s,i),u=e.formatWeekday(c,e.props.locale),l=e.props.weekDayClassName?e.props.weekDayClassName(c):void 0;return m.createElement("div",{key:i,"aria-label":H(c,"EEEE",e.props.locale),className:Z("react-datepicker__day-name",l)},u)}))},e.formatWeekday=function(n,s){return e.props.formatWeekDay?mc(n,e.props.formatWeekDay,s):e.props.useWeekdaysShort?wc(n,s):gc(n,s)},e.decreaseYear=function(){e.setState(function(n){var s,o=n.date;return{date:Ue(o,e.props.showYearPicker?(s=e.props.yearItemNumber)!==null&&s!==void 0?s:r.defaultProps.yearItemNumber:1)}},function(){return e.handleYearChange(e.state.date)})},e.clearSelectingDate=function(){e.setState({selectingDate:void 0})},e.renderPreviousButton=function(){var n,s,o;if(!e.props.renderCustomHeader){var i=(n=e.props.monthsShown)!==null&&n!==void 0?n:r.defaultProps.monthsShown,c=e.props.showPreviousMonths?i-1:0,u=(s=e.props.monthSelectedIn)!==null&&s!==void 0?s:c,l=Ie(e.state.date,u),d;switch(!0){case e.props.showMonthYearPicker:d=Bn(e.state.date,e.props);break;case e.props.showYearPicker:d=kc(e.state.date,e.props);break;case e.props.showQuarterYearPicker:d=vc(e.state.date,e.props);break;default:d=$n(l,e.props);break}if(!(!((o=e.props.forceShowMonthNavigation)!==null&&o!==void 0?o:r.defaultProps.forceShowMonthNavigation)&&!e.props.showDisabledMonthNavigation&&d||e.props.showTimeSelectOnly)){var f=["react-datepicker__navigation-icon","react-datepicker__navigation-icon--previous"],p=["react-datepicker__navigation","react-datepicker__navigation--previous"],h=e.decreaseMonth;(e.props.showMonthYearPicker||e.props.showQuarterYearPicker||e.props.showYearPicker)&&(h=e.decreaseYear),d&&e.props.showDisabledMonthNavigation&&(p.push("react-datepicker__navigation--previous--disabled"),h=void 0);var g=e.props.showMonthYearPicker||e.props.showQuarterYearPicker||e.props.showYearPicker,w=e.props,k=w.previousMonthButtonLabel,S=k===void 0?r.defaultProps.previousMonthButtonLabel:k,x=w.previousYearButtonLabel,N=x===void 0?r.defaultProps.previousYearButtonLabel:x,q=e.props,$=q.previousMonthAriaLabel,I=$===void 0?typeof S=="string"?S:"Previous Month":$,_=q.previousYearAriaLabel,M=_===void 0?typeof N=="string"?N:"Previous Year":_;return m.createElement("button",{type:"button",className:p.join(" "),onClick:h,onKeyDown:e.props.handleOnKeyDown,"aria-label":g?M:I},m.createElement("span",{className:f.join(" ")},g?N:S))}}},e.increaseYear=function(){e.setState(function(n){var s,o=n.date;return{date:ge(o,e.props.showYearPicker?(s=e.props.yearItemNumber)!==null&&s!==void 0?s:r.defaultProps.yearItemNumber:1)}},function(){return e.handleYearChange(e.state.date)})},e.renderNextButton=function(){var n;if(!e.props.renderCustomHeader){var s;switch(!0){case e.props.showMonthYearPicker:s=qn(e.state.date,e.props);break;case e.props.showYearPicker:s=_c(e.state.date,e.props);break;case e.props.showQuarterYearPicker:s=bc(e.state.date,e.props);break;default:s=Qn(e.state.date,e.props);break}if(!(!((n=e.props.forceShowMonthNavigation)!==null&&n!==void 0?n:r.defaultProps.forceShowMonthNavigation)&&!e.props.showDisabledMonthNavigation&&s||e.props.showTimeSelectOnly)){var o=["react-datepicker__navigation","react-datepicker__navigation--next"],i=["react-datepicker__navigation-icon","react-datepicker__navigation-icon--next"];e.props.showTimeSelect&&o.push("react-datepicker__navigation--next--with-time"),e.props.todayButton&&o.push("react-datepicker__navigation--next--with-today-button");var c=e.increaseMonth;(e.props.showMonthYearPicker||e.props.showQuarterYearPicker||e.props.showYearPicker)&&(c=e.increaseYear),s&&e.props.showDisabledMonthNavigation&&(o.push("react-datepicker__navigation--next--disabled"),c=void 0);var u=e.props.showMonthYearPicker||e.props.showQuarterYearPicker||e.props.showYearPicker,l=e.props,d=l.nextMonthButtonLabel,f=d===void 0?r.defaultProps.nextMonthButtonLabel:d,p=l.nextYearButtonLabel,h=p===void 0?r.defaultProps.nextYearButtonLabel:p,g=e.props,w=g.nextMonthAriaLabel,k=w===void 0?typeof f=="string"?f:"Next Month":w,S=g.nextYearAriaLabel,x=S===void 0?typeof h=="string"?h:"Next Year":S;return m.createElement("button",{type:"button",className:o.join(" "),onClick:c,onKeyDown:e.props.handleOnKeyDown,"aria-label":u?x:k},m.createElement("span",{className:i.join(" ")},u?h:f))}}},e.renderCurrentMonth=function(n){n===void 0&&(n=e.state.date);var s=["react-datepicker__current-month"];return e.props.showYearDropdown&&s.push("react-datepicker__current-month--hasYearDropdown"),e.props.showMonthDropdown&&s.push("react-datepicker__current-month--hasMonthDropdown"),e.props.showMonthYearDropdown&&s.push("react-datepicker__current-month--hasMonthYearDropdown"),m.createElement("h2",{className:s.join(" ")},H(n,e.props.dateFormat,e.props.locale))},e.renderYearDropdown=function(n){if(n===void 0&&(n=!1),!(!e.props.showYearDropdown||n))return m.createElement(qc,E({},r.defaultProps,e.props,{date:e.state.date,onChange:e.changeYear,year:P(e.state.date)}))},e.renderMonthDropdown=function(n){if(n===void 0&&(n=!1),!(!e.props.showMonthDropdown||n))return m.createElement(Fc,E({},r.defaultProps,e.props,{month:te(e.state.date),onChange:e.changeMonth}))},e.renderMonthYearDropdown=function(n){if(n===void 0&&(n=!1),!(!e.props.showMonthYearDropdown||n))return m.createElement(Ac,E({},r.defaultProps,e.props,{date:e.state.date,onChange:e.changeMonthYear}))},e.handleTodayButtonClick=function(n){e.props.onSelect(Fn(),n),e.props.setPreSelection&&e.props.setPreSelection(Fn())},e.renderTodayButton=function(){if(!(!e.props.todayButton||e.props.showTimeSelectOnly))return m.createElement("div",{className:"react-datepicker__today-button",onClick:e.handleTodayButtonClick},e.props.todayButton)},e.renderDefaultHeader=function(n){var s=n.monthDate,o=n.i;return m.createElement("div",{className:"react-datepicker__header ".concat(e.props.showTimeSelect?"react-datepicker__header--has-time-select":"")},e.renderCurrentMonth(s),m.createElement("div",{className:"react-datepicker__header__dropdown react-datepicker__header__dropdown--".concat(e.props.dropdownMode),onFocus:e.handleDropdownFocus},e.renderMonthDropdown(o!==0),e.renderMonthYearDropdown(o!==0),e.renderYearDropdown(o!==0)),m.createElement("div",{className:"react-datepicker__day-names"},e.header(s)))},e.renderCustomHeader=function(n){var s,o,i=n.monthDate,c=n.i;if(e.props.showTimeSelect&&!e.state.monthContainer||e.props.showTimeSelectOnly)return null;var u=$n(e.state.date,e.props),l=Qn(e.state.date,e.props),d=Bn(e.state.date,e.props),f=qn(e.state.date,e.props),p=!e.props.showMonthYearPicker&&!e.props.showQuarterYearPicker&&!e.props.showYearPicker;return m.createElement("div",{className:"react-datepicker__header react-datepicker__header--custom",onFocus:e.props.onDropdownFocus},(o=(s=e.props).renderCustomHeader)===null||o===void 0?void 0:o.call(s,E(E({},e.state),{customHeaderCount:c,monthDate:i,changeMonth:e.changeMonth,changeYear:e.changeYear,decreaseMonth:e.decreaseMonth,increaseMonth:e.increaseMonth,decreaseYear:e.decreaseYear,increaseYear:e.increaseYear,prevMonthButtonDisabled:u,nextMonthButtonDisabled:l,prevYearButtonDisabled:d,nextYearButtonDisabled:f})),p&&m.createElement("div",{className:"react-datepicker__day-names"},e.header(i)))},e.renderYearHeader=function(n){var s=n.monthDate,o=e.props,i=o.showYearPicker,c=o.yearItemNumber,u=c===void 0?r.defaultProps.yearItemNumber:c,l=xe(s,u),d=l.startPeriod,f=l.endPeriod;return m.createElement("div",{className:"react-datepicker__header react-datepicker-year-header"},i?"".concat(d," - ").concat(f):P(s))},e.renderHeader=function(n){var s=n.monthDate,o=n.i,i=o===void 0?0:o,c={monthDate:s,i};switch(!0){case e.props.renderCustomHeader!==void 0:return e.renderCustomHeader(c);case(e.props.showMonthYearPicker||e.props.showQuarterYearPicker||e.props.showYearPicker):return e.renderYearHeader(c);default:return e.renderDefaultHeader(c)}},e.renderMonths=function(){var n,s;if(!(e.props.showTimeSelectOnly||e.props.showYearPicker)){for(var o=[],i=(n=e.props.monthsShown)!==null&&n!==void 0?n:r.defaultProps.monthsShown,c=e.props.showPreviousMonths?i-1:0,u=e.props.showMonthYearPicker||e.props.showQuarterYearPicker?ge(e.state.date,c):Ie(e.state.date,c),l=(s=e.props.monthSelectedIn)!==null&&s!==void 0?s:c,d=0;d<i;++d){var f=d-l+c,p=e.props.showMonthYearPicker||e.props.showQuarterYearPicker?ge(u,f):ue(u,f),h="month-".concat(d),g=d<i-1,w=d>0;o.push(m.createElement("div",{key:h,ref:function(k){e.monthContainer=k??void 0},className:"react-datepicker__month-container"},e.renderHeader({monthDate:p,i:d}),m.createElement(Ic,E({},r.defaultProps,e.props,{ariaLabelPrefix:e.props.monthAriaLabelPrefix,day:p,onDayClick:e.handleDayClick,handleOnKeyDown:e.props.handleOnDayKeyDown,handleOnMonthKeyDown:e.props.handleOnKeyDown,onDayMouseEnter:e.handleDayMouseEnter,onMouseLeave:e.handleMonthMouseLeave,orderInDisplay:d,selectingDate:e.state.selectingDate,monthShowsDuplicateDaysEnd:g,monthShowsDuplicateDaysStart:w}))))}return o}},e.renderYears=function(){if(!e.props.showTimeSelectOnly&&e.props.showYearPicker)return m.createElement("div",{className:"react-datepicker__year--container"},e.renderHeader({monthDate:e.state.date}),m.createElement($c,E({},r.defaultProps,e.props,{selectingDate:e.state.selectingDate,date:e.state.date,onDayClick:e.handleDayClick,clearSelectingDate:e.clearSelectingDate,onYearMouseEnter:e.handleYearMouseEnter,onYearMouseLeave:e.handleYearMouseLeave})))},e.renderTimeSection=function(){if(e.props.showTimeSelect&&(e.state.monthContainer||e.props.showTimeSelectOnly))return m.createElement(Hc,E({},r.defaultProps,e.props,{onChange:e.props.onTimeChange,format:e.props.timeFormat,intervals:e.props.timeIntervals,monthRef:e.state.monthContainer}))},e.renderInputTimeSection=function(){var n=e.props.selected?new Date(e.props.selected):void 0,s=n&&Qt(n)&&!!e.props.selected,o=s?"".concat(Vn(n.getHours()),":").concat(Vn(n.getMinutes())):"";if(e.props.showTimeInput)return m.createElement(Tc,E({},r.defaultProps,e.props,{date:n,timeString:o,onChange:e.props.onTimeChange}))},e.renderAriaLiveRegion=function(){var n,s=xe(e.state.date,(n=e.props.yearItemNumber)!==null&&n!==void 0?n:r.defaultProps.yearItemNumber),o=s.startPeriod,i=s.endPeriod,c;return e.props.showYearPicker?c="".concat(o," - ").concat(i):e.props.showMonthYearPicker||e.props.showQuarterYearPicker?c=P(e.state.date):c="".concat(fn(te(e.state.date),e.props.locale)," ").concat(P(e.state.date)),m.createElement("span",{role:"alert","aria-live":"polite",className:"react-datepicker__aria-live"},e.state.isRenderAriaLiveMessage&&c)},e.renderChildren=function(){if(e.props.children)return m.createElement("div",{className:"react-datepicker__children-container"},e.props.children)},e.containerRef=v.createRef(),e.state={date:e.getDateInView(),selectingDate:void 0,monthContainer:void 0,isRenderAriaLiveMessage:!1},e}return Object.defineProperty(r,"defaultProps",{get:function(){return{monthsShown:1,forceShowMonthNavigation:!1,timeCaption:"Time",previousYearButtonLabel:"Previous Year",nextYearButtonLabel:"Next Year",previousMonthButtonLabel:"Previous Month",nextMonthButtonLabel:"Next Month",yearItemNumber:lt}},enumerable:!1,configurable:!0}),r.prototype.componentDidMount=function(){var t=this;this.props.showTimeSelect&&(this.assignMonthContainer=function(){t.setState({monthContainer:t.monthContainer})}())},r.prototype.componentDidUpdate=function(t){var e=this;if(this.props.preSelection&&(!O(this.props.preSelection,t.preSelection)||this.props.monthSelectedIn!==t.monthSelectedIn)){var n=!ee(this.state.date,this.props.preSelection);this.setState({date:this.props.preSelection},function(){return n&&e.handleCustomMonthChange(e.state.date)})}else this.props.openToDate&&!O(this.props.openToDate,t.openToDate)&&this.setState({date:this.props.openToDate})},r.prototype.render=function(){var t=this.props.container||ic;return m.createElement($t,{onClickOutside:this.handleClickOutside,style:{display:"contents"},containerRef:this.containerRef,ignoreClass:this.props.outsideClickIgnoreClass},m.createElement(t,{className:Z("react-datepicker",this.props.className,{"react-datepicker--time-only":this.props.showTimeSelectOnly}),showTime:this.props.showTimeSelect||this.props.showTimeInput,showTimeSelectOnly:this.props.showTimeSelectOnly},this.renderAriaLiveRegion(),this.renderPreviousButton(),this.renderNextButton(),this.renderMonths(),this.renderYears(),this.renderTodayButton(),this.renderTimeSection(),this.renderInputTimeSection(),this.renderChildren()))},r}(v.Component),jc=function(a){var r=a.icon,t=a.className,e=t===void 0?"":t,n=a.onClick,s="react-datepicker__calendar-icon";if(typeof r=="string")return m.createElement("i",{className:"".concat(s," ").concat(r," ").concat(e),"aria-hidden":"true",onClick:n});if(m.isValidElement(r)){var o=r;return m.cloneElement(o,{className:"".concat(o.props.className||""," ").concat(s," ").concat(e),onClick:function(i){typeof o.props.onClick=="function"&&o.props.onClick(i),typeof n=="function"&&n(i)}})}return m.createElement("svg",{className:"".concat(s," ").concat(e),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",onClick:n},m.createElement("path",{d:"M96 32V64H48C21.5 64 0 85.5 0 112v48H448V112c0-26.5-21.5-48-48-48H352V32c0-17.7-14.3-32-32-32s-32 14.3-32 32V64H160V32c0-17.7-14.3-32-32-32S96 14.3 96 32zM448 192H0V464c0 26.5 21.5 48 48 48H400c26.5 0 48-21.5 48-48V192z"}))},Nr=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.portalRoot=null,e.el=document.createElement("div"),e}return r.prototype.componentDidMount=function(){this.portalRoot=(this.props.portalHost||document).getElementById(this.props.portalId),this.portalRoot||(this.portalRoot=document.createElement("div"),this.portalRoot.setAttribute("id",this.props.portalId),(this.props.portalHost||document.body).appendChild(this.portalRoot)),this.portalRoot.appendChild(this.el)},r.prototype.componentWillUnmount=function(){this.portalRoot&&this.portalRoot.removeChild(this.el)},r.prototype.render=function(){return Lr.createPortal(this.props.children,this.el)},r}(v.Component),Xc="[tabindex], a, button, input, select, textarea",Gc=function(a){return(a instanceof HTMLAnchorElement||!a.disabled)&&a.tabIndex!==-1},Yr=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.getTabChildren=function(){var n;return Array.prototype.slice.call((n=e.tabLoopRef.current)===null||n===void 0?void 0:n.querySelectorAll(Xc),1,-1).filter(Gc)},e.handleFocusStart=function(){var n=e.getTabChildren();n&&n.length>1&&n[n.length-1].focus()},e.handleFocusEnd=function(){var n=e.getTabChildren();n&&n.length>1&&n[0].focus()},e.tabLoopRef=v.createRef(),e}return r.prototype.render=function(){var t;return((t=this.props.enableTabLoop)!==null&&t!==void 0?t:r.defaultProps.enableTabLoop)?m.createElement("div",{className:"react-datepicker__tab-loop",ref:this.tabLoopRef},m.createElement("div",{className:"react-datepicker__tab-loop__start",tabIndex:0,onFocus:this.handleFocusStart}),this.props.children,m.createElement("div",{className:"react-datepicker__tab-loop__end",tabIndex:0,onFocus:this.handleFocusEnd})):this.props.children},r.defaultProps={enableTabLoop:!0},r}(v.Component);function zc(a){var r=function(t){var e,n=typeof t.hidePopper=="boolean"?t.hidePopper:!0,s=v.useRef(null),o=oc(E({open:!n,whileElementsMounted:Hr,placement:t.popperPlacement,middleware:me([$r({padding:15}),Qr(10),Br({element:s})],(e=t.popperModifiers)!==null&&e!==void 0?e:[],!0)},t.popperProps)),i=E(E({},t),{hidePopper:n,popperProps:E(E({},o),{arrowRef:s})});return m.createElement(a,E({},i))};return r}var Zc=function(a){z(r,a);function r(){return a!==null&&a.apply(this,arguments)||this}return Object.defineProperty(r,"defaultProps",{get:function(){return{hidePopper:!0}},enumerable:!1,configurable:!0}),r.prototype.render=function(){var t=this.props,e=t.className,n=t.wrapperClassName,s=t.hidePopper,o=s===void 0?r.defaultProps.hidePopper:s,i=t.popperComponent,c=t.targetComponent,u=t.enableTabLoop,l=t.popperOnKeyDown,d=t.portalId,f=t.portalHost,p=t.popperProps,h=t.showArrow,g=void 0;if(!o){var w=Z("react-datepicker-popper",e);g=m.createElement(Yr,{enableTabLoop:u},m.createElement("div",{ref:p.refs.setFloating,style:p.floatingStyles,className:w,"data-placement":p.placement,onKeyDown:l},i,h&&m.createElement(Ji,{ref:p.arrowRef,context:p.context,fill:"currentColor",strokeWidth:1,height:8,width:16,style:{transform:"translateY(-1px)"},className:"react-datepicker__triangle"})))}this.props.popperContainer&&(g=v.createElement(this.props.popperContainer,{},g)),d&&!o&&(g=m.createElement(Nr,{portalId:d,portalHost:f},g));var k=Z("react-datepicker-wrapper",n);return m.createElement(m.Fragment,null,m.createElement("div",{ref:p.refs.setReference,className:k},c),g)},r}(v.Component),Jc=zc(Zc),Zn="react-datepicker-ignore-onclickoutside";function eu(a,r){return a&&r?te(a)!==te(r)||P(a)!==P(r):a!==r}var Gt="Date input not valid.",hu=function(a){z(r,a);function r(t){var e=a.call(this,t)||this;return e.calendar=null,e.input=null,e.getPreSelection=function(){return e.props.openToDate?e.props.openToDate:e.props.selectsEnd&&e.props.startDate?e.props.startDate:e.props.selectsStart&&e.props.endDate?e.props.endDate:R()},e.modifyHolidays=function(){var n;return(n=e.props.holidays)===null||n===void 0?void 0:n.reduce(function(s,o){var i=new Date(o.date);return Qt(i)?me(me([],s,!0),[E(E({},o),{date:i})],!1):s},[])},e.calcInitialState=function(){var n,s=e.getPreSelection(),o=Tr(e.props),i=Or(e.props),c=o&&Fe(s,_t(o))?o:i&&Pe(s,Ln(i))?i:s;return{open:e.props.startOpen||!1,preventFocus:!1,inputValue:null,preSelection:(n=e.props.selectsRange?e.props.startDate:e.props.selected)!==null&&n!==void 0?n:c,highlightDates:Kn(e.props.highlightDates),focused:!1,shouldFocusDayInline:!1,isRenderAriaLiveMessage:!1,wasHidden:!1}},e.resetHiddenStatus=function(){e.setState(E(E({},e.state),{wasHidden:!1}))},e.setHiddenStatus=function(){e.setState(E(E({},e.state),{wasHidden:!0}))},e.setHiddenStateOnVisibilityHidden=function(){document.visibilityState==="hidden"&&e.setHiddenStatus()},e.clearPreventFocusTimeout=function(){e.preventFocusTimeout&&clearTimeout(e.preventFocusTimeout)},e.safeFocus=function(){setTimeout(function(){var n,s;(s=(n=e.input)===null||n===void 0?void 0:n.focus)===null||s===void 0||s.call(n,{preventScroll:!0})},0)},e.safeBlur=function(){setTimeout(function(){var n,s;(s=(n=e.input)===null||n===void 0?void 0:n.blur)===null||s===void 0||s.call(n)},0)},e.setFocus=function(){e.safeFocus()},e.setBlur=function(){e.safeBlur(),e.cancelFocusInput()},e.setOpen=function(n,s){s===void 0&&(s=!1),e.setState({open:n,preSelection:n&&e.state.open?e.state.preSelection:e.calcInitialState().preSelection,lastPreSelectChange:zt},function(){n||e.setState(function(o){return{focused:s?o.focused:!1}},function(){!s&&e.setBlur(),e.setState({inputValue:null})})})},e.inputOk=function(){return we(e.state.preSelection)},e.isCalendarOpen=function(){return e.props.open===void 0?e.state.open&&!e.props.disabled&&!e.props.readOnly:e.props.open},e.handleFocus=function(n){var s,o,i=e.state.wasHidden,c=i?e.state.open:!0;i&&e.resetHiddenStatus(),e.state.preventFocus||((o=(s=e.props).onFocus)===null||o===void 0||o.call(s,n),c&&!e.props.preventOpenOnFocus&&!e.props.readOnly&&e.setOpen(!0)),e.setState({focused:!0})},e.sendFocusBackToInput=function(){e.preventFocusTimeout&&e.clearPreventFocusTimeout(),e.setState({preventFocus:!0},function(){e.preventFocusTimeout=setTimeout(function(){e.setFocus(),e.setState({preventFocus:!1})})})},e.cancelFocusInput=function(){clearTimeout(e.inputFocusTimeout),e.inputFocusTimeout=void 0},e.deferFocusInput=function(){e.cancelFocusInput(),e.inputFocusTimeout=setTimeout(function(){return e.setFocus()},1)},e.handleDropdownFocus=function(){e.cancelFocusInput()},e.handleBlur=function(n){var s,o;(!e.state.open||e.props.withPortal||e.props.showTimeInput)&&((o=(s=e.props).onBlur)===null||o===void 0||o.call(s,n)),e.setState({focused:!1})},e.handleCalendarClickOutside=function(n){var s,o;e.props.inline||e.setOpen(!1),(o=(s=e.props).onClickOutside)===null||o===void 0||o.call(s,n),e.props.withPortal&&n.preventDefault()},e.handleChange=function(){for(var n,s,o,i,c,u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];var d=u[0];if(!(e.props.onChangeRaw&&(e.props.onChangeRaw.apply(e,u),!d||typeof d.isDefaultPrevented!="function"||d.isDefaultPrevented()))){e.setState({inputValue:(d==null?void 0:d.target)instanceof HTMLInputElement?d.target.value:null,lastPreSelectChange:tu});var f=e.props,p=f.selectsRange,h=f.startDate,g=f.endDate,w=(n=e.props.dateFormat)!==null&&n!==void 0?n:r.defaultProps.dateFormat,k=(s=e.props.strictParsing)!==null&&s!==void 0?s:r.defaultProps.strictParsing,S=(d==null?void 0:d.target)instanceof HTMLInputElement?d.target.value:"";if(p){var x=S.split("-",2).map(function(X){return X.trim()}),N=x[0],q=x[1],$=Ut(N??"",w,e.props.locale,k),I=Ut(q??"",w,e.props.locale,k),_=(h==null?void 0:h.getTime())!==($==null?void 0:$.getTime()),M=(g==null?void 0:g.getTime())!==(I==null?void 0:I.getTime());if(!_&&!M||$&&se($,e.props)||I&&se(I,e.props))return;(i=(o=e.props).onChange)===null||i===void 0||i.call(o,[$,I],d)}else{var F=Ut(S,w,e.props.locale,k,(c=e.props.selected)!==null&&c!==void 0?c:void 0);(F||!S)&&e.setSelected(F,d,!0)}}},e.handleSelect=function(n,s,o){if(e.props.shouldCloseOnSelect&&!e.props.showTimeSelect&&e.sendFocusBackToInput(),e.props.onChangeRaw&&e.props.onChangeRaw(s),e.setSelected(n,s,!1,o),e.props.showDateSelect&&e.setState({isRenderAriaLiveMessage:!0}),!e.props.shouldCloseOnSelect||e.props.showTimeSelect)e.setPreSelection(n);else if(!e.props.inline){e.props.selectsRange||e.setOpen(!1);var i=e.props,c=i.startDate,u=i.endDate;c&&!u&&(e.props.swapRange||!Xn(n,c))&&e.setOpen(!1)}},e.setSelected=function(n,s,o,i){var c,u,l=n;if(e.props.showYearPicker){if(l!==null&&Mt(P(l),e.props))return}else if(e.props.showMonthYearPicker){if(l!==null&&Pr(l,e.props))return}else if(l!==null&&se(l,e.props))return;var d=e.props,f=d.onChange,p=d.selectsRange,h=d.startDate,g=d.endDate,w=d.selectsMultiple,k=d.selectedDates,S=d.minTime,x=d.swapRange;if(!Ee(e.props.selected,l)||e.props.allowSameDay||p||w)if(l!==null&&(e.props.selected&&(!o||!e.props.showTimeSelect&&!e.props.showTimeSelectOnly&&!e.props.showTimeInput)&&(l=jt(l,{hour:De(e.props.selected),minute:ye(e.props.selected),second:Se(e.props.selected)})),!o&&(e.props.showTimeSelect||e.props.showTimeSelectOnly)&&S&&(l=jt(l,{hour:S.getHours(),minute:S.getMinutes(),second:S.getSeconds()})),e.props.inline||e.setState({preSelection:l}),e.props.focusSelectedMonth||e.setState({monthSelectedIn:i})),p){var N=!h&&!g,q=h&&!g,$=h&&g;N?f==null||f([l,null],s):q&&(l===null?f==null||f([null,null],s):Xn(l,h)?x?f==null||f([l,h],s):f==null||f([l,null],s):f==null||f([h,l],s)),$&&(f==null||f([l,null],s))}else if(w){if(l!==null)if(!(k!=null&&k.length))f==null||f([l],s);else{var I=k.some(function(M){return O(M,l)});if(I){var _=k.filter(function(M){return!O(M,l)});f==null||f(_,s)}else f==null||f(me(me([],k,!0),[l],!1),s)}}else f==null||f(l,s);o||((u=(c=e.props).onSelect)===null||u===void 0||u.call(c,l,s),e.setState({inputValue:null}))},e.setPreSelection=function(n){var s=we(e.props.minDate),o=we(e.props.maxDate),i=!0;if(n){var c=_t(n);if(s&&o)i=ot(n,e.props.minDate,e.props.maxDate);else if(s){var u=_t(e.props.minDate);i=Pe(n,u)||Ee(c,u)}else if(o){var l=Ln(e.props.maxDate);i=Fe(n,l)||Ee(c,l)}}i&&e.setState({preSelection:n})},e.toggleCalendar=function(){e.setOpen(!e.state.open)},e.handleTimeChange=function(n){var s,o;if(!(e.props.selectsRange||e.props.selectsMultiple)){var i=e.props.selected?e.props.selected:e.getPreSelection(),c=e.props.selected?n:jt(i,{hour:De(n),minute:ye(n)});e.setState({preSelection:c}),(o=(s=e.props).onChange)===null||o===void 0||o.call(s,c),e.props.shouldCloseOnSelect&&!e.props.showTimeInput&&(e.sendFocusBackToInput(),e.setOpen(!1)),e.props.showTimeInput&&e.setOpen(!0),(e.props.showTimeSelectOnly||e.props.showTimeSelect)&&e.setState({isRenderAriaLiveMessage:!0}),e.setState({inputValue:null})}},e.onInputClick=function(){var n,s;!e.props.disabled&&!e.props.readOnly&&e.setOpen(!0),(s=(n=e.props).onInputClick)===null||s===void 0||s.call(n)},e.onInputKeyDown=function(n){var s,o,i,c,u,l;(o=(s=e.props).onKeyDown)===null||o===void 0||o.call(s,n);var d=n.key;if(!e.state.open&&!e.props.inline&&!e.props.preventOpenOnFocus){(d===D.ArrowDown||d===D.ArrowUp||d===D.Enter)&&((i=e.onInputClick)===null||i===void 0||i.call(e));return}if(e.state.open){if(d===D.ArrowDown||d===D.ArrowUp){n.preventDefault();var f=e.props.showTimeSelectOnly?".react-datepicker__time-list-item[tabindex='0']":e.props.showWeekPicker&&e.props.showWeekNumbers?'.react-datepicker__week-number[tabindex="0"]':e.props.showFullMonthYearPicker||e.props.showMonthYearPicker?'.react-datepicker__month-text[tabindex="0"]':'.react-datepicker__day[tabindex="0"]',p=((c=e.calendar)===null||c===void 0?void 0:c.containerRef.current)instanceof Element&&e.calendar.containerRef.current.querySelector(f);p instanceof HTMLElement&&p.focus({preventScroll:!0});return}var h=R(e.state.preSelection);d===D.Enter?(n.preventDefault(),n.target.blur(),e.inputOk()&&e.state.lastPreSelectChange===zt?(e.handleSelect(h,n),!e.props.shouldCloseOnSelect&&e.setPreSelection(h)):e.setOpen(!1)):d===D.Escape?(n.preventDefault(),n.target.blur(),e.sendFocusBackToInput(),e.setOpen(!1)):d===D.Tab&&e.setOpen(!1),e.inputOk()||(l=(u=e.props).onInputError)===null||l===void 0||l.call(u,{code:1,msg:Gt})}},e.onPortalKeyDown=function(n){var s=n.key;s===D.Escape&&(n.preventDefault(),e.setState({preventFocus:!0},function(){e.setOpen(!1),setTimeout(function(){e.setFocus(),e.setState({preventFocus:!1})})}))},e.onDayKeyDown=function(n){var s,o,i,c,u,l,d=e.props,f=d.minDate,p=d.maxDate,h=d.disabledKeyboardNavigation,g=d.showWeekPicker,w=d.shouldCloseOnSelect,k=d.locale,S=d.calendarStartDay,x=d.adjustDateOnChange,N=d.inline;if((o=(s=e.props).onKeyDown)===null||o===void 0||o.call(s,n),!h){var q=n.key,$=n.shiftKey,I=R(e.state.preSelection),_=function(G,A){var Q=A;switch(G){case D.ArrowRight:Q=g?Pt(A,1):ce(A,1);break;case D.ArrowLeft:Q=g?Nn(A):Oi(A);break;case D.ArrowUp:Q=Nn(A);break;case D.ArrowDown:Q=Pt(A,1);break;case D.PageUp:Q=$?Ue(A,1):Ie(A,1);break;case D.PageDown:Q=$?ge(A,1):ue(A,1);break;case D.Home:Q=Ce(A,k,S);break;case D.End:Q=pc(A);break}return Q},M=function(G,A){for(var Q=40,ne=G,Xe=!1,hn=0,ie=_(G,A);!Xe;){if(hn>=Q){ie=A;break}f&&ie<f&&(ne=D.ArrowRight,ie=se(f,e.props)?_(ne,ie):f),p&&ie>p&&(ne=D.ArrowLeft,ie=se(p,e.props)?_(ne,ie):p),se(ie,e.props)?((ne===D.PageUp||ne===D.Home)&&(ne=D.ArrowRight),(ne===D.PageDown||ne===D.End)&&(ne=D.ArrowLeft),ie=_(ne,ie)):Xe=!0,hn++}return ie};if(q===D.Enter){n.preventDefault(),e.handleSelect(I,n),!w&&e.setPreSelection(I);return}else if(q===D.Escape){n.preventDefault(),e.setOpen(!1),e.inputOk()||(c=(i=e.props).onInputError)===null||c===void 0||c.call(i,{code:1,msg:Gt});return}var F=null;switch(q){case D.ArrowLeft:case D.ArrowRight:case D.ArrowUp:case D.ArrowDown:case D.PageUp:case D.PageDown:case D.Home:case D.End:F=M(q,I);break}if(!F){(l=(u=e.props).onInputError)===null||l===void 0||l.call(u,{code:1,msg:Gt});return}if(n.preventDefault(),e.setState({lastPreSelectChange:zt}),x&&e.setSelected(F),e.setPreSelection(F),N){var X=te(I),K=te(F),J=P(I),le=P(F);X!==K||J!==le?e.setState({shouldFocusDayInline:!0}):e.setState({shouldFocusDayInline:!1})}}},e.onPopperKeyDown=function(n){var s=n.key;s===D.Escape&&(n.preventDefault(),e.sendFocusBackToInput())},e.onClearClick=function(n){n&&n.preventDefault&&n.preventDefault(),e.sendFocusBackToInput();var s=e.props,o=s.selectsRange,i=s.onChange;o?i==null||i([null,null],n):i==null||i(null,n),e.setState({inputValue:null})},e.clear=function(){e.onClearClick()},e.onScroll=function(n){typeof e.props.closeOnScroll=="boolean"&&e.props.closeOnScroll?(n.target===document||n.target===document.documentElement||n.target===document.body)&&e.setOpen(!1):typeof e.props.closeOnScroll=="function"&&e.props.closeOnScroll(n)&&e.setOpen(!1)},e.renderCalendar=function(){var n,s;return!e.props.inline&&!e.isCalendarOpen()?null:m.createElement(Uc,E({showMonthYearDropdown:void 0,ref:function(o){e.calendar=o}},e.props,e.state,{setOpen:e.setOpen,dateFormat:(n=e.props.dateFormatCalendar)!==null&&n!==void 0?n:r.defaultProps.dateFormatCalendar,onSelect:e.handleSelect,onClickOutside:e.handleCalendarClickOutside,holidays:xc(e.modifyHolidays()),outsideClickIgnoreClass:Zn,onDropdownFocus:e.handleDropdownFocus,onTimeChange:e.handleTimeChange,className:e.props.calendarClassName,container:e.props.calendarContainer,handleOnKeyDown:e.props.onKeyDown,handleOnDayKeyDown:e.onDayKeyDown,setPreSelection:e.setPreSelection,dropdownMode:(s=e.props.dropdownMode)!==null&&s!==void 0?s:r.defaultProps.dropdownMode}),e.props.children)},e.renderAriaLiveRegion=function(){var n=e.props,s=n.dateFormat,o=s===void 0?r.defaultProps.dateFormat:s,i=n.locale,c=e.props.showTimeInput||e.props.showTimeSelect,u=c?"PPPPp":"PPPP",l;return e.props.selectsRange?l="Selected start date: ".concat(re(e.props.startDate,{dateFormat:u,locale:i}),". ").concat(e.props.endDate?"End date: "+re(e.props.endDate,{dateFormat:u,locale:i}):""):e.props.showTimeSelectOnly?l="Selected time: ".concat(re(e.props.selected,{dateFormat:o,locale:i})):e.props.showYearPicker?l="Selected year: ".concat(re(e.props.selected,{dateFormat:"yyyy",locale:i})):e.props.showMonthYearPicker?l="Selected month: ".concat(re(e.props.selected,{dateFormat:"MMMM yyyy",locale:i})):e.props.showQuarterYearPicker?l="Selected quarter: ".concat(re(e.props.selected,{dateFormat:"yyyy, QQQ",locale:i})):l="Selected date: ".concat(re(e.props.selected,{dateFormat:u,locale:i})),m.createElement("span",{role:"alert","aria-live":"polite",className:"react-datepicker__aria-live"},l)},e.renderDateInput=function(){var n,s,o,i=Z(e.props.className,(n={},n[Zn]=e.state.open,n)),c=e.props.customInput||m.createElement("input",{type:"text"}),u=e.props.customInputRef||"ref",l=e.props,d=l.dateFormat,f=d===void 0?r.defaultProps.dateFormat:d,p=l.locale,h=typeof e.props.value=="string"?e.props.value:typeof e.state.inputValue=="string"?e.state.inputValue:e.props.selectsRange?uc(e.props.startDate,e.props.endDate,{dateFormat:f,locale:p}):e.props.selectsMultiple?lc((o=e.props.selectedDates)!==null&&o!==void 0?o:[],{dateFormat:f,locale:p}):re(e.props.selected,{dateFormat:f,locale:p});return v.cloneElement(c,(s={},s[u]=function(g){e.input=g},s.value=h,s.onBlur=e.handleBlur,s.onChange=e.handleChange,s.onClick=e.onInputClick,s.onFocus=e.handleFocus,s.onKeyDown=e.onInputKeyDown,s.id=e.props.id,s.name=e.props.name,s.form=e.props.form,s.autoFocus=e.props.autoFocus,s.placeholder=e.props.placeholderText,s.disabled=e.props.disabled,s.autoComplete=e.props.autoComplete,s.className=Z(c.props.className,i),s.title=e.props.title,s.readOnly=e.props.readOnly,s.required=e.props.required,s.tabIndex=e.props.tabIndex,s["aria-describedby"]=e.props.ariaDescribedBy,s["aria-invalid"]=e.props.ariaInvalid,s["aria-labelledby"]=e.props.ariaLabelledBy,s["aria-required"]=e.props.ariaRequired,s))},e.renderClearButton=function(){var n=e.props,s=n.isClearable,o=n.disabled,i=n.selected,c=n.startDate,u=n.endDate,l=n.clearButtonTitle,d=n.clearButtonClassName,f=d===void 0?"":d,p=n.ariaLabelClose,h=p===void 0?"Close":p,g=n.selectedDates;return s&&(i!=null||c!=null||u!=null||g!=null&&g.length)?m.createElement("button",{type:"button",className:Z("react-datepicker__close-icon",f,{"react-datepicker__close-icon--disabled":o}),disabled:o,"aria-label":h,onClick:e.onClearClick,title:l,tabIndex:-1}):null},e.state=e.calcInitialState(),e.preventFocusTimeout=void 0,e}return Object.defineProperty(r,"defaultProps",{get:function(){return{allowSameDay:!1,dateFormat:"MM/dd/yyyy",dateFormatCalendar:"LLLL yyyy",disabled:!1,disabledKeyboardNavigation:!1,dropdownMode:"scroll",preventOpenOnFocus:!1,monthsShown:1,readOnly:!1,withPortal:!1,selectsDisabledDaysInRange:!1,shouldCloseOnSelect:!0,showTimeSelect:!1,showTimeInput:!1,showPreviousMonths:!1,showMonthYearPicker:!1,showFullMonthYearPicker:!1,showTwoColumnMonthYearPicker:!1,showFourColumnMonthYearPicker:!1,showYearPicker:!1,showQuarterYearPicker:!1,showWeekPicker:!1,strictParsing:!1,swapRange:!1,timeIntervals:30,timeCaption:"Time",previousMonthAriaLabel:"Previous Month",previousMonthButtonLabel:"Previous Month",nextMonthAriaLabel:"Next Month",nextMonthButtonLabel:"Next Month",previousYearAriaLabel:"Previous Year",previousYearButtonLabel:"Previous Year",nextYearAriaLabel:"Next Year",nextYearButtonLabel:"Next Year",timeInputLabel:"Time",enableTabLoop:!0,yearItemNumber:lt,focusSelectedMonth:!1,showPopperArrow:!0,excludeScrollbar:!0,customTimeInput:null,calendarStartDay:void 0,toggleCalendarOnIconClick:!1,usePointerEvent:!1}},enumerable:!1,configurable:!0}),r.prototype.componentDidMount=function(){window.addEventListener("scroll",this.onScroll,!0),document.addEventListener("visibilitychange",this.setHiddenStateOnVisibilityHidden)},r.prototype.componentDidUpdate=function(t,e){var n,s,o,i;t.inline&&eu(t.selected,this.props.selected)&&this.setPreSelection(this.props.selected),this.state.monthSelectedIn!==void 0&&t.monthsShown!==this.props.monthsShown&&this.setState({monthSelectedIn:0}),t.highlightDates!==this.props.highlightDates&&this.setState({highlightDates:Kn(this.props.highlightDates)}),!e.focused&&!Ee(t.selected,this.props.selected)&&this.setState({inputValue:null}),e.open!==this.state.open&&(e.open===!1&&this.state.open===!0&&((s=(n=this.props).onCalendarOpen)===null||s===void 0||s.call(n)),e.open===!0&&this.state.open===!1&&((i=(o=this.props).onCalendarClose)===null||i===void 0||i.call(o)))},r.prototype.componentWillUnmount=function(){this.clearPreventFocusTimeout(),window.removeEventListener("scroll",this.onScroll,!0),document.removeEventListener("visibilitychange",this.setHiddenStateOnVisibilityHidden)},r.prototype.renderInputContainer=function(){var t=this.props,e=t.showIcon,n=t.icon,s=t.calendarIconClassname,o=t.calendarIconClassName,i=t.toggleCalendarOnIconClick,c=this.state.open;return s&&console.warn("calendarIconClassname props is deprecated. should use calendarIconClassName props."),m.createElement("div",{className:"react-datepicker__input-container".concat(e?" react-datepicker__view-calendar-icon":"")},e&&m.createElement(jc,E({icon:n,className:Z(o,!o&&s,c&&"react-datepicker-ignore-onclickoutside")},i?{onClick:this.toggleCalendar}:null)),this.state.isRenderAriaLiveMessage&&this.renderAriaLiveRegion(),this.renderDateInput(),this.renderClearButton())},r.prototype.render=function(){var t=this.renderCalendar();if(this.props.inline)return t;if(this.props.withPortal){var e=this.state.open?m.createElement(Yr,{enableTabLoop:this.props.enableTabLoop},m.createElement("div",{className:"react-datepicker__portal",tabIndex:-1,onKeyDown:this.onPortalKeyDown},t)):null;return this.state.open&&this.props.portalId&&(e=m.createElement(Nr,E({portalId:this.props.portalId},this.props),e)),m.createElement("div",null,this.renderInputContainer(),e)}return m.createElement(Jc,E({},this.props,{className:this.props.popperClassName,hidePopper:!this.isCalendarOpen(),targetComponent:this.renderInputContainer(),popperComponent:t,popperOnKeyDown:this.onPopperKeyDown,showArrow:this.props.showPopperArrow}))},r}(v.Component),tu="input",zt="navigate";export{hu as D,lu as a,iu as b,ou as c,as as d,du as e,cu as f,uu as g,fu as h,Gr as i,pu as p}; diff --git a/pkg/ui/frontend/dist/assets/form-libs-B6JBoFJD.js b/pkg/ui/frontend/dist/assets/form-libs-B6JBoFJD.js new file mode 100644 index 0000000000000..30d726f4e1bd6 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/form-libs-B6JBoFJD.js @@ -0,0 +1 @@ +import{b as I}from"./react-core-D_V7s-9r.js";var Ge=r=>r.type==="checkbox",Ae=r=>r instanceof Date,H=r=>r==null;const mr=r=>typeof r=="object";var j=r=>!H(r)&&!Array.isArray(r)&&mr(r)&&!Ae(r),pr=r=>j(r)&&r.target?Ge(r.target)?r.target.checked:r.target.value:r,$r=r=>r.substring(0,r.search(/\.\d+(\.|$)/))||r,yr=(r,e)=>r.has($r(e)),Ur=r=>{const e=r.constructor&&r.constructor.prototype;return j(e)&&e.hasOwnProperty("isPrototypeOf")},jt=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function G(r){let e;const t=Array.isArray(r),s=typeof FileList<"u"?r instanceof FileList:!1;if(r instanceof Date)e=new Date(r);else if(r instanceof Set)e=new Set(r);else if(!(jt&&(r instanceof Blob||s))&&(t||j(r)))if(e=t?[]:{},!t&&!Ur(r))e=r;else for(const n in r)r.hasOwnProperty(n)&&(e[n]=G(r[n]));else return r;return e}var _t=r=>Array.isArray(r)?r.filter(Boolean):[],Z=r=>r===void 0,p=(r,e,t)=>{if(!e||!j(r))return t;const s=_t(e.split(/[,[\].]+?/)).reduce((n,a)=>H(n)?n:n[a],r);return Z(s)||s===r?Z(r[e])?t:r[e]:s},re=r=>typeof r=="boolean",Mt=r=>/^\w*$/.test(r),_r=r=>_t(r.replace(/["|']|\]/g,"").split(/\.|\[/)),F=(r,e,t)=>{let s=-1;const n=Mt(e)?[e]:_r(e),a=n.length,i=a-1;for(;++s<a;){const d=n[s];let c=t;if(s!==i){const h=r[d];c=j(h)||Array.isArray(h)?h:isNaN(+n[s+1])?{}:[]}if(d==="__proto__"||d==="constructor"||d==="prototype")return;r[d]=c,r=r[d]}return r};const et={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},ae={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},fe={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},gr=I.createContext(null),Lt=()=>I.useContext(gr),Fs=r=>{const{children:e,...t}=r;return I.createElement(gr.Provider,{value:t},e)};var vr=(r,e,t,s=!0)=>{const n={defaultValues:e._defaultValues};for(const a in r)Object.defineProperty(n,a,{get:()=>{const i=a;return e._proxyFormState[i]!==ae.all&&(e._proxyFormState[i]=!s||ae.all),t&&(t[i]=!0),r[i]}});return n},X=r=>j(r)&&!Object.keys(r).length,xr=(r,e,t,s)=>{t(r);const{name:n,...a}=r;return X(a)||Object.keys(a).length>=Object.keys(e).length||Object.keys(a).find(i=>e[i]===(!s||ae.all))},ze=r=>Array.isArray(r)?r:[r],br=(r,e,t)=>!r||!e||r===e||ze(r).some(s=>s&&(t?s===e:s.startsWith(e)||e.startsWith(s)));function Pt(r){const e=I.useRef(r);e.current=r,I.useEffect(()=>{const t=!r.disabled&&e.current.subject&&e.current.subject.subscribe({next:e.current.next});return()=>{t&&t.unsubscribe()}},[r.disabled])}function Br(r){const e=Lt(),{control:t=e.control,disabled:s,name:n,exact:a}=r,[i,d]=I.useState(t._formState),c=I.useRef(!0),h=I.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),y=I.useRef(n);return y.current=n,Pt({disabled:s,next:k=>c.current&&br(y.current,k.name,a)&&xr(k,h.current,t._updateFormState)&&d({...t._formState,...k}),subject:t._subjects.state}),I.useEffect(()=>(c.current=!0,h.current.isValid&&t._updateValid(!0),()=>{c.current=!1}),[t]),I.useMemo(()=>vr(i,t,h.current,!1),[i,t])}var ue=r=>typeof r=="string",kr=(r,e,t,s,n)=>ue(r)?(s&&e.watch.add(r),p(t,r,n)):Array.isArray(r)?r.map(a=>(s&&e.watch.add(a),p(t,a))):(s&&(e.watchAll=!0),t);function zr(r){const e=Lt(),{control:t=e.control,name:s,defaultValue:n,disabled:a,exact:i}=r,d=I.useRef(s);d.current=s,Pt({disabled:a,subject:t._subjects.values,next:y=>{br(d.current,y.name,i)&&h(G(kr(d.current,t._names,y.values||t._formValues,!1,n)))}});const[c,h]=I.useState(t._getWatch(s,n));return I.useEffect(()=>t._removeUnmounted()),c}function Wr(r){const e=Lt(),{name:t,disabled:s,control:n=e.control,shouldUnregister:a}=r,i=yr(n._names.array,t),d=zr({control:n,name:t,defaultValue:p(n._formValues,t,p(n._defaultValues,t,r.defaultValue)),exact:!0}),c=Br({control:n,name:t,exact:!0}),h=I.useRef(n.register(t,{...r.rules,value:d,...re(r.disabled)?{disabled:r.disabled}:{}})),y=I.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!p(c.errors,t)},isDirty:{enumerable:!0,get:()=>!!p(c.dirtyFields,t)},isTouched:{enumerable:!0,get:()=>!!p(c.touchedFields,t)},isValidating:{enumerable:!0,get:()=>!!p(c.validatingFields,t)},error:{enumerable:!0,get:()=>p(c.errors,t)}}),[c,t]),k=I.useMemo(()=>({name:t,value:d,...re(s)||c.disabled?{disabled:c.disabled||s}:{},onChange:M=>h.current.onChange({target:{value:pr(M),name:t},type:et.CHANGE}),onBlur:()=>h.current.onBlur({target:{value:p(n._formValues,t),name:t},type:et.BLUR}),ref:M=>{const Y=p(n._fields,t);Y&&M&&(Y._f.ref={focus:()=>M.focus(),select:()=>M.select(),setCustomValidity:z=>M.setCustomValidity(z),reportValidity:()=>M.reportValidity()})}}),[t,n._formValues,s,c.disabled,d,n._fields]);return I.useEffect(()=>{const M=n._options.shouldUnregister||a,Y=(z,q)=>{const K=p(n._fields,z);K&&K._f&&(K._f.mount=q)};if(Y(t,!0),M){const z=G(p(n._options.defaultValues,t));F(n._defaultValues,t,z),Z(p(n._formValues,t))&&F(n._formValues,t,z)}return!i&&n.register(t),()=>{(i?M&&!n._state.action:M)?n.unregister(t):Y(t,!1)}},[t,n,i,a]),I.useEffect(()=>{n._updateDisabledField({disabled:s,fields:n._fields,name:t})},[s,t,n]),I.useMemo(()=>({field:k,formState:c,fieldState:y}),[k,c,y])}const Is=r=>r.render(Wr(r));var qr=(r,e,t,s,n)=>e?{...t[r],types:{...t[r]&&t[r].types?t[r].types:{},[s]:n||!0}}:{},er=r=>({isOnSubmit:!r||r===ae.onSubmit,isOnBlur:r===ae.onBlur,isOnChange:r===ae.onChange,isOnAll:r===ae.all,isOnTouch:r===ae.onTouched}),tr=(r,e,t)=>!t&&(e.watchAll||e.watch.has(r)||[...e.watch].some(s=>r.startsWith(s)&&/^\.\w+/.test(r.slice(s.length))));const We=(r,e,t,s)=>{for(const n of t||Object.keys(r)){const a=p(r,n);if(a){const{_f:i,...d}=a;if(i){if(i.refs&&i.refs[0]&&e(i.refs[0],n)&&!s)return!0;if(i.ref&&e(i.ref,i.name)&&!s)return!0;if(We(d,e))break}else if(j(d)&&We(d,e))break}}};var Hr=(r,e,t)=>{const s=ze(p(r,t));return F(s,"root",e[t]),F(r,t,s),r},$t=r=>r.type==="file",ie=r=>typeof r=="function",tt=r=>{if(!jt)return!1;const e=r?r.ownerDocument:0;return r instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},Ke=r=>ue(r),Ut=r=>r.type==="radio",rt=r=>r instanceof RegExp;const rr={value:!1,isValid:!1},sr={value:!0,isValid:!0};var wr=r=>{if(Array.isArray(r)){if(r.length>1){const e=r.filter(t=>t&&t.checked&&!t.disabled).map(t=>t.value);return{value:e,isValid:!!e.length}}return r[0].checked&&!r[0].disabled?r[0].attributes&&!Z(r[0].attributes.value)?Z(r[0].value)||r[0].value===""?sr:{value:r[0].value,isValid:!0}:sr:rr}return rr};const nr={isValid:!1,value:null};var Ar=r=>Array.isArray(r)?r.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,nr):nr;function ar(r,e,t="validate"){if(Ke(r)||Array.isArray(r)&&r.every(Ke)||re(r)&&!r)return{type:t,message:Ke(r)?r:"",ref:e}}var Ee=r=>j(r)&&!rt(r)?r:{value:r,message:""},ir=async(r,e,t,s,n,a)=>{const{ref:i,refs:d,required:c,maxLength:h,minLength:y,min:k,max:M,pattern:Y,validate:z,name:q,valueAsNumber:K,mount:ge}=r._f,R=p(t,q);if(!ge||e.has(q))return{};const le=d?d[0]:i,ce=E=>{n&&le.reportValidity&&(le.setCustomValidity(re(E)?"":E||""),le.reportValidity())},L={},Ce=Ut(i),Xe=Ge(i),we=Ce||Xe,Ve=(K||$t(i))&&Z(i.value)&&Z(R)||tt(i)&&i.value===""||R===""||Array.isArray(R)&&!R.length,ee=qr.bind(null,q,s,L),Qe=(E,N,P,W=fe.maxLength,ne=fe.minLength)=>{const te=E?N:P;L[q]={type:E?W:ne,message:te,ref:i,...ee(E?W:ne,te)}};if(a?!Array.isArray(R)||!R.length:c&&(!we&&(Ve||H(R))||re(R)&&!R||Xe&&!wr(d).isValid||Ce&&!Ar(d).isValid)){const{value:E,message:N}=Ke(c)?{value:!!c,message:c}:Ee(c);if(E&&(L[q]={type:fe.required,message:N,ref:le,...ee(fe.required,N)},!s))return ce(N),L}if(!Ve&&(!H(k)||!H(M))){let E,N;const P=Ee(M),W=Ee(k);if(!H(R)&&!isNaN(R)){const ne=i.valueAsNumber||R&&+R;H(P.value)||(E=ne>P.value),H(W.value)||(N=ne<W.value)}else{const ne=i.valueAsDate||new Date(R),te=Me=>new Date(new Date().toDateString()+" "+Me),Ze=i.type=="time",je=i.type=="week";ue(P.value)&&R&&(E=Ze?te(R)>te(P.value):je?R>P.value:ne>new Date(P.value)),ue(W.value)&&R&&(N=Ze?te(R)<te(W.value):je?R<W.value:ne<new Date(W.value))}if((E||N)&&(Qe(!!E,P.message,W.message,fe.max,fe.min),!s))return ce(L[q].message),L}if((h||y)&&!Ve&&(ue(R)||a&&Array.isArray(R))){const E=Ee(h),N=Ee(y),P=!H(E.value)&&R.length>+E.value,W=!H(N.value)&&R.length<+N.value;if((P||W)&&(Qe(P,E.message,N.message),!s))return ce(L[q].message),L}if(Y&&!Ve&&ue(R)){const{value:E,message:N}=Ee(Y);if(rt(E)&&!R.match(E)&&(L[q]={type:fe.pattern,message:N,ref:i,...ee(fe.pattern,N)},!s))return ce(N),L}if(z){if(ie(z)){const E=await z(R,t),N=ar(E,le);if(N&&(L[q]={...N,...ee(fe.validate,N.message)},!s))return ce(N.message),L}else if(j(z)){let E={};for(const N in z){if(!X(E)&&!s)break;const P=ar(await z[N](R,t),le,N);P&&(E={...P,...ee(N,P.message)},ce(P.message),s&&(L[q]=E))}if(!X(E)&&(L[q]={ref:le,...E},!s))return L}}return ce(!0),L};function Jr(r,e){const t=e.slice(0,-1).length;let s=0;for(;s<t;)r=Z(r)?s++:r[e[s++]];return r}function Yr(r){for(const e in r)if(r.hasOwnProperty(e)&&!Z(r[e]))return!1;return!0}function $(r,e){const t=Array.isArray(e)?e:Mt(e)?[e]:_r(e),s=t.length===1?r:Jr(r,t),n=t.length-1,a=t[n];return s&&delete s[a],n!==0&&(j(s)&&X(s)||Array.isArray(s)&&Yr(s))&&$(r,t.slice(0,-1)),r}var wt=()=>{let r=[];return{get observers(){return r},next:n=>{for(const a of r)a.next&&a.next(n)},subscribe:n=>(r.push(n),{unsubscribe:()=>{r=r.filter(a=>a!==n)}}),unsubscribe:()=>{r=[]}}},Ct=r=>H(r)||!mr(r);function be(r,e){if(Ct(r)||Ct(e))return r===e;if(Ae(r)&&Ae(e))return r.getTime()===e.getTime();const t=Object.keys(r),s=Object.keys(e);if(t.length!==s.length)return!1;for(const n of t){const a=r[n];if(!s.includes(n))return!1;if(n!=="ref"){const i=e[n];if(Ae(a)&&Ae(i)||j(a)&&j(i)||Array.isArray(a)&&Array.isArray(i)?!be(a,i):a!==i)return!1}}return!0}var Sr=r=>r.type==="select-multiple",Gr=r=>Ut(r)||Ge(r),At=r=>tt(r)&&r.isConnected,Tr=r=>{for(const e in r)if(ie(r[e]))return!0;return!1};function st(r,e={}){const t=Array.isArray(r);if(j(r)||t)for(const s in r)Array.isArray(r[s])||j(r[s])&&!Tr(r[s])?(e[s]=Array.isArray(r[s])?[]:{},st(r[s],e[s])):H(r[s])||(e[s]=!0);return e}function Cr(r,e,t){const s=Array.isArray(r);if(j(r)||s)for(const n in r)Array.isArray(r[n])||j(r[n])&&!Tr(r[n])?Z(e)||Ct(t[n])?t[n]=Array.isArray(r[n])?st(r[n],[]):{...st(r[n])}:Cr(r[n],H(e)?{}:e[n],t[n]):t[n]=!be(r[n],e[n]);return t}var Le=(r,e)=>Cr(r,e,st(e)),Vr=(r,{valueAsNumber:e,valueAsDate:t,setValueAs:s})=>Z(r)?r:e?r===""?NaN:r&&+r:t&&ue(r)?new Date(r):s?s(r):r;function St(r){const e=r.ref;return $t(e)?e.files:Ut(e)?Ar(r.refs).value:Sr(e)?[...e.selectedOptions].map(({value:t})=>t):Ge(e)?wr(r.refs).value:Vr(Z(e.value)?r.ref.value:e.value,r)}var Xr=(r,e,t,s)=>{const n={};for(const a of r){const i=p(e,a);i&&F(n,a,i._f)}return{criteriaMode:t,names:[...r],fields:n,shouldUseNativeValidation:s}},Pe=r=>Z(r)?r:rt(r)?r.source:j(r)?rt(r.value)?r.value.source:r.value:r;const ur="AsyncFunction";var Qr=r=>!!r&&!!r.validate&&!!(ie(r.validate)&&r.validate.constructor.name===ur||j(r.validate)&&Object.values(r.validate).find(e=>e.constructor.name===ur)),Kr=r=>r.mount&&(r.required||r.min||r.max||r.maxLength||r.minLength||r.pattern||r.validate);function dr(r,e,t){const s=p(r,t);if(s||Mt(t))return{error:s,name:t};const n=t.split(".");for(;n.length;){const a=n.join("."),i=p(e,a),d=p(r,a);if(i&&!Array.isArray(i)&&t!==a)return{name:t};if(d&&d.type)return{name:a,error:d};n.pop()}return{name:t}}var es=(r,e,t,s,n)=>n.isOnAll?!1:!t&&n.isOnTouch?!(e||r):(t?s.isOnBlur:n.isOnBlur)?!r:(t?s.isOnChange:n.isOnChange)?r:!0,ts=(r,e)=>!_t(p(r,e)).length&&$(r,e);const rs={mode:ae.onSubmit,reValidateMode:ae.onChange,shouldFocusError:!0};function ss(r={}){let e={...rs,...r},t={submitCount:0,isDirty:!1,isLoading:ie(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},s={},n=j(e.defaultValues)||j(e.values)?G(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:G(n),i={action:!1,mount:!1,watch:!1},d={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,h=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},k={values:wt(),array:wt(),state:wt()},M=er(e.mode),Y=er(e.reValidateMode),z=e.criteriaMode===ae.all,q=u=>o=>{clearTimeout(h),h=setTimeout(u,o)},K=async u=>{if(!e.disabled&&(y.isValid||u)){const o=e.resolver?X((await we()).errors):await ee(s,!0);o!==t.isValid&&k.state.next({isValid:o})}},ge=(u,o)=>{!e.disabled&&(y.isValidating||y.validatingFields)&&((u||Array.from(d.mount)).forEach(l=>{l&&(o?F(t.validatingFields,l,o):$(t.validatingFields,l))}),k.state.next({validatingFields:t.validatingFields,isValidating:!X(t.validatingFields)}))},R=(u,o=[],l,v,_=!0,m=!0)=>{if(v&&l&&!e.disabled){if(i.action=!0,m&&Array.isArray(p(s,u))){const w=l(p(s,u),v.argA,v.argB);_&&F(s,u,w)}if(m&&Array.isArray(p(t.errors,u))){const w=l(p(t.errors,u),v.argA,v.argB);_&&F(t.errors,u,w),ts(t.errors,u)}if(y.touchedFields&&m&&Array.isArray(p(t.touchedFields,u))){const w=l(p(t.touchedFields,u),v.argA,v.argB);_&&F(t.touchedFields,u,w)}y.dirtyFields&&(t.dirtyFields=Le(n,a)),k.state.next({name:u,isDirty:E(u,o),dirtyFields:t.dirtyFields,errors:t.errors,isValid:t.isValid})}else F(a,u,o)},le=(u,o)=>{F(t.errors,u,o),k.state.next({errors:t.errors})},ce=u=>{t.errors=u,k.state.next({errors:t.errors,isValid:!1})},L=(u,o,l,v)=>{const _=p(s,u);if(_){const m=p(a,u,Z(l)?p(n,u):l);Z(m)||v&&v.defaultChecked||o?F(a,u,o?m:St(_._f)):W(u,m),i.mount&&K()}},Ce=(u,o,l,v,_)=>{let m=!1,w=!1;const C={name:u};if(!e.disabled){const U=!!(p(s,u)&&p(s,u)._f&&p(s,u)._f.disabled);if(!l||v){y.isDirty&&(w=t.isDirty,t.isDirty=C.isDirty=E(),m=w!==C.isDirty);const B=U||be(p(n,u),o);w=!!(!U&&p(t.dirtyFields,u)),B||U?$(t.dirtyFields,u):F(t.dirtyFields,u,!0),C.dirtyFields=t.dirtyFields,m=m||y.dirtyFields&&w!==!B}if(l){const B=p(t.touchedFields,u);B||(F(t.touchedFields,u,l),C.touchedFields=t.touchedFields,m=m||y.touchedFields&&B!==l)}m&&_&&k.state.next(C)}return m?C:{}},Xe=(u,o,l,v)=>{const _=p(t.errors,u),m=y.isValid&&re(o)&&t.isValid!==o;if(e.delayError&&l?(c=q(()=>le(u,l)),c(e.delayError)):(clearTimeout(h),c=null,l?F(t.errors,u,l):$(t.errors,u)),(l?!be(_,l):_)||!X(v)||m){const w={...v,...m&&re(o)?{isValid:o}:{},errors:t.errors,name:u};t={...t,...w},k.state.next(w)}},we=async u=>{ge(u,!0);const o=await e.resolver(a,e.context,Xr(u||d.mount,s,e.criteriaMode,e.shouldUseNativeValidation));return ge(u),o},Ve=async u=>{const{errors:o}=await we(u);if(u)for(const l of u){const v=p(o,l);v?F(t.errors,l,v):$(t.errors,l)}else t.errors=o;return o},ee=async(u,o,l={valid:!0})=>{for(const v in u){const _=u[v];if(_){const{_f:m,...w}=_;if(m){const C=d.array.has(m.name),U=_._f&&Qr(_._f);U&&y.validatingFields&&ge([v],!0);const B=await ir(_,d.disabled,a,z,e.shouldUseNativeValidation&&!o,C);if(U&&y.validatingFields&&ge([v]),B[m.name]&&(l.valid=!1,o))break;!o&&(p(B,m.name)?C?Hr(t.errors,B,m.name):F(t.errors,m.name,B[m.name]):$(t.errors,m.name))}!X(w)&&await ee(w,o,l)}}return l.valid},Qe=()=>{for(const u of d.unMount){const o=p(s,u);o&&(o._f.refs?o._f.refs.every(l=>!At(l)):!At(o._f.ref))&&vt(u)}d.unMount=new Set},E=(u,o)=>!e.disabled&&(u&&o&&F(a,u,o),!be(zt(),n)),N=(u,o,l)=>kr(u,d,{...i.mount?a:Z(o)?n:ue(u)?{[u]:o}:o},l,o),P=u=>_t(p(i.mount?a:n,u,e.shouldUnregister?p(n,u,[]):[])),W=(u,o,l={})=>{const v=p(s,u);let _=o;if(v){const m=v._f;m&&(!m.disabled&&F(a,u,Vr(o,m)),_=tt(m.ref)&&H(o)?"":o,Sr(m.ref)?[...m.ref.options].forEach(w=>w.selected=_.includes(w.value)):m.refs?Ge(m.ref)?m.refs.length>1?m.refs.forEach(w=>(!w.defaultChecked||!w.disabled)&&(w.checked=Array.isArray(_)?!!_.find(C=>C===w.value):_===w.value)):m.refs[0]&&(m.refs[0].checked=!!_):m.refs.forEach(w=>w.checked=w.value===_):$t(m.ref)?m.ref.value="":(m.ref.value=_,m.ref.type||k.values.next({name:u,values:{...a}})))}(l.shouldDirty||l.shouldTouch)&&Ce(u,_,l.shouldTouch,l.shouldDirty,!0),l.shouldValidate&&Me(u)},ne=(u,o,l)=>{for(const v in o){const _=o[v],m=`${u}.${v}`,w=p(s,m);(d.array.has(u)||j(_)||w&&!w._f)&&!Ae(_)?ne(m,_,l):W(m,_,l)}},te=(u,o,l={})=>{const v=p(s,u),_=d.array.has(u),m=G(o);F(a,u,m),_?(k.array.next({name:u,values:{...a}}),(y.isDirty||y.dirtyFields)&&l.shouldDirty&&k.state.next({name:u,dirtyFields:Le(n,a),isDirty:E(u,m)})):v&&!v._f&&!H(m)?ne(u,m,l):W(u,m,l),tr(u,d)&&k.state.next({...t}),k.values.next({name:i.mount?u:void 0,values:{...a}})},Ze=async u=>{i.mount=!0;const o=u.target;let l=o.name,v=!0;const _=p(s,l),m=()=>o.type?St(_._f):pr(u),w=C=>{v=Number.isNaN(C)||Ae(C)&&isNaN(C.getTime())||be(C,p(a,l,C))};if(_){let C,U;const B=m(),ve=u.type===et.BLUR||u.type===et.FOCUS_OUT,Mr=!Kr(_._f)&&!e.resolver&&!p(t.errors,l)&&!_._f.deps||es(ve,p(t.touchedFields,l),t.isSubmitted,Y,M),bt=tr(l,d,ve);F(a,l,B),ve?(_._f.onBlur&&_._f.onBlur(u),c&&c(0)):_._f.onChange&&_._f.onChange(u);const kt=Ce(l,B,ve,!1),Lr=!X(kt)||bt;if(!ve&&k.values.next({name:l,type:u.type,values:{...a}}),Mr)return y.isValid&&(e.mode==="onBlur"&&ve?K():ve||K()),Lr&&k.state.next({name:l,...bt?{}:kt});if(!ve&&bt&&k.state.next({...t}),e.resolver){const{errors:Qt}=await we([l]);if(w(B),v){const Pr=dr(t.errors,s,l),Kt=dr(Qt,s,Pr.name||l);C=Kt.error,l=Kt.name,U=X(Qt)}}else ge([l],!0),C=(await ir(_,d.disabled,a,z,e.shouldUseNativeValidation))[l],ge([l]),w(B),v&&(C?U=!1:y.isValid&&(U=await ee(s,!0)));v&&(_._f.deps&&Me(_._f.deps),Xe(l,U,C,kt))}},je=(u,o)=>{if(p(t.errors,o)&&u.focus)return u.focus(),1},Me=async(u,o={})=>{let l,v;const _=ze(u);if(e.resolver){const m=await Ve(Z(u)?u:_);l=X(m),v=u?!_.some(w=>p(m,w)):l}else u?(v=(await Promise.all(_.map(async m=>{const w=p(s,m);return await ee(w&&w._f?{[m]:w}:w)}))).every(Boolean),!(!v&&!t.isValid)&&K()):v=l=await ee(s);return k.state.next({...!ue(u)||y.isValid&&l!==t.isValid?{}:{name:u},...e.resolver||!u?{isValid:l}:{},errors:t.errors}),o.shouldFocus&&!v&&We(s,je,u?_:d.mount),v},zt=u=>{const o={...i.mount?a:n};return Z(u)?o:ue(u)?p(o,u):u.map(l=>p(o,l))},Wt=(u,o)=>({invalid:!!p((o||t).errors,u),isDirty:!!p((o||t).dirtyFields,u),error:p((o||t).errors,u),isValidating:!!p(t.validatingFields,u),isTouched:!!p((o||t).touchedFields,u)}),Ir=u=>{u&&ze(u).forEach(o=>$(t.errors,o)),k.state.next({errors:u?t.errors:{}})},qt=(u,o,l)=>{const v=(p(s,u,{_f:{}})._f||{}).ref,_=p(t.errors,u)||{},{ref:m,message:w,type:C,...U}=_;F(t.errors,u,{...U,...o,ref:v}),k.state.next({name:u,errors:t.errors,isValid:!1}),l&&l.shouldFocus&&v&&v.focus&&v.focus()},Dr=(u,o)=>ie(u)?k.values.subscribe({next:l=>u(N(void 0,o),l)}):N(u,o,!0),vt=(u,o={})=>{for(const l of u?ze(u):d.mount)d.mount.delete(l),d.array.delete(l),o.keepValue||($(s,l),$(a,l)),!o.keepError&&$(t.errors,l),!o.keepDirty&&$(t.dirtyFields,l),!o.keepTouched&&$(t.touchedFields,l),!o.keepIsValidating&&$(t.validatingFields,l),!e.shouldUnregister&&!o.keepDefaultValue&&$(n,l);k.values.next({values:{...a}}),k.state.next({...t,...o.keepDirty?{isDirty:E()}:{}}),!o.keepIsValid&&K()},Ht=({disabled:u,name:o,field:l,fields:v})=>{(re(u)&&i.mount||u||d.disabled.has(o))&&(u?d.disabled.add(o):d.disabled.delete(o),Ce(o,St(l?l._f:p(v,o)._f),!1,!1,!0))},xt=(u,o={})=>{let l=p(s,u);const v=re(o.disabled)||re(e.disabled);return F(s,u,{...l||{},_f:{...l&&l._f?l._f:{ref:{name:u}},name:u,mount:!0,...o}}),d.mount.add(u),l?Ht({field:l,disabled:re(o.disabled)?o.disabled:e.disabled,name:u}):L(u,!0,o.value),{...v?{disabled:o.disabled||e.disabled}:{},...e.progressive?{required:!!o.required,min:Pe(o.min),max:Pe(o.max),minLength:Pe(o.minLength),maxLength:Pe(o.maxLength),pattern:Pe(o.pattern)}:{},name:u,onChange:Ze,onBlur:Ze,ref:_=>{if(_){xt(u,o),l=p(s,u);const m=Z(_.value)&&_.querySelectorAll&&_.querySelectorAll("input,select,textarea")[0]||_,w=Gr(m),C=l._f.refs||[];if(w?C.find(U=>U===m):m===l._f.ref)return;F(s,u,{_f:{...l._f,...w?{refs:[...C.filter(At),m,...Array.isArray(p(n,u))?[{}]:[]],ref:{type:m.type,name:u}}:{ref:m}}}),L(u,!1,void 0,m)}else l=p(s,u,{}),l._f&&(l._f.mount=!1),(e.shouldUnregister||o.shouldUnregister)&&!(yr(d.array,u)&&i.action)&&d.unMount.add(u)}}},Jt=()=>e.shouldFocusError&&We(s,je,d.mount),Zr=u=>{re(u)&&(k.state.next({disabled:u}),We(s,(o,l)=>{const v=p(s,l);v&&(o.disabled=v._f.disabled||u,Array.isArray(v._f.refs)&&v._f.refs.forEach(_=>{_.disabled=v._f.disabled||u}))},0,!1))},Yt=(u,o)=>async l=>{let v;l&&(l.preventDefault&&l.preventDefault(),l.persist&&l.persist());let _=G(a);if(d.disabled.size)for(const m of d.disabled)F(_,m,void 0);if(k.state.next({isSubmitting:!0}),e.resolver){const{errors:m,values:w}=await we();t.errors=m,_=w}else await ee(s);if($(t.errors,"root"),X(t.errors)){k.state.next({errors:{}});try{await u(_,l)}catch(m){v=m}}else o&&await o({...t.errors},l),Jt(),setTimeout(Jt);if(k.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:X(t.errors)&&!v,submitCount:t.submitCount+1,errors:t.errors}),v)throw v},jr=(u,o={})=>{p(s,u)&&(Z(o.defaultValue)?te(u,G(p(n,u))):(te(u,o.defaultValue),F(n,u,G(o.defaultValue))),o.keepTouched||$(t.touchedFields,u),o.keepDirty||($(t.dirtyFields,u),t.isDirty=o.defaultValue?E(u,G(p(n,u))):E()),o.keepError||($(t.errors,u),y.isValid&&K()),k.state.next({...t}))},Gt=(u,o={})=>{const l=u?G(u):n,v=G(l),_=X(u),m=_?n:v;if(o.keepDefaultValues||(n=l),!o.keepValues){if(o.keepDirtyValues){const w=new Set([...d.mount,...Object.keys(Le(n,a))]);for(const C of Array.from(w))p(t.dirtyFields,C)?F(m,C,p(a,C)):te(C,p(m,C))}else{if(jt&&Z(u))for(const w of d.mount){const C=p(s,w);if(C&&C._f){const U=Array.isArray(C._f.refs)?C._f.refs[0]:C._f.ref;if(tt(U)){const B=U.closest("form");if(B){B.reset();break}}}}s={}}a=e.shouldUnregister?o.keepDefaultValues?G(n):{}:G(m),k.array.next({values:{...m}}),k.values.next({values:{...m}})}d={mount:o.keepDirtyValues?d.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},i.mount=!y.isValid||!!o.keepIsValid||!!o.keepDirtyValues,i.watch=!!e.shouldUnregister,k.state.next({submitCount:o.keepSubmitCount?t.submitCount:0,isDirty:_?!1:o.keepDirty?t.isDirty:!!(o.keepDefaultValues&&!be(u,n)),isSubmitted:o.keepIsSubmitted?t.isSubmitted:!1,dirtyFields:_?{}:o.keepDirtyValues?o.keepDefaultValues&&a?Le(n,a):t.dirtyFields:o.keepDefaultValues&&u?Le(n,u):o.keepDirty?t.dirtyFields:{},touchedFields:o.keepTouched?t.touchedFields:{},errors:o.keepErrors?t.errors:{},isSubmitSuccessful:o.keepIsSubmitSuccessful?t.isSubmitSuccessful:!1,isSubmitting:!1})},Xt=(u,o)=>Gt(ie(u)?u(a):u,o);return{control:{register:xt,unregister:vt,getFieldState:Wt,handleSubmit:Yt,setError:qt,_executeSchema:we,_getWatch:N,_getDirty:E,_updateValid:K,_removeUnmounted:Qe,_updateFieldArray:R,_updateDisabledField:Ht,_getFieldArray:P,_reset:Gt,_resetDefaultValues:()=>ie(e.defaultValues)&&e.defaultValues().then(u=>{Xt(u,e.resetOptions),k.state.next({isLoading:!1})}),_updateFormState:u=>{t={...t,...u}},_disableForm:Zr,_subjects:k,_proxyFormState:y,_setErrors:ce,get _fields(){return s},get _formValues(){return a},get _state(){return i},set _state(u){i=u},get _defaultValues(){return n},get _names(){return d},set _names(u){d=u},get _formState(){return t},set _formState(u){t=u},get _options(){return e},set _options(u){e={...e,...u}}},trigger:Me,register:xt,handleSubmit:Yt,watch:Dr,setValue:te,getValues:zt,reset:Xt,resetField:jr,clearErrors:Ir,unregister:vt,setError:qt,setFocus:(u,o={})=>{const l=p(s,u),v=l&&l._f;if(v){const _=v.refs?v.refs[0]:v.ref;_.focus&&(_.focus(),o.shouldSelect&&ie(_.select)&&_.select())}},getFieldState:Wt}}function Ds(r={}){const e=I.useRef(void 0),t=I.useRef(void 0),[s,n]=I.useState({isDirty:!1,isValidating:!1,isLoading:ie(r.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:r.errors||{},disabled:r.disabled||!1,defaultValues:ie(r.defaultValues)?void 0:r.defaultValues});e.current||(e.current={...ss(r),formState:s});const a=e.current.control;return a._options=r,Pt({subject:a._subjects.state,next:i=>{xr(i,a._proxyFormState,a._updateFormState,!0)&&n({...a._formState})}}),I.useEffect(()=>a._disableForm(r.disabled),[a,r.disabled]),I.useEffect(()=>{if(a._proxyFormState.isDirty){const i=a._getDirty();i!==s.isDirty&&a._subjects.state.next({isDirty:i})}},[a,s.isDirty]),I.useEffect(()=>{r.values&&!be(r.values,t.current)?(a._reset(r.values,a._options.resetOptions),t.current=r.values,n(i=>({...i}))):a._resetDefaultValues()},[r.values,a]),I.useEffect(()=>{r.errors&&a._setErrors(r.errors)},[r.errors,a]),I.useEffect(()=>{a._state.mount||(a._updateValid(),a._state.mount=!0),a._state.watch&&(a._state.watch=!1,a._subjects.state.next({...a._formState})),a._removeUnmounted()}),I.useEffect(()=>{r.shouldUnregister&&a._subjects.values.next({values:a._getWatch()})},[r.shouldUnregister,a]),e.current.formState=vr(s,a),e.current}const or=(r,e,t)=>{if(r&&"reportValidity"in r){const s=p(t,e);r.setCustomValidity(s&&s.message||""),r.reportValidity()}},ns=(r,e)=>{for(const t in e.fields){const s=e.fields[t];s&&s.ref&&"reportValidity"in s.ref?or(s.ref,t,r):s.refs&&s.refs.forEach(n=>or(n,t,r))}},Zs=(r,e)=>{e.shouldUseNativeValidation&&ns(r,e);const t={};for(const s in r){const n=p(e.fields,s),a=Object.assign(r[s]||{},{ref:n&&n.ref});if(as(e.names||Object.keys(r),s)){const i=Object.assign({},p(t,s));F(i,"root",a),F(t,s,i)}else F(t,s,a)}return t},as=(r,e)=>r.some(t=>t.startsWith(e+"."));var O;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(d=>typeof n[n[d]]!="number"),i={};for(const d of a)i[d]=n[d];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(O||(O={}));var lr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(lr||(lr={}));const x=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xe=r=>{switch(typeof r){case"undefined":return x.undefined;case"string":return x.string;case"number":return isNaN(r)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":return Array.isArray(r)?x.array:r===null?x.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?x.promise:typeof Map<"u"&&r instanceof Map?x.map:typeof Set<"u"&&r instanceof Set?x.set:typeof Date<"u"&&r instanceof Date?x.date:x.object;default:return x.unknown}},f=O.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class se extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let d=s,c=0;for(;c<i.path.length;){const h=i.path[c];c===i.path.length-1?(d[h]=d[h]||{_errors:[]},d[h]._errors.push(t(i))):d[h]=d[h]||{_errors:[]},d=d[h],c++}}};return n(this),s}static assert(e){if(!(e instanceof se))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}se.create=r=>new se(r);const He=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===x.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,O.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${O.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${O.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${O.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:O.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,O.assertNever(r)}return{message:t}};let is=He;function Vt(){return is}const Et=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let d="";const c=s.filter(h=>!!h).slice().reverse();for(const h of c)d=h(i,{data:e,defaultError:d}).message;return{...n,path:a,message:d}};function g(r,e){const t=Vt(),s=Et({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===He?void 0:He].filter(n=>!!n)});r.common.issues.push(s)}class J{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return S;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return J.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return S;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const S=Object.freeze({status:"aborted"}),$e=r=>({status:"dirty",value:r}),Q=r=>({status:"valid",value:r}),cr=r=>r.status==="aborted",fr=r=>r.status==="dirty",Ne=r=>r.status==="valid",nt=r=>typeof Promise<"u"&&r instanceof Promise;function at(r,e,t,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Er(r,e,t,s,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var b;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var Ue,Be;class oe{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const hr=(r,e)=>{if(Ne(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new se(r.common.issues);return this._error=t,this._error}}};function T(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,d)=>{var c,h;const{message:y}=r;return i.code==="invalid_enum_value"?{message:y??d.defaultError}:typeof d.data>"u"?{message:(c=y??s)!==null&&c!==void 0?c:d.defaultError}:i.code!=="invalid_type"?{message:d.defaultError}:{message:(h=y??t)!==null&&h!==void 0?h:d.defaultError}},description:n}}class V{get description(){return this._def.description}_getType(e){return xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new J,ctx:{common:e.parent.common,data:e.data,parsedType:xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(nt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const n={common:{issues:[],async:(s=t==null?void 0:t.async)!==null&&s!==void 0?s:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xe(e)},a=this._parseSync({data:e,path:n.path,parent:n});return hr(n,a)}"~validate"(e){var t,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xe(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return Ne(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a==null?void 0:a.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>Ne(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xe(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(nt(n)?n:Promise.resolve(n));return hr(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),d=()=>a.addIssue({code:f.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(d(),!1)):i?!0:(d(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new _e({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return pe.create(this,this._def)}nullable(){return Te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return de.create(this)}promise(){return Ye.create(this,this._def)}or(e){return dt.create([this,e],this._def)}and(e){return ot.create(this,e,this._def)}transform(e){return new _e({...T(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new mt({...T(this._def),innerType:this,defaultValue:t,typeName:A.ZodDefault})}brand(){return new Fr({typeName:A.ZodBranded,type:this,...T(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new pt({...T(this._def),innerType:this,catchValue:t,typeName:A.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return gt.create(this,e)}readonly(){return yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const us=/^c[^\s-]{8,}$/i,ds=/^[0-9a-z]+$/,os=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ls=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,cs=/^[a-z0-9_-]{21}$/i,fs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hs=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ms=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ps="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Tt;const ys=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_s=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,gs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,vs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Or="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ks=new RegExp(`^${Or}$`);function Rr(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ws(r){return new RegExp(`^${Rr(r)}$`)}function As(r){let e=`${Or}T${Rr(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ss(r,e){return!!((e==="v4"||!e)&&ys.test(r)||(e==="v6"||!e)&&gs.test(r))}function Ts(r,e){if(!fs.test(r))return!1;try{const[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Cs(r,e){return!!((e==="v4"||!e)&&_s.test(r)||(e==="v6"||!e)&&vs.test(r))}class me extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==x.string){const a=this._getOrReturnCtx(e);return g(a,{code:f.invalid_type,expected:x.string,received:a.parsedType}),S}const s=new J;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,d=e.data.length<a.value;(i||d)&&(n=this._getOrReturnCtx(e,n),i?g(n,{code:f.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):d&&g(n,{code:f.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")ms.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"email",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")Tt||(Tt=new RegExp(ps,"u")),Tt.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"emoji",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")ls.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"uuid",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")cs.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"nanoid",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")us.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"cuid",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")ds.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"cuid2",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")os.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"ulid",code:f.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),g(n,{validation:"url",code:f.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"regex",code:f.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?As(a).test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?ks.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?ws(a).test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?hs.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"duration",code:f.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Ss(e.data,a.version)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"ip",code:f.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Ts(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"jwt",code:f.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Cs(e.data,a.version)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"cidr",code:f.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?xs.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"base64",code:f.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?bs.test(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{validation:"base64url",code:f.invalid_string,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:f.invalid_string,...b.errToObj(s)})}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...b.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...b.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(s=e==null?void 0:e.local)!==null&&s!==void 0?s:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...b.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new me({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new me({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new me({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}me.create=r=>{var e;return new me({checks:[],typeName:A.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...T(r)})};function Vs(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=parseInt(r.toFixed(n).replace(".","")),i=parseInt(e.toFixed(n).replace(".",""));return a%i/Math.pow(10,n)}class Fe extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==x.number){const a=this._getOrReturnCtx(e);return g(a,{code:f.invalid_type,expected:x.number,received:a.parsedType}),S}let s;const n=new J;for(const a of this._def.checks)a.kind==="int"?O.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),g(s,{code:f.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?Vs(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),g(s,{code:f.not_finite,message:a.message}),n.dirty()):O.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,s,n){return new Fe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:b.toString(n)}]})}_addCheck(e){return new Fe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&O.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Fe.create=r=>new Fe({checks:[],typeName:A.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...T(r)});class Ie extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==x.bigint)return this._getInvalidInput(e);let s;const n=new J;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),g(s,{code:f.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):O.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return g(t,{code:f.invalid_type,expected:x.bigint,received:t.parsedType}),S}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,s,n){return new Ie({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:b.toString(n)}]})}_addCheck(e){return new Ie({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ie.create=r=>{var e;return new Ie({checks:[],typeName:A.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...T(r)})};class Ot extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==x.boolean){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.boolean,received:s.parsedType}),S}return Q(e.data)}}Ot.create=r=>new Ot({typeName:A.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...T(r)});class Je extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==x.date){const a=this._getOrReturnCtx(e);return g(a,{code:f.invalid_type,expected:x.date,received:a.parsedType}),S}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return g(a,{code:f.invalid_date}),S}const s=new J;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):O.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Je({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Je.create=r=>new Je({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:A.ZodDate,...T(r)});class Rt extends V{_parse(e){if(this._getType(e)!==x.symbol){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.symbol,received:s.parsedType}),S}return Q(e.data)}}Rt.create=r=>new Rt({typeName:A.ZodSymbol,...T(r)});class it extends V{_parse(e){if(this._getType(e)!==x.undefined){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.undefined,received:s.parsedType}),S}return Q(e.data)}}it.create=r=>new it({typeName:A.ZodUndefined,...T(r)});class ut extends V{_parse(e){if(this._getType(e)!==x.null){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.null,received:s.parsedType}),S}return Q(e.data)}}ut.create=r=>new ut({typeName:A.ZodNull,...T(r)});class Nt extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}}Nt.create=r=>new Nt({typeName:A.ZodAny,...T(r)});class Re extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}}Re.create=r=>new Re({typeName:A.ZodUnknown,...T(r)});class ke extends V{_parse(e){const t=this._getOrReturnCtx(e);return g(t,{code:f.invalid_type,expected:x.never,received:t.parsedType}),S}}ke.create=r=>new ke({typeName:A.ZodNever,...T(r)});class Ft extends V{_parse(e){if(this._getType(e)!==x.undefined){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.void,received:s.parsedType}),S}return Q(e.data)}}Ft.create=r=>new Ft({typeName:A.ZodVoid,...T(r)});class de extends V{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==x.array)return g(t,{code:f.invalid_type,expected:x.array,received:t.parsedType}),S;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,d=t.data.length<n.exactLength.value;(i||d)&&(g(t,{code:i?f.too_big:f.too_small,minimum:d?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(g(t,{code:f.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(g(t,{code:f.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,d)=>n.type._parseAsync(new oe(t,i,t.path,d)))).then(i=>J.mergeArray(s,i));const a=[...t.data].map((i,d)=>n.type._parseSync(new oe(t,i,t.path,d)));return J.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new de({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new de({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new de({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}de.create=(r,e)=>new de({type:r,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...T(e)});function Oe(r){if(r instanceof D){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=pe.create(Oe(s))}return new D({...r._def,shape:()=>e})}else return r instanceof de?new de({...r._def,type:Oe(r.element)}):r instanceof pe?pe.create(Oe(r.unwrap())):r instanceof Te?Te.create(Oe(r.unwrap())):r instanceof ye?ye.create(r.items.map(e=>Oe(e))):r}class D extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=O.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==x.object){const h=this._getOrReturnCtx(e);return g(h,{code:f.invalid_type,expected:x.object,received:h.parsedType}),S}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),d=[];if(!(this._def.catchall instanceof ke&&this._def.unknownKeys==="strip"))for(const h in n.data)i.includes(h)||d.push(h);const c=[];for(const h of i){const y=a[h],k=n.data[h];c.push({key:{status:"valid",value:h},value:y._parse(new oe(n,k,n.path,h)),alwaysSet:h in n.data})}if(this._def.catchall instanceof ke){const h=this._def.unknownKeys;if(h==="passthrough")for(const y of d)c.push({key:{status:"valid",value:y},value:{status:"valid",value:n.data[y]}});else if(h==="strict")d.length>0&&(g(n,{code:f.unrecognized_keys,keys:d}),s.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const h=this._def.catchall;for(const y of d){const k=n.data[y];c.push({key:{status:"valid",value:y},value:h._parse(new oe(n,k,n.path,y)),alwaysSet:y in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const h=[];for(const y of c){const k=await y.key,M=await y.value;h.push({key:k,value:M,alwaysSet:y.alwaysSet})}return h}).then(h=>J.mergeObjectSync(s,h)):J.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new D({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,d;const c=(i=(a=(n=this._def).errorMap)===null||a===void 0?void 0:a.call(n,t,s).message)!==null&&i!==void 0?i:s.defaultError;return t.code==="unrecognized_keys"?{message:(d=b.errToObj(e).message)!==null&&d!==void 0?d:c}:{message:c}}}:{}})}strip(){return new D({...this._def,unknownKeys:"strip"})}passthrough(){return new D({...this._def,unknownKeys:"passthrough"})}extend(e){return new D({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new D({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new D({...this._def,catchall:e})}pick(e){const t={};return O.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(t[s]=this.shape[s])}),new D({...this._def,shape:()=>t})}omit(e){const t={};return O.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s])}),new D({...this._def,shape:()=>t})}deepPartial(){return Oe(this)}partial(e){const t={};return O.objectKeys(this.shape).forEach(s=>{const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}),new D({...this._def,shape:()=>t})}required(e){const t={};return O.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof pe;)a=a._def.innerType;t[s]=a}}),new D({...this._def,shape:()=>t})}keyof(){return Nr(O.objectKeys(this.shape))}}D.create=(r,e)=>new D({shape:()=>r,unknownKeys:"strip",catchall:ke.create(),typeName:A.ZodObject,...T(e)});D.strictCreate=(r,e)=>new D({shape:()=>r,unknownKeys:"strict",catchall:ke.create(),typeName:A.ZodObject,...T(e)});D.lazycreate=(r,e)=>new D({shape:r,unknownKeys:"strip",catchall:ke.create(),typeName:A.ZodObject,...T(e)});class dt extends V{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const d of a)if(d.result.status==="valid")return d.result;for(const d of a)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const i=a.map(d=>new se(d.ctx.common.issues));return g(t,{code:f.invalid_union,unionErrors:i}),S}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const c of s){const h={...t,common:{...t.common,issues:[]},parent:null},y=c._parseSync({data:t.data,path:t.path,parent:h});if(y.status==="valid")return y;y.status==="dirty"&&!a&&(a={result:y,ctx:h}),h.common.issues.length&&i.push(h.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const d=i.map(c=>new se(c));return g(t,{code:f.invalid_union,unionErrors:d}),S}}get options(){return this._def.options}}dt.create=(r,e)=>new dt({options:r,typeName:A.ZodUnion,...T(e)});const he=r=>r instanceof ct?he(r.schema):r instanceof _e?he(r.innerType()):r instanceof ft?[r.value]:r instanceof Se?r.options:r instanceof ht?O.objectValues(r.enum):r instanceof mt?he(r._def.innerType):r instanceof it?[void 0]:r instanceof ut?[null]:r instanceof pe?[void 0,...he(r.unwrap())]:r instanceof Te?[null,...he(r.unwrap())]:r instanceof Fr||r instanceof yt?he(r.unwrap()):r instanceof pt?he(r._def.innerType):[];class Bt extends V{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==x.object)return g(t,{code:f.invalid_type,expected:x.object,received:t.parsedType}),S;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=he(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of i){if(n.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);n.set(d,a)}}return new Bt({typeName:A.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...T(s)})}}function It(r,e){const t=xe(r),s=xe(e);if(r===e)return{valid:!0,data:r};if(t===x.object&&s===x.object){const n=O.objectKeys(e),a=O.objectKeys(r).filter(d=>n.indexOf(d)!==-1),i={...r,...e};for(const d of a){const c=It(r[d],e[d]);if(!c.valid)return{valid:!1};i[d]=c.data}return{valid:!0,data:i}}else if(t===x.array&&s===x.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<r.length;a++){const i=r[a],d=e[a],c=It(i,d);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return t===x.date&&s===x.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ot extends V{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(cr(a)||cr(i))return S;const d=It(a.value,i.value);return d.valid?((fr(a)||fr(i))&&t.dirty(),{status:t.value,value:d.data}):(g(s,{code:f.invalid_intersection_types}),S)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}ot.create=(r,e,t)=>new ot({left:r,right:e,typeName:A.ZodIntersection,...T(t)});class ye extends V{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==x.array)return g(s,{code:f.invalid_type,expected:x.array,received:s.parsedType}),S;if(s.data.length<this._def.items.length)return g(s,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&s.data.length>this._def.items.length&&(g(s,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,d)=>{const c=this._def.items[d]||this._def.rest;return c?c._parse(new oe(s,i,s.path,d)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>J.mergeArray(t,i)):J.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ye({...this._def,rest:e})}}ye.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ye({items:r,typeName:A.ZodTuple,rest:null,...T(e)})};class lt extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==x.object)return g(s,{code:f.invalid_type,expected:x.object,received:s.parsedType}),S;const n=[],a=this._def.keyType,i=this._def.valueType;for(const d in s.data)n.push({key:a._parse(new oe(s,d,s.path,d)),value:i._parse(new oe(s,s.data[d],s.path,d)),alwaysSet:d in s.data});return s.common.async?J.mergeObjectAsync(t,n):J.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof V?new lt({keyType:e,valueType:t,typeName:A.ZodRecord,...T(s)}):new lt({keyType:me.create(),valueType:e,typeName:A.ZodRecord,...T(t)})}}class Dt extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==x.map)return g(s,{code:f.invalid_type,expected:x.map,received:s.parsedType}),S;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([d,c],h)=>({key:n._parse(new oe(s,d,s.path,[h,"key"])),value:a._parse(new oe(s,c,s.path,[h,"value"]))}));if(s.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const c of i){const h=await c.key,y=await c.value;if(h.status==="aborted"||y.status==="aborted")return S;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),d.set(h.value,y.value)}return{status:t.value,value:d}})}else{const d=new Map;for(const c of i){const h=c.key,y=c.value;if(h.status==="aborted"||y.status==="aborted")return S;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),d.set(h.value,y.value)}return{status:t.value,value:d}}}}Dt.create=(r,e,t)=>new Dt({valueType:e,keyType:r,typeName:A.ZodMap,...T(t)});class De extends V{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==x.set)return g(s,{code:f.invalid_type,expected:x.set,received:s.parsedType}),S;const n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(g(s,{code:f.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(g(s,{code:f.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(c){const h=new Set;for(const y of c){if(y.status==="aborted")return S;y.status==="dirty"&&t.dirty(),h.add(y.value)}return{status:t.value,value:h}}const d=[...s.data.values()].map((c,h)=>a._parse(new oe(s,c,s.path,h)));return s.common.async?Promise.all(d).then(c=>i(c)):i(d)}min(e,t){return new De({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new De({...this._def,maxSize:{value:e,message:b.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}De.create=(r,e)=>new De({valueType:r,minSize:null,maxSize:null,typeName:A.ZodSet,...T(e)});class qe extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==x.function)return g(t,{code:f.invalid_type,expected:x.function,received:t.parsedType}),S;function s(d,c){return Et({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Vt(),He].filter(h=>!!h),issueData:{code:f.invalid_arguments,argumentsError:c}})}function n(d,c){return Et({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Vt(),He].filter(h=>!!h),issueData:{code:f.invalid_return_type,returnTypeError:c}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Ye){const d=this;return Q(async function(...c){const h=new se([]),y=await d._def.args.parseAsync(c,a).catch(Y=>{throw h.addIssue(s(c,Y)),h}),k=await Reflect.apply(i,this,y);return await d._def.returns._def.type.parseAsync(k,a).catch(Y=>{throw h.addIssue(n(k,Y)),h})})}else{const d=this;return Q(function(...c){const h=d._def.args.safeParse(c,a);if(!h.success)throw new se([s(c,h.error)]);const y=Reflect.apply(i,this,h.data),k=d._def.returns.safeParse(y,a);if(!k.success)throw new se([n(y,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new qe({...this._def,args:ye.create(e).rest(Re.create())})}returns(e){return new qe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new qe({args:e||ye.create([]).rest(Re.create()),returns:t||Re.create(),typeName:A.ZodFunction,...T(s)})}}class ct extends V{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ct.create=(r,e)=>new ct({getter:r,typeName:A.ZodLazy,...T(e)});class ft extends V{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}ft.create=(r,e)=>new ft({value:r,typeName:A.ZodLiteral,...T(e)});function Nr(r,e){return new Se({values:r,typeName:A.ZodEnum,...T(e)})}class Se extends V{constructor(){super(...arguments),Ue.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return g(t,{expected:O.joinValues(s),received:t.parsedType,code:f.invalid_type}),S}if(at(this,Ue)||Er(this,Ue,new Set(this._def.values)),!at(this,Ue).has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return g(t,{received:t.data,code:f.invalid_enum_value,options:s}),S}return Q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Se.create(e,{...this._def,...t})}exclude(e,t=this._def){return Se.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}Ue=new WeakMap;Se.create=Nr;class ht extends V{constructor(){super(...arguments),Be.set(this,void 0)}_parse(e){const t=O.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==x.string&&s.parsedType!==x.number){const n=O.objectValues(t);return g(s,{expected:O.joinValues(n),received:s.parsedType,code:f.invalid_type}),S}if(at(this,Be)||Er(this,Be,new Set(O.getValidEnumValues(this._def.values))),!at(this,Be).has(e.data)){const n=O.objectValues(t);return g(s,{received:s.data,code:f.invalid_enum_value,options:n}),S}return Q(e.data)}get enum(){return this._def.values}}Be=new WeakMap;ht.create=(r,e)=>new ht({values:r,typeName:A.ZodNativeEnum,...T(e)});class Ye extends V{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==x.promise&&t.common.async===!1)return g(t,{code:f.invalid_type,expected:x.promise,received:t.parsedType}),S;const s=t.parsedType===x.promise?t.data:Promise.resolve(t.data);return Q(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ye.create=(r,e)=>new Ye({type:r,typeName:A.ZodPromise,...T(e)});class _e extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{g(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async d=>{if(t.value==="aborted")return S;const c=await this._def.schema._parseAsync({data:d,path:s.path,parent:s});return c.status==="aborted"?S:c.status==="dirty"||t.value==="dirty"?$e(c.value):c});{if(t.value==="aborted")return S;const d=this._def.schema._parseSync({data:i,path:s.path,parent:s});return d.status==="aborted"?S:d.status==="dirty"||t.value==="dirty"?$e(d.value):d}}if(n.type==="refinement"){const i=d=>{const c=n.refinement(d,a);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(s.common.async===!1){const d=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return d.status==="aborted"?S:(d.status==="dirty"&&t.dirty(),i(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(d=>d.status==="aborted"?S:(d.status==="dirty"&&t.dirty(),i(d.value).then(()=>({status:t.value,value:d.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Ne(i))return i;const d=n.transform(i.value,a);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:d}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>Ne(i)?Promise.resolve(n.transform(i.value,a)).then(d=>({status:t.value,value:d})):i);O.assertNever(n)}}_e.create=(r,e,t)=>new _e({schema:r,typeName:A.ZodEffects,effect:e,...T(t)});_e.createWithPreprocess=(r,e,t)=>new _e({schema:e,effect:{type:"preprocess",transform:r},typeName:A.ZodEffects,...T(t)});class pe extends V{_parse(e){return this._getType(e)===x.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(r,e)=>new pe({innerType:r,typeName:A.ZodOptional,...T(e)});class Te extends V{_parse(e){return this._getType(e)===x.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(r,e)=>new Te({innerType:r,typeName:A.ZodNullable,...T(e)});class mt extends V{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===x.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}mt.create=(r,e)=>new mt({innerType:r,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...T(e)});class pt extends V{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return nt(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new se(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new se(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}pt.create=(r,e)=>new pt({innerType:r,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...T(e)});class Zt extends V{_parse(e){if(this._getType(e)!==x.nan){const s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:x.nan,received:s.parsedType}),S}return{status:"valid",value:e.data}}}Zt.create=r=>new Zt({typeName:A.ZodNaN,...T(r)});class Fr extends V{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class gt extends V{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?S:a.status==="dirty"?(t.dirty(),$e(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?S:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new gt({in:e,out:t,typeName:A.ZodPipeline})}}class yt extends V{_parse(e){const t=this._def.innerType._parse(e),s=n=>(Ne(n)&&(n.value=Object.freeze(n.value)),n);return nt(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}yt.create=(r,e)=>new yt({innerType:r,typeName:A.ZodReadonly,...T(e)});D.lazycreate;var A;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(A||(A={}));const js=me.create;Fe.create;Zt.create;Ie.create;Ot.create;const Ms=Je.create;Rt.create;it.create;ut.create;Nt.create;Re.create;ke.create;Ft.create;de.create;const Ls=D.create;D.strictCreate;dt.create;Bt.create;ot.create;ye.create;lt.create;Dt.create;De.create;qe.create;ct.create;ft.create;Se.create;ht.create;Ye.create;_e.create;pe.create;Te.create;_e.createWithPreprocess;gt.create;export{Is as C,Fs as F,qr as a,Ls as b,Ds as c,Ms as d,ns as o,Zs as r,js as s,Lt as u}; diff --git a/pkg/ui/frontend/dist/assets/index-DqJzRHuy.js b/pkg/ui/frontend/dist/assets/index-DqJzRHuy.js new file mode 100644 index 0000000000000..0d9ab4e529c17 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/index-DqJzRHuy.js @@ -0,0 +1,63 @@ +import{j as e,S as Se,c as hr,P as re,e as Me,B as uo,E as xr,G as po,T as mo,H as go,I as br,J as fo,K as ho,L as xo,M as yr,u as vr,N as bo,V as jr,a as yo,g as vo,b as jt,d as pe,O as jo,n as wo,p as No,m as ko}from"./radix-core-ByqQ8fsu.js";import{c as wr,r as i,b as Be}from"./react-core-D_V7s-9r.js";import{u as It,a as at,L as ce,b as Nr,c as So,d as Eo,R as Co,e as To,f as Ro,g as Ao}from"./react-router-Bj-soKrx.js";import{t as _o,c as ys,a as Ee}from"./ui-utils-BNSC_Jv-.js";import{S as Io,M as Fo,C as kr,R as Lo,H as Po,a as qe,b as Do,A as Ws,c as ls,d as Sr,e as Ft,X as vs,f as Er,P as Oo,L as he,g as nt,h as Cr,i as $o,j as Mo,k as ot,l as Tr,F as Bo,m as zo,D as Rr,n as Ar,o as Vo,G as js,p as Uo,q as qo,r as Go,s as Ho,t as Ko,U as Wo,u as Zo,B as Yo}from"./ui-icons-CFVjIJRk.js";import{f as Xo,a as Qo,b as _r,c as wt,p as cs,i as Ze,d as Jo,e as Zs,g as ei,h as ti,D as Ys}from"./date-utils-B6syNIuD.js";import{R as Ir,I as si,T as Fr,a as ri,S as Lr,b as Pr,P as ai,C as Dr,V as ni,L as Or,c as $r,d as oi,e as ii,f as Mr,g as li,h as ci,i as Br,j as di,k as zr,l as Vr,m as Ur}from"./radix-inputs-D4_OLmm6.js";import{S as qr,d as Gr,P as ui,C as Hr,e as Kr,f as Wr,g as Zr,h as Yr,L as Xr,i as Qr,j as pi,T as mi,k as Jr,V as gi,l as fi,m as ea,n as hi,o as ta,p as sa,q as ra,r as xi,c as bi}from"./radix-navigation-DYoR-lWZ.js";import{R as ws,P as Ns,O as it,C as lt,a as aa,T as Lt,D as Pt,b as na,c as yi,d as vi,e as ji,f as wi,g as Ni,h as oa}from"./radix-layout-BqTpm3s4.js";import{R as ct,P as Dt,a as Ot,C as $t,T as dt,d as ki,B as Si,b as Ei,Y as Ci,X as Ti,c as Ri}from"./data-viz-BuFFX-vG.js";import{u as Mt,a as Ai,Q as _i,b as Ii}from"./query-management-DbWM5GrR.js";import{z as Fi}from"./theme-utils-CNom64Sw.js";import{u as Li,F as Pi,C as Di,o as Oi,r as $i,a as Mi,b as ia,s as Ye,d as Xs,c as la}from"./form-libs-B6JBoFJD.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function r(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(n){if(n.ep)return;n.ep=!0;const o=r(n);fetch(n.href,o)}})();var ca,Qs=wr;ca=Qs.createRoot,Qs.hydrateRoot;function v(...t){return _o(ys(t))}function me(t){if(t===0)return"0 B";const s=1024,r=["B","KB","MB","GB","TB","PB"],a=Math.floor(Math.log(t)/Math.log(s));return`${parseFloat((t/Math.pow(s,a)).toFixed(2))} ${r[a]}`}function Oe(t,s){return t?Object.keys(t).find(r=>da(t[r],s)):null}function da(t,s){var r;return((r=t.services)==null?void 0:r.some(a=>a.service===s))??!1}const Bi=Ee("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),q=i.forwardRef(({className:t,variant:s,size:r,asChild:a=!1,...n},o)=>{const l=a?Se:"button";return e.jsx(l,{className:v(Bi({variant:s,size:r,className:t})),ref:o,...n})});q.displayName="Button";function zi(){return e.jsx(q,{variant:"ghost",size:"icon",className:"bg-muted hover:bg-muted-hover rounded-lg",asChild:!0,children:e.jsxs("a",{href:"https://github.com/grafana/loki",target:"_blank",rel:"noopener noreferrer",children:[e.jsx("svg",{viewBox:"0 0 438.549 438.549",className:"h-[1.2rem] w-[1.2rem]",children:e.jsx("path",{fill:"currentColor",d:"M409.132 114.573c-19.608-33.596-46.205-60.194-79.798-79.8-33.598-19.607-70.277-29.408-110.063-29.408-39.781 0-76.472 9.804-110.063 29.408-33.596 19.605-60.192 46.204-79.8 79.8C9.803 148.168 0 184.854 0 224.63c0 47.78 13.94 90.745 41.827 128.906 27.884 38.164 63.906 64.572 108.063 79.227 5.14.954 8.945.283 11.419-1.996 2.475-2.282 3.711-5.14 3.711-8.562 0-.571-.049-5.708-.144-15.417a2549.81 2549.81 0 01-.144-25.406l-6.567 1.136c-4.187.767-9.469 1.092-15.846 1-6.374-.089-12.991-.757-19.842-1.999-6.854-1.231-13.229-4.086-19.13-8.559-5.898-4.473-10.085-10.328-12.56-17.556l-2.855-6.57c-1.903-4.374-4.899-9.233-8.992-14.559-4.093-5.331-8.232-8.945-12.419-10.848l-1.999-1.431c-1.332-.951-2.568-2.098-3.711-3.429-1.142-1.331-1.997-2.663-2.568-3.997-.572-1.335-.098-2.43 1.427-3.289 1.525-.859 4.281-1.276 8.28-1.276l5.708.853c3.807.763 8.516 3.042 14.133 6.851 5.614 3.806 10.229 8.754 13.846 14.842 4.38 7.806 9.657 13.754 15.846 17.847 6.184 4.093 12.419 6.136 18.699 6.136 6.28 0 11.704-.476 16.274-1.423 4.565-.952 8.848-2.383 12.847-4.285 1.713-12.758 6.377-22.559 13.988-29.41-10.848-1.14-20.601-2.857-29.264-5.14-8.658-2.286-17.605-5.996-26.835-11.14-9.235-5.137-16.896-11.516-22.985-19.126-6.09-7.614-11.088-17.61-14.987-29.979-3.901-12.374-5.852-26.648-5.852-42.826 0-23.035 7.52-42.637 22.557-58.817-7.044-17.318-6.379-36.732 1.997-58.24 5.52-1.715 13.706-.428 24.554 3.853 10.85 4.283 18.794 7.952 23.84 10.994 5.046 3.041 9.089 5.618 12.135 7.708 17.705-4.947 35.976-7.421 54.818-7.421s37.117 2.474 54.823 7.421l10.849-6.849c7.419-4.57 16.18-8.758 26.262-12.565 10.088-3.805 17.802-4.853 23.134-3.138 8.562 21.509 9.325 40.922 2.279 58.24 15.036 16.18 22.559 35.787 22.559 58.817 0 16.178-1.958 30.497-5.853 42.966-3.9 12.471-8.941 22.457-15.125 29.979-6.191 7.521-13.901 13.85-23.131 18.986-9.232 5.14-18.182 8.85-26.84 11.136-8.662 2.286-18.415 4.004-29.263 5.146 9.894 8.562 14.842 22.077 14.842 40.539v60.237c0 3.422 1.19 6.279 3.572 8.562 2.379 2.279 6.136 2.95 11.276 1.995 44.163-14.653 80.185-41.062 108.068-79.226 27.88-38.161 41.825-81.126 41.825-128.906-.01-39.771-9.818-76.454-29.414-110.049z"})}),e.jsx("span",{className:"sr-only",children:"View on GitHub"})]})})}const Vi={theme:"light",setTheme:()=>null},ua=i.createContext(Vi);function Ui(){const t=i.useContext(ua);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t}function qi({children:t,defaultTheme:s="light",storageKey:r="loki-ui-theme",...a}){const[n,o]=i.useState(()=>{try{const c=localStorage.getItem(r);return c==="dark"||c==="light"?c:s}catch{return s}}),l=c=>{try{localStorage.setItem(r,c),o(c)}catch(d){console.error("Failed to save theme:",d)}};return i.useEffect(()=>{const c=window.document.documentElement;c.classList.remove("light","dark"),c.classList.add(n)},[n]),e.jsx(ua.Provider,{value:{theme:n,setTheme:l},...a,children:t})}function Gi(){const{theme:t,setTheme:s}=Ui(),r=()=>{s(t==="light"?"dark":"light")};return e.jsxs(q,{variant:"ghost",size:"icon",className:"bg-muted hover:bg-muted-hover rounded-lg",onClick:r,children:[t==="light"?e.jsx(Io,{className:"h-[1.2rem] w-[1.2rem]"}):e.jsx(Fo,{className:"h-[1.2rem] w-[1.2rem]"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}function Hi(){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zi,{}),e.jsx(Gi,{})]})}const ks=i.forwardRef(({...t},s)=>e.jsx("nav",{ref:s,"aria-label":"breadcrumb",...t}));ks.displayName="Breadcrumb";const Ss=i.forwardRef(({className:t,...s},r)=>e.jsx("ol",{ref:r,className:v("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...s}));Ss.displayName="BreadcrumbList";const Nt=i.forwardRef(({className:t,...s},r)=>e.jsx("li",{ref:r,className:v("inline-flex items-center gap-1.5",t),...s}));Nt.displayName="BreadcrumbItem";const kt=i.forwardRef(({asChild:t,className:s,...r},a)=>{const n=t?Se:"a";return e.jsx(n,{ref:a,className:v("transition-colors hover:text-foreground",s),...r})});kt.displayName="BreadcrumbLink";const pa=i.forwardRef(({className:t,...s},r)=>e.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:v("font-normal text-foreground",t),...s}));pa.displayName="BreadcrumbPage";const St=({children:t,className:s,...r})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:v("[&>svg]:w-3.5 [&>svg]:h-3.5",s),...r,children:t??e.jsx(kr,{})});St.displayName="BreadcrumbSeparator";const Ki=({match:t})=>{const s=t.params.nodeName;return e.jsx("span",{children:s})},Wi=({match:t})=>{const s=t.params.ringName;return e.jsx("span",{children:s})},ee=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("rounded-xl border bg-card text-card-foreground shadow",t),...s}));ee.displayName="Card";const se=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("flex flex-col space-y-1.5 p-6",t),...s}));se.displayName="CardHeader";const ae=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("font-semibold leading-none tracking-tight",t),...s}));ae.displayName="CardTitle";const Qe=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("text-sm text-muted-foreground",t),...s}));Qe.displayName="CardDescription";const te=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("p-6 pt-0",t),...s}));te.displayName="CardContent";const ma=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("flex items-center p-6 pt-0",t),...s}));ma.displayName="CardFooter";function Zi(){const t=It(),[s]=at(),r=s.get("path")||window.location.pathname;return e.jsxs("div",{className:"flex min-h-[calc(100vh-12rem)] items-center justify-center bg-dot-pattern px-4",children:[e.jsxs(ee,{className:"w-full max-w-[450px] overflow-hidden",children:[e.jsxs(se,{className:"text-center pb-0",children:[e.jsxs("div",{className:"relative mb-8",children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center"}),e.jsx("div",{className:"relative flex justify-center py-4",children:e.jsx("div",{className:"bg-white dark:bg-transparent p-2 rounded-full",children:e.jsx("img",{src:"https://grafana.com/media/docs/loki/logo-grafana-loki.png",alt:"Loki Logo",className:v("h-16 w-16 sm:h-24 sm:w-24","rotate-180 animate-swing hover:animate-shake cursor-pointer transition-all duration-300")})})})]}),e.jsx(ae,{className:"text-5xl sm:text-7xl font-bold bg-gradient-to-r from-primary to-primary/50 bg-clip-text text-transparent",children:"404"})]}),e.jsxs(te,{className:"text-center space-y-3 pb-8",children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-semibold tracking-tight",children:"Oops! Page Not Found"}),e.jsx("p",{className:"text-sm sm:text-base text-muted-foreground",children:"Even with our powerful log aggregation, we couldn't find this page in any of our streams!"}),e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground italic",children:["Error: LogQL query returned 0 results for label"," ",`{path="${r}"}`]})]}),e.jsxs(ma,{className:"flex justify-center gap-4 pb-8",children:[e.jsxs(q,{variant:"outline",onClick:()=>t(-1),className:"gap-2 group",size:"sm",children:[e.jsx(Lo,{className:"h-4 w-4 group-hover:animate-spin"}),"Go Back"]}),e.jsxs(q,{onClick:()=>t("/"),className:"gap-2 group",size:"sm",children:[e.jsx(Po,{className:"h-4 w-4 group-hover:animate-bounce"}),"Go Home"]})]})]}),e.jsx("style",{children:` + .bg-dot-pattern { + background-image: radial-gradient(circle at 1px 1px, hsl(var(--muted-foreground) / 0.1) 1px, transparent 0); + background-size: 32px 32px; + } + @keyframes shake { + 0%, 100% { transform: rotate(180deg); } + 25% { transform: rotate(170deg); } + 75% { transform: rotate(190deg); } + } + @keyframes swing { + 0%, 100% { transform: rotate(180deg); } + 50% { transform: rotate(190deg); } + } + .animate-swing { + animation: swing 1s ease-in-out infinite; + } + .animate-shake { + animation: shake 0.3s ease-in-out; + } + `})]})}const J={INGESTER:"ingester",PARTITION_INGESTER:"partition-ingester",DISTRIBUTOR:"distributor",PATTERN_INGESTER:"pattern-ingester",QUERY_SCHEDULER:"query-scheduler",COMPACTOR:"compactor",RULER:"ruler",INDEX_GATEWAY:"index-gateway"},ga={0:"Unknown",1:"Pending",2:"Active",3:"Inactive",4:"Deleted"},Yi={cluster:null,error:null,isLoading:!0,refresh:()=>Promise.resolve()},fa=i.createContext(Yi);function ue(){const t=i.useContext(fa);if(!t)throw new Error("useCluster must be used within a ClusterProvider");return t}function ha(t){const s=new Date(t);return`${Xo(s)} ago`}function xa(t){const s=new Date(t);return Qo(s,{format:"extended"})}function Et(t){switch(typeof t=="string"?parseInt(t,10):t){case 2:return"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200";case 1:return"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200";case 3:return"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200";case 4:return"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200";default:return"bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"}}function ba(t){const s=t.split("").reduce((n,o)=>o.charCodeAt(0)+((n<<5)-n),0),r=["bg-rose-100 text-rose-800 dark:bg-rose-900 dark:text-rose-200","bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200","bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200","bg-lime-100 text-lime-800 dark:bg-lime-900 dark:text-lime-200","bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200","bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200","bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200","bg-fuchsia-100 text-fuchsia-800 dark:bg-fuchsia-900 dark:text-fuchsia-200"],a=Math.abs(s)%r.length;return r[a]}function Es(t){const s=t.split("-");return s.length>=3?s[s.length-2]:""}function Xi(t){const s=["B","KiB","MiB","GiB","TiB"];let r=t,a=0;for(;r>=1024&&a<s.length-1;)r/=1024,a++;return`${r.toFixed(1)} ${s[a]}`}const Qi=(t,s)=>Object.values(t).some(r=>da(r,s)),ya={ingester:"ingester","partition-ring":"partition-ring",distributor:"distributor","pattern-ingester":"pattern-ingester","query-scheduler":"query-scheduler",compactor:"compactor",ruler:"ruler","index-gateway":"index-gateway"},Ne={ingester:{title:"Ingester",ringName:J.INGESTER,ringPath:"/ring",needsTokens:!0},"partition-ring":{title:"Partition Ingester",ringName:J.PARTITION_INGESTER,ringPath:"/partition-ring",needsTokens:!0},distributor:{title:"Distributor",ringName:J.DISTRIBUTOR,ringPath:"/distributor/ring",needsTokens:!1},"pattern-ingester":{title:"Pattern Ingester",ringName:J.PATTERN_INGESTER,ringPath:"/pattern/ring",needsTokens:!0},"query-scheduler":{title:"Scheduler",ringName:J.QUERY_SCHEDULER,ringPath:"/scheduler/ring",needsTokens:!1},compactor:{title:"Compactor",ringName:J.COMPACTOR,ringPath:"/compactor/ring",needsTokens:!1},ruler:{title:"Ruler",ringName:J.RULER,ringPath:"/ruler/ring",needsTokens:!0},"index-gateway":{title:"Index Gateway",ringName:J.INDEX_GATEWAY,ringPath:"/indexgateway/ring",needsTokens:!0}};function va(t){return Object.keys(Ne).find(s=>Ne[s].ringName===t)}function Ji(t){if(!t)return!1;const s=va(t);return s?Ne[s].needsTokens:!1}const el=t=>{const s=[];if(!t)return s;for(const r in Ne)Qi(t,r)&&s.push({title:Ne[r].title,url:`/rings/${Ne[r].ringName}`});return s};function ja(t,s){if(!t||!s)return"";const r=va(s);if(!r)return"";const a=Oe(t,r);if(!a)return"";const n=`/ui/api/v1/proxy/${a}`,o=Ne[r].ringPath,l=Ne[r].needsTokens?"?tokens=true":"";return`${n}${o}${l}`}const wa=[{id:J.INGESTER,title:"Ingester"},{id:J.PARTITION_INGESTER,title:"Partition Ingester"},{id:J.DISTRIBUTOR,title:"Distributor"},{id:J.PATTERN_INGESTER,title:"Pattern Ingester"},{id:J.QUERY_SCHEDULER,title:"Scheduler"},{id:J.COMPACTOR,title:"Compactor"},{id:J.RULER,title:"Ruler"},{id:J.INDEX_GATEWAY,title:"Index Gateway"}];function tl(t){const s={};try{const r=/<tbody[^>]*>([\s\S]*?)<\/tbody>/,a=t.match(r);if(!a)return s;const n=/<tr[^>]*>([\s\S]*?)<\/tr>/g,o=Array.from(a[1].matchAll(n));for(const l of o){const c=/<td[^>]*>([\s\S]*?)<\/td>/g,d=Array.from(l[1].matchAll(c)).map(u=>u[1].trim().replace(/&nbsp;/g,""));if(d.length>=10){const u=d[0],m=d[9].endsWith("%")?d[9]:`${d[9]}%`;s[u]=m}}}catch(r){console.error("Error parsing ring HTML:",r)}return s}function sl({ringName:t,isPaused:s=!1}){const{cluster:r}=ue(),[a,n]=i.useState(null),[o,l]=i.useState(""),[c,d]=i.useState(!1),u=i.useRef(),m=i.useMemo(()=>Ji(t),[t]),f=i.useCallback(()=>ja(r==null?void 0:r.members,t??""),[r,t]),y=i.useCallback(async()=>{if(!t){l("Ring name is required");return}const g=f();if(!g){l("No cluster members available");return}u.current&&u.current.abort(),u.current=new AbortController,d(!0);try{const x=await fetch(g,{headers:{Accept:"application/json"},signal:u.current.signal});if(!x.ok)throw new Error(`Failed to fetch ring: ${x.statusText}`);const b=await x.json();if(!b||!b.shards){n(null);return}const j=await fetch(g,{headers:{Accept:"text/plain"},signal:u.current.signal});if(!j.ok)throw new Error(`Failed to fetch ring ownership: ${j.statusText}`);const w=await j.text(),E=tl(w),C={...b,shards:b.shards.map(A=>({...A,ownership:E[A.id]||"0%"}))};n(C),l("")}catch(x){if(x instanceof Error&&x.name==="AbortError")return;console.error("Error fetching ring:",x),l(x instanceof Error?x.message:"Unknown error"),n(null)}finally{d(!1)}},[t,f]),N=i.useCallback(async g=>{const x=f();if(!x)throw new Error("Ring name and node name are required");let b=0;const j=g.length;for(const w of g)try{const E=new FormData;E.append("forget",w),(await fetch(x,{method:"POST",body:E})).ok&&b++}catch(E){console.error(`Error forgetting instance ${w}:`,E)}return{success:b,total:j}},[f]),{uniqueStates:h,uniqueZones:p}=i.useMemo(()=>{if(!(a!=null&&a.shards))return{uniqueStates:[],uniqueZones:[]};const g=new Set,x=new Set;return a.shards.forEach(b=>{const j=b.state||"unknown";j.trim()&&g.add(j),b.zone&&b.zone.trim()&&x.add(b.zone)}),{uniqueStates:Array.from(g).sort(),uniqueZones:Array.from(x).sort()}},[a==null?void 0:a.shards]);return i.useEffect(()=>()=>{u.current&&u.current.abort()},[]),i.useEffect(()=>{if(y(),!s){const g=setInterval(()=>{y()},5e3);return()=>{clearInterval(g)}}},[y,s]),{ring:a,error:o,isLoading:c,fetchRing:y,forgetInstances:N,uniqueStates:h,uniqueZones:p,isTokenBased:m}}const Le=i.forwardRef(({className:t,...s},r)=>e.jsx(Ir,{ref:r,className:v("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",t),...s,children:e.jsx(si,{className:v("flex items-center justify-center text-current"),children:e.jsx(qe,{className:"h-4 w-4"})})}));Le.displayName=Ir.displayName;const Ce=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:r,className:v("w-full caption-bottom text-sm",t),...s})}));Ce.displayName="Table";const Te=i.forwardRef(({className:t,...s},r)=>e.jsx("thead",{ref:r,className:v("[&_tr]:border-b",t),...s}));Te.displayName="TableHeader";const Re=i.forwardRef(({className:t,...s},r)=>e.jsx("tbody",{ref:r,className:v("[&_tr:last-child]:border-0",t),...s}));Re.displayName="TableBody";const rl=i.forwardRef(({className:t,...s},r)=>e.jsx("tfoot",{ref:r,className:v("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...s}));rl.displayName="TableFooter";const X=i.forwardRef(({className:t,...s},r)=>e.jsx("tr",{ref:r,className:v("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",t),...s}));X.displayName="TableRow";const D=i.forwardRef(({className:t,...s},r)=>e.jsx("th",{ref:r,className:v("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s}));D.displayName="TableHead";const F=i.forwardRef(({className:t,...s},r)=>e.jsx("td",{ref:r,className:v("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s}));F.displayName="TableCell";const al=i.forwardRef(({className:t,...s},r)=>e.jsx("caption",{ref:r,className:v("mt-4 text-sm text-muted-foreground",t),...s}));al.displayName="TableCaption";const nl=pi,ol=mi,il=i.forwardRef(({className:t,inset:s,children:r,...a},n)=>e.jsxs(qr,{ref:n,className:v("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",s&&"pl-8",t),...a,children:[r,e.jsx(kr,{className:"ml-auto h-4 w-4"})]}));il.displayName=qr.displayName;const ll=i.forwardRef(({className:t,...s},r)=>e.jsx(Gr,{ref:r,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s}));ll.displayName=Gr.displayName;const Na=i.forwardRef(({className:t,sideOffset:s=4,...r},a)=>e.jsx(ui,{children:e.jsx(Hr,{ref:a,sideOffset:s,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));Na.displayName=Hr.displayName;const ds=i.forwardRef(({className:t,inset:s,...r},a)=>e.jsx(Kr,{ref:a,className:v("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...r}));ds.displayName=Kr.displayName;const cl=i.forwardRef(({className:t,children:s,checked:r,...a},n)=>e.jsxs(Wr,{ref:n,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:r,...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Zr,{children:e.jsx(qe,{className:"h-4 w-4"})})}),s]}));cl.displayName=Wr.displayName;const dl=i.forwardRef(({className:t,children:s,...r},a)=>e.jsxs(Yr,{ref:a,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Zr,{children:e.jsx(Do,{className:"h-2 w-2 fill-current"})})}),s]}));dl.displayName=Yr.displayName;const ul=i.forwardRef(({className:t,inset:s,...r},a)=>e.jsx(Xr,{ref:a,className:v("px-2 py-1.5 text-sm font-semibold",s&&"pl-8",t),...r}));ul.displayName=Xr.displayName;const pl=i.forwardRef(({className:t,...s},r)=>e.jsx(Qr,{ref:r,className:v("-mx-1 my-1 h-px bg-muted",t),...s}));pl.displayName=Qr.displayName;function Z({title:t,field:s,sortField:r,sortDirection:a,onSort:n}){const o=r===s,l=c=>{r===s&&a===c||n(s)};return e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs(nl,{children:[e.jsx(ol,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-muted/50 data-[state=open]:bg-muted/50",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{children:t}),o?a==="desc"?e.jsx(Ws,{className:"ml-2 h-4 w-4"}):e.jsx(ls,{className:"ml-2 h-4 w-4"}):e.jsx(Sr,{className:"ml-2 h-4 w-4"})]})})}),e.jsxs(Na,{align:"start",children:[e.jsxs(ds,{onClick:()=>l("asc"),className:v("cursor-pointer",o&&a==="asc"&&"bg-accent"),children:[e.jsx(ls,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground/70"}),"Asc"]}),e.jsxs(ds,{onClick:()=>l("desc"),className:v("cursor-pointer",o&&a==="desc"&&"bg-accent"),children:[e.jsx(Ws,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground/70"}),"Desc"]})]})]})})}var Cs="Progress",Ts=100,[ml,Im]=hr(Cs),[gl,fl]=ml(Cs),ka=i.forwardRef((t,s)=>{const{__scopeProgress:r,value:a=null,max:n,getValueLabel:o=hl,...l}=t;(n||n===0)&&!Js(n)&&console.error(xl(`${n}`,"Progress"));const c=Js(n)?n:Ts;a!==null&&!er(a,c)&&console.error(bl(`${a}`,"Progress"));const d=er(a,c)?a:null,u=Ct(d)?o(d,c):void 0;return e.jsx(gl,{scope:r,value:d,max:c,children:e.jsx(re.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":Ct(d)?d:void 0,"aria-valuetext":u,role:"progressbar","data-state":Ca(d,c),"data-value":d??void 0,"data-max":c,...l,ref:s})})});ka.displayName=Cs;var Sa="ProgressIndicator",Ea=i.forwardRef((t,s)=>{const{__scopeProgress:r,...a}=t,n=fl(Sa,r);return e.jsx(re.div,{"data-state":Ca(n.value,n.max),"data-value":n.value??void 0,"data-max":n.max,...a,ref:s})});Ea.displayName=Sa;function hl(t,s){return`${Math.round(t/s*100)}%`}function Ca(t,s){return t==null?"indeterminate":t===s?"complete":"loading"}function Ct(t){return typeof t=="number"}function Js(t){return Ct(t)&&!isNaN(t)&&t>0}function er(t,s){return Ct(t)&&!isNaN(t)&&t<=s&&t>=0}function xl(t,s){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${s}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Ts}\`.`}function bl(t,s){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${s}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${Ts} if no \`max\` prop is set) + - \`null\` or \`undefined\` if the progress is indeterminate. + +Defaulting to \`null\`.`}var Ta=ka,yl=Ea;const Ra=i.forwardRef(({className:t,value:s,...r},a)=>e.jsx(Ta,{ref:a,className:v("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...r,children:e.jsx(yl,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(s||0)}%)`}})}));Ra.displayName=Ta.displayName;function vl({visibleIds:t,selectedIds:s,onChange:r}){const a=t.every(o=>s.has(o)),n=()=>{const o=new Set(t);r(a?new Set([...s].filter(l=>!o.has(l))):new Set([...s,...t]))};return e.jsx(Le,{checked:t.length>0&&a,onCheckedChange:n,"aria-label":"Select all visible instances"})}function jl({instances:t,selectedInstances:s,onSelectInstance:r,sortField:a,sortDirection:n,onSort:o,showTokens:l=!1}){return e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{className:"hover:bg-transparent",children:[e.jsx(D,{className:"w-[50px]",children:e.jsx(vl,{visibleIds:t.map(c=>c.id),selectedIds:s,onChange:c=>{t.forEach(d=>{c.has(d.id)!==s.has(d.id)&&r(d.id)})}})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"ID",field:"id",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"State",field:"state",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{children:e.jsx(Z,{title:"Address",field:"address",sortField:a,sortDirection:n,onSort:o})}),l&&e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Ownership",field:"ownership",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"Zone",field:"zone",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Last Heartbeat",field:"timestamp",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[50px]"})]})}),e.jsxs(Re,{children:[t.map(c=>{const d=l?c.ownership:0;return e.jsxs(X,{children:[e.jsx(F,{children:e.jsx(Le,{checked:s.has(c.id),onCheckedChange:()=>r(c.id),"aria-label":`Select instance ${c.id}`})}),e.jsx(F,{className:"font-medium",children:e.jsx(ce,{to:`/nodes/${c.id}`,className:"hover:underline",children:c.id})}),e.jsx(F,{children:e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",Et(c.state)),children:c.state})}),e.jsx(F,{children:c.address}),l&&e.jsx(F,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:d}),e.jsxs("span",{className:"text-muted-foreground",children:[c.tokens.length," tokens"]})]}),e.jsx(Ra,{value:typeof d=="number"?d:Number(d.slice(0,-1)),className:"h-2"})]})}),e.jsx(F,{children:c.zone?e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",ba(c.zone)),children:c.zone}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(F,{children:e.jsx("span",{title:xa(c.timestamp),className:"text-muted-foreground",children:ha(c.timestamp)})}),e.jsx(F,{children:e.jsx(q,{variant:"ghost",size:"icon",asChild:!0,className:"h-8 w-8",title:"View instance details",children:e.jsx(ce,{to:`/nodes/${c.id}`,children:e.jsx(Ft,{className:"h-4 w-4"})})})})]},c.id)}),t.length===0&&e.jsx(X,{children:e.jsx(F,{colSpan:7,className:"h-24 text-center",children:e.jsx("div",{className:"text-muted-foreground",children:"No instances found"})})})]})]})}const xe=i.forwardRef(({className:t,type:s,...r},a)=>e.jsx("input",{type:s,className:v("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:a,...r}));xe.displayName="Input";var tr=1,wl=.9,Nl=.8,kl=.17,Qt=.1,Jt=.999,Sl=.9999,El=.99,Cl=/[\\\/_+.#"@\[\(\{&]/,Tl=/[\\\/_+.#"@\[\(\{&]/g,Rl=/[\s-]/,Aa=/[\s-]/g;function us(t,s,r,a,n,o,l){if(o===s.length)return n===t.length?tr:El;var c=`${n},${o}`;if(l[c]!==void 0)return l[c];for(var d=a.charAt(o),u=r.indexOf(d,n),m=0,f,y,N,h;u>=0;)f=us(t,s,r,a,u+1,o+1,l),f>m&&(u===n?f*=tr:Cl.test(t.charAt(u-1))?(f*=Nl,N=t.slice(n,u-1).match(Tl),N&&n>0&&(f*=Math.pow(Jt,N.length))):Rl.test(t.charAt(u-1))?(f*=wl,h=t.slice(n,u-1).match(Aa),h&&n>0&&(f*=Math.pow(Jt,h.length))):(f*=kl,n>0&&(f*=Math.pow(Jt,u-n))),t.charAt(u)!==s.charAt(o)&&(f*=Sl)),(f<Qt&&r.charAt(u-1)===a.charAt(o+1)||a.charAt(o+1)===a.charAt(o)&&r.charAt(u-1)!==a.charAt(o))&&(y=us(t,s,r,a,u+1,o+2,l),y*Qt>f&&(f=y*Qt)),f>m&&(m=f),u=r.indexOf(d,u+1);return l[c]=m,m}function sr(t){return t.toLowerCase().replace(Aa," ")}function Al(t,s,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,us(t,s,sr(t),sr(s),0,0,{})}var _a={exports:{}},Ia={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ve=i;function _l(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Il=typeof Object.is=="function"?Object.is:_l,Fl=Ve.useState,Ll=Ve.useEffect,Pl=Ve.useLayoutEffect,Dl=Ve.useDebugValue;function Ol(t,s){var r=s(),a=Fl({inst:{value:r,getSnapshot:s}}),n=a[0].inst,o=a[1];return Pl(function(){n.value=r,n.getSnapshot=s,es(n)&&o({inst:n})},[t,r,s]),Ll(function(){return es(n)&&o({inst:n}),t(function(){es(n)&&o({inst:n})})},[t]),Dl(r),r}function es(t){var s=t.getSnapshot;t=t.value;try{var r=s();return!Il(t,r)}catch{return!0}}function $l(t,s){return s()}var Ml=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?$l:Ol;Ia.useSyncExternalStore=Ve.useSyncExternalStore!==void 0?Ve.useSyncExternalStore:Ml;_a.exports=Ia;var Bl=_a.exports,We='[cmdk-group=""]',ts='[cmdk-group-items=""]',zl='[cmdk-group-heading=""]',Rs='[cmdk-item=""]',rr=`${Rs}:not([aria-disabled="true"])`,ps="cmdk-item-select",_e="data-value",Vl=(t,s,r)=>Al(t,s,r),Fa=i.createContext(void 0),ut=()=>i.useContext(Fa),La=i.createContext(void 0),As=()=>i.useContext(La),Pa=i.createContext(void 0),Da=i.forwardRef((t,s)=>{let r=$e(()=>{var S,R;return{search:"",value:(R=(S=t.value)!=null?S:t.defaultValue)!=null?R:"",filtered:{count:0,items:new Map,groups:new Set}}}),a=$e(()=>new Set),n=$e(()=>new Map),o=$e(()=>new Map),l=$e(()=>new Set),c=Oa(t),{label:d,children:u,value:m,onValueChange:f,filter:y,shouldFilter:N,loop:h,disablePointerSelection:p=!1,vimBindings:g=!0,...x}=t,b=Me(),j=Me(),w=Me(),E=i.useRef(null),C=Jl();Pe(()=>{if(m!==void 0){let S=m.trim();r.current.value=S,A.emit()}},[m]),Pe(()=>{C(6,W)},[]);let A=i.useMemo(()=>({subscribe:S=>(l.current.add(S),()=>l.current.delete(S)),snapshot:()=>r.current,setState:(S,R,$)=>{var L,G,H;if(!Object.is(r.current[S],R)){if(r.current[S]=R,S==="search")M(),Y(),C(1,K);else if(S==="value"&&($||C(5,W),((L=c.current)==null?void 0:L.value)!==void 0)){let ne=R??"";(H=(G=c.current).onValueChange)==null||H.call(G,ne);return}A.emit()}},emit:()=>{l.current.forEach(S=>S())}}),[]),B=i.useMemo(()=>({value:(S,R,$)=>{var L;R!==((L=o.current.get(S))==null?void 0:L.value)&&(o.current.set(S,{value:R,keywords:$}),r.current.filtered.items.set(S,z(R,$)),C(2,()=>{Y(),A.emit()}))},item:(S,R)=>(a.current.add(S),R&&(n.current.has(R)?n.current.get(R).add(S):n.current.set(R,new Set([S]))),C(3,()=>{M(),Y(),r.current.value||K(),A.emit()}),()=>{o.current.delete(S),a.current.delete(S),r.current.filtered.items.delete(S);let $=T();C(4,()=>{M(),($==null?void 0:$.getAttribute("id"))===S&&K(),A.emit()})}),group:S=>(n.current.has(S)||n.current.set(S,new Set),()=>{o.current.delete(S),n.current.delete(S)}),filter:()=>c.current.shouldFilter,label:d||t["aria-label"],getDisablePointerSelection:()=>c.current.disablePointerSelection,listId:b,inputId:w,labelId:j,listInnerRef:E}),[]);function z(S,R){var $,L;let G=(L=($=c.current)==null?void 0:$.filter)!=null?L:Vl;return S?G(S,r.current.search,R):0}function Y(){if(!r.current.search||c.current.shouldFilter===!1)return;let S=r.current.filtered.items,R=[];r.current.filtered.groups.forEach(L=>{let G=n.current.get(L),H=0;G.forEach(ne=>{let de=S.get(ne);H=Math.max(de,H)}),R.push([L,H])});let $=E.current;O().sort((L,G)=>{var H,ne;let de=L.getAttribute("id"),gt=G.getAttribute("id");return((H=S.get(gt))!=null?H:0)-((ne=S.get(de))!=null?ne:0)}).forEach(L=>{let G=L.closest(ts);G?G.appendChild(L.parentElement===G?L:L.closest(`${ts} > *`)):$.appendChild(L.parentElement===$?L:L.closest(`${ts} > *`))}),R.sort((L,G)=>G[1]-L[1]).forEach(L=>{var G;let H=(G=E.current)==null?void 0:G.querySelector(`${We}[${_e}="${encodeURIComponent(L[0])}"]`);H==null||H.parentElement.appendChild(H)})}function K(){let S=O().find($=>$.getAttribute("aria-disabled")!=="true"),R=S==null?void 0:S.getAttribute(_e);A.setState("value",R||void 0)}function M(){var S,R,$,L;if(!r.current.search||c.current.shouldFilter===!1){r.current.filtered.count=a.current.size;return}r.current.filtered.groups=new Set;let G=0;for(let H of a.current){let ne=(R=(S=o.current.get(H))==null?void 0:S.value)!=null?R:"",de=(L=($=o.current.get(H))==null?void 0:$.keywords)!=null?L:[],gt=z(ne,de);r.current.filtered.items.set(H,gt),gt>0&&G++}for(let[H,ne]of n.current)for(let de of ne)if(r.current.filtered.items.get(de)>0){r.current.filtered.groups.add(H);break}r.current.filtered.count=G}function W(){var S,R,$;let L=T();L&&(((S=L.parentElement)==null?void 0:S.firstChild)===L&&(($=(R=L.closest(We))==null?void 0:R.querySelector(zl))==null||$.scrollIntoView({block:"nearest"})),L.scrollIntoView({block:"nearest"}))}function T(){var S;return(S=E.current)==null?void 0:S.querySelector(`${Rs}[aria-selected="true"]`)}function O(){var S;return Array.from(((S=E.current)==null?void 0:S.querySelectorAll(rr))||[])}function V(S){let R=O()[S];R&&A.setState("value",R.getAttribute(_e))}function Q(S){var R;let $=T(),L=O(),G=L.findIndex(ne=>ne===$),H=L[G+S];(R=c.current)!=null&&R.loop&&(H=G+S<0?L[L.length-1]:G+S===L.length?L[0]:L[G+S]),H&&A.setState("value",H.getAttribute(_e))}function _(S){let R=T(),$=R==null?void 0:R.closest(We),L;for(;$&&!L;)$=S>0?Xl($,We):Ql($,We),L=$==null?void 0:$.querySelector(rr);L?A.setState("value",L.getAttribute(_e)):Q(S)}let I=()=>V(O().length-1),P=S=>{S.preventDefault(),S.metaKey?I():S.altKey?_(1):Q(1)},U=S=>{S.preventDefault(),S.metaKey?V(0):S.altKey?_(-1):Q(-1)};return i.createElement(re.div,{ref:s,tabIndex:-1,...x,"cmdk-root":"",onKeyDown:S=>{var R;if((R=x.onKeyDown)==null||R.call(x,S),!S.defaultPrevented)switch(S.key){case"n":case"j":{g&&S.ctrlKey&&P(S);break}case"ArrowDown":{P(S);break}case"p":case"k":{g&&S.ctrlKey&&U(S);break}case"ArrowUp":{U(S);break}case"Home":{S.preventDefault(),V(0);break}case"End":{S.preventDefault(),I();break}case"Enter":if(!S.nativeEvent.isComposing&&S.keyCode!==229){S.preventDefault();let $=T();if($){let L=new Event(ps);$.dispatchEvent(L)}}}}},i.createElement("label",{"cmdk-label":"",htmlFor:B.inputId,id:B.labelId,style:tc},d),Bt(t,S=>i.createElement(La.Provider,{value:A},i.createElement(Fa.Provider,{value:B},S))))}),Ul=i.forwardRef((t,s)=>{var r,a;let n=Me(),o=i.useRef(null),l=i.useContext(Pa),c=ut(),d=Oa(t),u=(a=(r=d.current)==null?void 0:r.forceMount)!=null?a:l==null?void 0:l.forceMount;Pe(()=>{if(!u)return c.item(n,l==null?void 0:l.id)},[u]);let m=$a(n,o,[t.value,t.children,o],t.keywords),f=As(),y=De(C=>C.value&&C.value===m.current),N=De(C=>u||c.filter()===!1?!0:C.search?C.filtered.items.get(n)>0:!0);i.useEffect(()=>{let C=o.current;if(!(!C||t.disabled))return C.addEventListener(ps,h),()=>C.removeEventListener(ps,h)},[N,t.onSelect,t.disabled]);function h(){var C,A;p(),(A=(C=d.current).onSelect)==null||A.call(C,m.current)}function p(){f.setState("value",m.current,!0)}if(!N)return null;let{disabled:g,value:x,onSelect:b,forceMount:j,keywords:w,...E}=t;return i.createElement(re.div,{ref:Je([o,s]),...E,id:n,"cmdk-item":"",role:"option","aria-disabled":!!g,"aria-selected":!!y,"data-disabled":!!g,"data-selected":!!y,onPointerMove:g||c.getDisablePointerSelection()?void 0:p,onClick:g?void 0:h},t.children)}),ql=i.forwardRef((t,s)=>{let{heading:r,children:a,forceMount:n,...o}=t,l=Me(),c=i.useRef(null),d=i.useRef(null),u=Me(),m=ut(),f=De(N=>n||m.filter()===!1?!0:N.search?N.filtered.groups.has(l):!0);Pe(()=>m.group(l),[]),$a(l,c,[t.value,t.heading,d]);let y=i.useMemo(()=>({id:l,forceMount:n}),[n]);return i.createElement(re.div,{ref:Je([c,s]),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},r&&i.createElement("div",{ref:d,"cmdk-group-heading":"","aria-hidden":!0,id:u},r),Bt(t,N=>i.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?u:void 0},i.createElement(Pa.Provider,{value:y},N))))}),Gl=i.forwardRef((t,s)=>{let{alwaysRender:r,...a}=t,n=i.useRef(null),o=De(l=>!l.search);return!r&&!o?null:i.createElement(re.div,{ref:Je([n,s]),...a,"cmdk-separator":"",role:"separator"})}),Hl=i.forwardRef((t,s)=>{let{onValueChange:r,...a}=t,n=t.value!=null,o=As(),l=De(m=>m.search),c=De(m=>m.value),d=ut(),u=i.useMemo(()=>{var m;let f=(m=d.listInnerRef.current)==null?void 0:m.querySelector(`${Rs}[${_e}="${encodeURIComponent(c)}"]`);return f==null?void 0:f.getAttribute("id")},[]);return i.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),i.createElement(re.input,{ref:s,...a,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":d.listId,"aria-labelledby":d.labelId,"aria-activedescendant":u,id:d.inputId,type:"text",value:n?t.value:l,onChange:m=>{n||o.setState("search",m.target.value),r==null||r(m.target.value)}})}),Kl=i.forwardRef((t,s)=>{let{children:r,label:a="Suggestions",...n}=t,o=i.useRef(null),l=i.useRef(null),c=ut();return i.useEffect(()=>{if(l.current&&o.current){let d=l.current,u=o.current,m,f=new ResizeObserver(()=>{m=requestAnimationFrame(()=>{let y=d.offsetHeight;u.style.setProperty("--cmdk-list-height",y.toFixed(1)+"px")})});return f.observe(d),()=>{cancelAnimationFrame(m),f.unobserve(d)}}},[]),i.createElement(re.div,{ref:Je([o,s]),...n,"cmdk-list":"",role:"listbox","aria-label":a,id:c.listId},Bt(t,d=>i.createElement("div",{ref:Je([l,c.listInnerRef]),"cmdk-list-sizer":""},d)))}),Wl=i.forwardRef((t,s)=>{let{open:r,onOpenChange:a,overlayClassName:n,contentClassName:o,container:l,...c}=t;return i.createElement(ws,{open:r,onOpenChange:a},i.createElement(Ns,{container:l},i.createElement(it,{"cmdk-overlay":"",className:n}),i.createElement(lt,{"aria-label":t.label,"cmdk-dialog":"",className:o},i.createElement(Da,{ref:s,...c}))))}),Zl=i.forwardRef((t,s)=>De(r=>r.filtered.count===0)?i.createElement(re.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),Yl=i.forwardRef((t,s)=>{let{progress:r,children:a,label:n="Loading...",...o}=t;return i.createElement(re.div,{ref:s,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Bt(t,l=>i.createElement("div",{"aria-hidden":!0},l)))}),oe=Object.assign(Da,{List:Kl,Item:Ul,Input:Hl,Group:ql,Separator:Gl,Dialog:Wl,Empty:Zl,Loading:Yl});function Xl(t,s){let r=t.nextElementSibling;for(;r;){if(r.matches(s))return r;r=r.nextElementSibling}}function Ql(t,s){let r=t.previousElementSibling;for(;r;){if(r.matches(s))return r;r=r.previousElementSibling}}function Oa(t){let s=i.useRef(t);return Pe(()=>{s.current=t}),s}var Pe=typeof window>"u"?i.useEffect:i.useLayoutEffect;function $e(t){let s=i.useRef();return s.current===void 0&&(s.current=t()),s}function Je(t){return s=>{t.forEach(r=>{typeof r=="function"?r(s):r!=null&&(r.current=s)})}}function De(t){let s=As(),r=()=>t(s.snapshot());return Bl.useSyncExternalStore(s.subscribe,r,r)}function $a(t,s,r,a=[]){let n=i.useRef(),o=ut();return Pe(()=>{var l;let c=(()=>{var u;for(let m of r){if(typeof m=="string")return m.trim();if(typeof m=="object"&&"current"in m)return m.current?(u=m.current.textContent)==null?void 0:u.trim():n.current}})(),d=a.map(u=>u.trim());o.value(t,c,d),(l=s.current)==null||l.setAttribute(_e,c),n.current=c}),n}var Jl=()=>{let[t,s]=i.useState(),r=$e(()=>new Map);return Pe(()=>{r.current.forEach(a=>a()),r.current=new Map},[t]),(a,n)=>{r.current.set(a,n),s({})}};function ec(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Bt({asChild:t,children:s},r){return t&&i.isValidElement(s)?i.cloneElement(ec(s),{ref:s.ref},r(s.props.children)):r(s)}var tc={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ma=ws,sc=Ns,Ba=i.forwardRef(({className:t,...s},r)=>e.jsx(it,{ref:r,className:v("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));Ba.displayName=it.displayName;const _s=i.forwardRef(({className:t,children:s,...r},a)=>e.jsxs(sc,{children:[e.jsx(Ba,{}),e.jsxs(lt,{ref:a,className:v("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r,children:[s,e.jsxs(aa,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(vs,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));_s.displayName=lt.displayName;const Is=({className:t,...s})=>e.jsx("div",{className:v("flex flex-col space-y-1.5 text-center sm:text-left",t),...s});Is.displayName="DialogHeader";const Fs=({className:t,...s})=>e.jsx("div",{className:v("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...s});Fs.displayName="DialogFooter";const Ls=i.forwardRef(({className:t,...s},r)=>e.jsx(Lt,{ref:r,className:v("text-lg font-semibold leading-none tracking-tight",t),...s}));Ls.displayName=Lt.displayName;const Ps=i.forwardRef(({className:t,...s},r)=>e.jsx(Pt,{ref:r,className:v("text-sm text-muted-foreground",t),...s}));Ps.displayName=Pt.displayName;const za=i.forwardRef(({className:t,...s},r)=>e.jsx(oe,{ref:r,className:v("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...s}));za.displayName=oe.displayName;const Va=i.forwardRef(({className:t,...s},r)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Er,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(oe.Input,{ref:r,className:v("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...s})]}));Va.displayName=oe.Input.displayName;const rc=i.forwardRef(({className:t,...s},r)=>e.jsx(oe.List,{ref:r,className:v("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...s}));rc.displayName=oe.List.displayName;const Ua=i.forwardRef((t,s)=>e.jsx(oe.Empty,{ref:s,className:"py-6 text-center text-sm",...t}));Ua.displayName=oe.Empty.displayName;const qa=i.forwardRef(({className:t,...s},r)=>e.jsx(oe.Group,{ref:r,className:v("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...s}));qa.displayName=oe.Group.displayName;const ac=i.forwardRef(({className:t,...s},r)=>e.jsx(oe.Separator,{ref:r,className:v("-mx-1 h-px bg-border",t),...s}));ac.displayName=oe.Separator.displayName;const ms=i.forwardRef(({className:t,...s},r)=>e.jsx(oe.Item,{ref:r,className:v("relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t),...s}));ms.displayName=oe.Item.displayName;const nc=po,oc=mo,Ga=i.forwardRef(({className:t,align:s="center",sideOffset:r=4,...a},n)=>e.jsx(uo,{children:e.jsx(xr,{ref:n,align:s,sideOffset:r,className:v("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})}));Ga.displayName=xr.displayName;function Fe({options:t=[],selected:s=[],onChange:r,placeholder:a="Select options...",emptyMessage:n="No options found.",className:o}){const[l,c]=i.useState(!1),d=y=>{const N=s.includes(y)?s.filter(h=>h!==y):[...s,y];r(N)},u=()=>{s.length===t.length?r([]):r(t.map(y=>y.value))},m=s.length,f=t.length;return e.jsxs(nc,{open:l,onOpenChange:c,children:[e.jsx(oc,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox","aria-expanded":l,className:v("justify-between",o),children:[m===0?a:`${m} selected`,e.jsx(Sr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ga,{className:"w-[200px] p-0",children:e.jsxs(za,{children:[e.jsx(Va,{placeholder:a}),e.jsx(Ua,{children:n}),e.jsxs(qa,{children:[f>0&&e.jsx(ms,{onSelect:u,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{checked:m>0&&m===f,"aria-label":"Select all"}),e.jsx("span",{children:"Select all"})]})}),t.map(y=>e.jsx(ms,{onSelect:()=>d(y.value),children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{checked:s.includes(y.value)}),e.jsx("span",{children:y.label})]})},y.value))]})]})})]})}function ic({idFilter:t,onIdFilterChange:s,stateFilter:r,onStateFilterChange:a,zoneFilter:n,onZoneFilterChange:o,uniqueStates:l,uniqueZones:c}){return e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Er,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Filter by ID...",value:t,onChange:d=>s(d.target.value),className:"pl-8"})]}),l.length>0&&e.jsx(Fe,{options:l.map(d=>({value:d,label:d})),selected:r,onChange:a,placeholder:"Filter by State",className:"w-[180px]"}),c.length>0&&e.jsx(Fe,{options:c.map(d=>({value:d,label:d})),selected:n,onChange:o,placeholder:"Filter by Zone",className:"w-[180px]"})]})}const lc=t=>{switch(t){case"ACTIVE":return"#22c55e";case"LEAVING":return"#eab308";case"PENDING":return"#3b82f6";case"JOINING":return"#a855f7";case"LEFT":return"#ef4444";default:return"#6b7280"}};function cc({instances:t}){const s=i.useMemo(()=>{const a=new Map;return t.forEach(n=>{const o=n.state||"unknown";a.set(o,(a.get(o)||0)+1)}),Array.from(a.entries()).sort((n,o)=>o[1]-n[1]).map(([n,o])=>({name:n,value:o,color:lc(n)}))},[t]),r=i.useMemo(()=>t.length,[t]);return s.length===0?null:e.jsxs("div",{className:"w-full h-[120px] relative",children:[e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center pointer-events-none",children:[e.jsx("div",{className:"text-xl font-bold",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Instances"})]}),e.jsx(ct,{width:"100%",height:"100%",children:e.jsxs(Dt,{children:[e.jsx(Ot,{data:s,cx:"50%",cy:"50%",labelLine:!1,outerRadius:60,innerRadius:42,dataKey:"value",paddingAngle:1,strokeWidth:1,children:s.map(a=>e.jsx($t,{fill:a.color,stroke:"hsl(var(--background))"},`cell-${a.name}`))}),e.jsx(dt,{content:({active:a,payload:n})=>{if(!a||!n||!n[0])return null;const o=n[0].payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm",style:{backgroundColor:o.color}}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx("span",{className:"text-sm font-semibold",children:o.value})]})}})]})})]})}function Ha({onRefresh:t,isPaused:s=!1,isLoading:r,className:a}){const[n,o]=i.useState(r);return i.useEffect(()=>{let l;return r?o(!0):l=setTimeout(()=>{o(!1)},1e3),()=>{l&&clearTimeout(l)}},[r]),e.jsxs("div",{className:`flex items-center gap-2 text-sm text-muted-foreground ${a}`,children:[e.jsx(q,{variant:"secondary",size:"sm",className:"h-6 px-2 text-xs hover:bg-muted",onClick:t,children:"Refresh now"}),s?e.jsx(Oo,{className:"h-3 w-3 text-orange-500"}):e.jsx(he,{className:`h-3 w-3 ${n?"animate-spin text-emerald-500 ":"opacity-0 transition-opacity duration-1000"} `}),e.jsx("span",{className:"transition-opacity duration-1000",children:s?"Auto-refresh paused":n?"Refreshing...":""})]})}const dc=Ee("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Ge=i.forwardRef(({className:t,variant:s,...r},a)=>e.jsx("div",{ref:a,role:"alert",className:v(dc({variant:s}),t),...r}));Ge.displayName="Alert";const He=i.forwardRef(({className:t,...s},r)=>e.jsx("h5",{ref:r,className:v("mb-1 font-medium leading-none tracking-tight",t),...s}));He.displayName="AlertTitle";const Ke=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,className:v("text-sm [&_p]:leading-relaxed",t),...s}));Ke.displayName="AlertDescription";function ke({children:t,className:s,spacing:r=!0,...a}){return e.jsx("div",{className:"container p-6",children:e.jsx("div",{className:v(r&&"space-y-6",s),...a,children:t})})}function Ds({error:t,ringName:s}){return t?e.jsx(ke,{children:e.jsxs(Ge,{variant:"destructive",children:[e.jsx(nt,{className:"h-4 w-4"}),e.jsx(He,{children:"Error"}),e.jsx(Ke,{children:t})]})}):s?null:e.jsx(ke,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Cr,{className:"h-6 w-6"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Rings"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:wa.map(r=>e.jsx(ce,{to:`/rings/${r.id}`,children:e.jsxs(ee,{className:"hover:bg-muted/50 transition-colors cursor-pointer",children:[e.jsx(se,{children:e.jsx(ae,{children:r.title})}),e.jsx(te,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["View and manage ",r.title.toLowerCase()," ring members"]})})]})},r.id))})]})})}const uc=5,pc=1e6;let ss=0;function mc(){return ss=(ss+1)%Number.MAX_SAFE_INTEGER,ss.toString()}const rs=new Map,ar=t=>{if(rs.has(t))return;const s=setTimeout(()=>{rs.delete(t),Xe({type:"REMOVE_TOAST",toastId:t})},pc);rs.set(t,s)},gc=(t,s)=>{switch(s.type){case"ADD_TOAST":return{...t,toasts:[s.toast,...t.toasts].slice(0,uc)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(r=>r.id===s.toast.id?{...r,...s.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=s;return r?ar(r):t.toasts.forEach(a=>{ar(a.id)}),{...t,toasts:t.toasts.map(a=>a.id===r||r===void 0?{...a,open:!1}:a)}}case"REMOVE_TOAST":return s.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(r=>r.id!==s.toastId)}}},xt=[];let bt={toasts:[]};function Xe(t){bt=gc(bt,t),xt.forEach(s=>{s(bt)})}function fc({...t}){const s=mc(),r=n=>Xe({type:"UPDATE_TOAST",toast:{...n,id:s}}),a=()=>Xe({type:"DISMISS_TOAST",toastId:s});return Xe({type:"ADD_TOAST",toast:{...t,id:s,open:!0,onOpenChange:n=>{n||a()}}}),{id:s,dismiss:a,update:r}}function zt(){const[t,s]=i.useState(bt);return i.useEffect(()=>(xt.push(s),()=>{const r=xt.indexOf(s);r>-1&&xt.splice(r,1)}),[t]),{...t,toast:fc,dismiss:r=>Xe({type:"DISMISS_TOAST",toastId:r})}}function hc({ringName:t}){var Q;const[s,r]=i.useState(new Set),[a,n]=i.useState(!1),[o,l]=i.useState(0),[c,d]=i.useState("id"),[u,m]=i.useState("asc"),[f,y]=i.useState(""),[N,h]=i.useState([]),[p,g]=i.useState([]),[x,b]=i.useState(!1),{ring:j,error:w,isLoading:E,fetchRing:C,forgetInstances:A,uniqueStates:B,uniqueZones:z,isTokenBased:Y}=sl({ringName:t,isPaused:s.size>0}),K=i.useMemo(()=>j!=null&&j.shards?j.shards.filter(_=>s.has(_.id)):[],[j==null?void 0:j.shards,s]),M=i.useCallback(_=>{d(I=>I===_?(m(P=>P==="asc"?"desc":"asc"),_):(m("asc"),_))},[]),W=i.useCallback(_=>{r(I=>{const P=new Set(I);return P.has(_)?P.delete(_):P.add(_),P})},[]),{toast:T}=zt(),O=i.useCallback(async()=>{if(s.size!==0)try{n(!0),l(0);const{success:_,total:I}=await A(Array.from(s));_>0&&(await C(),r(new Set)),_<I&&T({title:"Failed to forget instances",description:`Failed to forget ${I-_} instance(s)`,variant:"destructive"})}catch{T({title:"Failed to forget instances",description:`${w}`,variant:"destructive"})}finally{n(!1),b(!1)}},[s,A,C,T,w]),V=i.useMemo(()=>j!=null&&j.shards?j.shards.filter(_=>{const I=_.id.toLowerCase().includes(f.toLowerCase()),P=N.length===0||N.includes(_.state),U=p.length===0||p.includes(_.zone);return I&&P&&U}).sort((_,I)=>{let P=0;switch(c){case"id":P=_.id.localeCompare(I.id);break;case"state":P=_.state.localeCompare(I.state);break;case"address":P=_.address.localeCompare(I.address);break;case"zone":P=(_.zone||"").localeCompare(I.zone||"");break;case"timestamp":P=new Date(_.timestamp).getTime()-new Date(I.timestamp).getTime();break;case"tokens":P=_.tokens.length-I.tokens.length;break;case"ownership":P=parseFloat(_.ownership)-parseFloat(I.ownership);break}return u==="asc"?P:-P}):[],[j==null?void 0:j.shards,f,N,p,c,u]);return w?e.jsx(Ds,{error:w,ringName:t}):e.jsxs("div",{className:"container space-y-6 p-6",children:[e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-8",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs(ae,{className:"text-3xl font-semibold tracking-tight",children:[((Q=wa.find(_=>_.id===t))==null?void 0:Q.title)||""," ","Ring Members"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View and manage ring instances with their current status and configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between min-h-[32px]",children:[e.jsx(Ha,{onRefresh:C,isPaused:s.size>0,isLoading:E}),s.size>0&&e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[s.size," instance",s.size!==1?"s":""," selected"]}),e.jsxs(q,{onClick:()=>b(!0),disabled:a,size:"sm",variant:"outline",className:v("border-red-200 bg-red-50 text-red-900 hover:bg-red-100 hover:text-red-900","dark:border-red-800 dark:bg-red-950 dark:text-red-200 dark:hover:bg-red-900","disabled:hover:bg-red-50 dark:disabled:hover:bg-red-950"),children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"mr-2 h-4 w-4 animate-spin"}),o>0&&e.jsxs("span",{className:"mr-2",children:[o,"/",s.size]})]}),"Forget Selected"]})]})]})]}),e.jsx("div",{className:"flex items-center",children:e.jsx("div",{className:"w-[250px]",children:(j==null?void 0:j.shards)&&e.jsx(cc,{instances:j.shards})})})]})}),e.jsxs(te,{className:"space-y-6",children:[e.jsx(ic,{idFilter:f,onIdFilterChange:y,stateFilter:N,onStateFilterChange:h,zoneFilter:p,onZoneFilterChange:g,uniqueStates:B,uniqueZones:z}),e.jsx("div",{className:"rounded-md border bg-card",children:e.jsx(jl,{instances:V,selectedInstances:s,onSelectInstance:W,sortField:c,sortDirection:u,onSort:M,showTokens:Y})})]})]}),e.jsx(Ma,{open:x,onOpenChange:b,children:e.jsxs(_s,{children:[e.jsxs(Is,{children:[e.jsx(Ls,{children:"Confirm Forget Instances"}),e.jsx(Ps,{children:"Are you sure you want to forget the following instances? This action cannot be undone."})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto",children:e.jsx("div",{className:"space-y-2",children:K.map(_=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:_.id}),e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",Et(_.state)),children:_.state})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:_.address})]},_.id))})}),e.jsxs(Fs,{children:[e.jsx(q,{variant:"outline",onClick:()=>b(!1),disabled:a,children:"Cancel"}),e.jsx(q,{variant:"outline",onClick:O,disabled:a,className:v("border-red-200 bg-red-50 text-red-900 hover:bg-red-100 hover:text-red-900","dark:border-red-800 dark:bg-red-950 dark:text-red-200 dark:hover:bg-red-900","disabled:hover:bg-red-50 dark:disabled:hover:bg-red-950"),children:a?e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"mr-2 h-4 w-4 animate-spin"}),"Forgetting..."]}):"Forget Instances"})]})]})})]})}const xc=()=>{const t=i.useRef({});return{fetchMetrics:i.useCallback(async({nodeNames:r,metrics:a})=>{if(!r.length)return{};const n={...t.current},o={};return await Promise.all(r.map(async l=>{try{const c=await fetch(`/ui/api/v1/proxy/${l}/metrics`);if(!c.ok)throw new Error(`Failed to fetch metrics: ${c.statusText}`);const d=await c.text(),u={timestamp:Date.now(),values:{}};a.forEach(f=>{const y=new RegExp(`${f}\\{[^}]*\\}\\s+([\\d.e+]+)`),N=d.match(y);N&&(u.values[f]=parseFloat(N[1]))});const m=t.current[l];if(n[l]=u,m){const f=(u.timestamp-m.timestamp)/1e3;if(f>0){const y=a.map(N=>{const h=u.values[N],p=m.values[N];if(h!==void 0&&p!==void 0){const g=(h-p)/f;return{name:N,rate:g,currentValue:h}}return{name:N,rate:0,currentValue:h??0}});o[l]=y}}}catch(c){console.error(`Error fetching metrics for node ${l}:`,c)}})),t.current=n,o},[])}},bc={0:"PartitionUnknown",1:"PartitionPending",2:"PartitionActive",3:"PartitionInactive",4:"PartitionDeleted"};function yc({isPaused:t=!1}={}){const{cluster:s,isLoading:r}=ue(),[a,n]=i.useState({partitions:[],error:"",isLoading:!1}),o=i.useRef(),l=i.useCallback(()=>ja(s==null?void 0:s.members,J.PARTITION_INGESTER),[s]),{fetchMetrics:c}=xc(),d=i.useCallback(async()=>{if(!l()){n(f=>({...f,partitions:[],error:"No cluster members available",isLoading:!1}));return}o.current&&o.current.abort(),o.current=new AbortController;try{n(g=>({...g,isLoading:!0,error:""}));const f=await fetch(l(),{signal:o.current.signal,headers:{Accept:"application/json"}});if(!f.ok)throw new Error(`Failed to fetch partitions: ${f.statusText}`);const N=(await f.json()).partitions.flatMap(g=>g.owner_ids.map(x=>({...g,owner_id:x,owner_ids:[x],zone:Es(x)}))),h=Array.from(new Set(N.map(g=>g.owner_ids).flat().filter(g=>g!==void 0))),p=await c({nodeNames:h,metrics:["loki_ingest_storage_reader_fetch_bytes_total","loki_ingest_storage_reader_fetch_compressed_bytes_total"]});n(g=>({...g,isLoading:!1,partitions:N.map(x=>{var j,w;if(!x.owner_id)return x;const b=p[x.owner_id]||[];return{...x,uncompressedRate:((j=b.find(E=>E.name==="loki_ingest_storage_reader_fetch_bytes_total"))==null?void 0:j.rate)||0,compressedRate:((w=b.find(E=>E.name==="loki_ingest_storage_reader_fetch_compressed_bytes_total"))==null?void 0:w.rate)||0}})}))}catch(f){f instanceof Error&&f.name!=="AbortError"&&n(y=>({...y,error:f instanceof Error?f.message:"Unknown error occurred",isLoading:!1}))}},[l,c]),u=i.useCallback(async(f,y)=>{if(!l())throw new Error("No cluster members available");const N=Array.from(new Set(f)),h=N.length;let p=0;return await Promise.allSettled(N.map(async g=>{const x=new FormData;x.append("action","change_state"),x.append("partition_id",g.toString());const b=bc[y];if(b===void 0)throw new Error(`Invalid partition state: ${y}`);x.append("partition_state",b.toString());const j=await fetch(l(),{method:"POST",body:x});if(!j.ok){const w=await j.text();throw new Error(`Failed to change state for partition ${g}: ${w}`)}return p++,g})),{success:p,total:h}},[l]),m=i.useMemo(()=>{const f=new Set,y=new Set,N={};return a.partitions.forEach(h=>{const p=h.state.toString();N[p]=(N[p]||0)+1,f.add(p),h.owner_ids.forEach(g=>{const x=g.split("-")[2];x&&y.add(x)})}),{partitionsByState:N,uniqueStates:Array.from(f).sort(),uniqueZones:Array.from(y).sort()}},[a.partitions]);return i.useEffect(()=>()=>{o.current&&o.current.abort()},[]),i.useEffect(()=>{if(d(),!t){const f=setInterval(d,5e3);return()=>clearInterval(f)}},[d,t]),{partitions:a.partitions,error:a.error,isLoading:a.isLoading||r,fetchPartitions:d,changePartitionState:u,...m}}function vc(t,s){return t===void 0||s===void 0||Math.abs((t-s)/s)<.1?null:t>s?"up":"down"}function jc({trend:t}){return t?t==="up"?e.jsx($o,{className:"inline h-4 w-4 text-green-500 ml-1"}):e.jsx(Mo,{className:"inline h-4 w-4 text-red-500 ml-1"}):null}function nr({currentRate:t,label:s,className:r}){const a=i.useRef(t),n=i.useMemo(()=>vc(t,a.current),[t]);return i.useEffect(()=>{const o=setTimeout(()=>{a.current=t},2e3);return()=>clearTimeout(o)},[t]),e.jsxs("span",{className:r,children:[Xi(t),"/s",s&&` ${s}`,e.jsx(jc,{trend:n})]})}function wc({allPartitions:t,selectedIds:s,onChange:r}){const a=i.useMemo(()=>Array.from(new Set(t.map(l=>l.id))),[t]),n=a.every(l=>s.has(l)),o=()=>{r(n?new Set:new Set(a))};return e.jsx(Le,{checked:a.length>0&&n,onCheckedChange:o,"aria-label":"Select all partitions"})}function Nc(t){switch(t){case 2:return"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200";case 1:return"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200";case 3:return"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200";case 4:return"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200";default:return"bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"}}const kc=[{value:1,label:"Pending"},{value:2,label:"Active"},{value:3,label:"Inactive"},{value:4,label:"Deleted"}];function Sc({partitions:t,selectedPartitions:s,onSelectPartition:r,sortField:a,sortDirection:n,onSort:o}){const l=i.useMemo(()=>[...t].sort((c,d)=>{var m;let u=0;switch(a){case"uncompressed_rate":{u=(c.uncompressedRate||0)-(d.uncompressedRate||0);break}case"compressed_rate":{u=(c.compressedRate||0)-(d.compressedRate||0);break}case"id":u=c.id-d.id;break;case"state":u=c.state-d.state;break;case"owner":u=((m=c.owner_id)==null?void 0:m.localeCompare(d.owner_id||""))||0;break;case"zone":u=(c.zone||"").localeCompare(d.zone||"");break;case"timestamp":u=new Date(c.state_timestamp).getTime()-new Date(d.state_timestamp).getTime();break}return n==="asc"?u:-u}),[t,a,n]);return e.jsx(e.Fragment,{children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{className:"hover:bg-transparent",children:[e.jsx(D,{className:"w-[50px]",children:e.jsx(wc,{allPartitions:t,selectedIds:s,onChange:c=>{new Set(t.map(u=>u.id)).forEach(u=>{c.has(u)!==s.has(u)&&r(u)})}})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Owner",field:"owner",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"Zone",field:"zone",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[100px]",children:e.jsx(Z,{title:"Partition ID",field:"id",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"State",field:"state",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Last Update",field:"timestamp",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"Uncompressed Rate",field:"uncompressed_rate",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"Compressed Rate",field:"compressed_rate",sortField:a,sortDirection:n,onSort:o})}),e.jsx(D,{className:"w-[100px]"})]})}),e.jsxs(Re,{children:[l.map(c=>{var d;return e.jsxs(X,{children:[e.jsx(F,{children:e.jsx(Le,{checked:s.has(c.id),onCheckedChange:()=>r(c.id),"aria-label":`Select partition ${c.id}`})}),e.jsx(F,{className:"font-medium",children:e.jsx(ce,{to:`/nodes/${c.owner_id}`,className:"hover:underline",children:c.owner_id})}),e.jsx(F,{children:e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",ba(c.zone||"")),children:c.zone||"-"})}),e.jsx(F,{children:e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium",c.corrupted?"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200":"bg-muted"),title:c.corrupted?"Corrupted":void 0,children:c.id})}),e.jsx(F,{children:e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium",Nc(c.state)),children:((d=kc.find(u=>u.value===c.state))==null?void 0:d.label)||"Unknown"})}),e.jsx(F,{children:e.jsx("span",{title:xa(c.state_timestamp),className:"text-muted-foreground",children:ha(c.state_timestamp)})}),e.jsx(F,{children:e.jsx(nr,{currentRate:c.uncompressedRate||0,className:"text-muted-foreground inline-flex items-center"})}),e.jsx(F,{children:e.jsx(nr,{currentRate:c.compressedRate||0,className:"text-muted-foreground inline-flex items-center"})}),e.jsx(F,{children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ce,{to:`/nodes/${c.owner_id}`,className:"hover:underline",children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"View instance details",children:e.jsx(Ft,{className:"h-4 w-4"})})})})})]},`${c.owner_id}-${c.id}`)}),l.length===0&&e.jsx(X,{children:e.jsx(F,{colSpan:7,className:"h-24 text-center",children:e.jsx("div",{className:"text-muted-foreground",children:"No partitions found"})})})]})]})})}const Tt=li,Rt=ci,et=i.forwardRef(({className:t,children:s,...r},a)=>e.jsxs(Fr,{ref:a,className:v("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...r,children:[s,e.jsx(ri,{asChild:!0,children:e.jsx(ot,{className:"h-4 w-4 opacity-50"})})]}));et.displayName=Fr.displayName;const Ka=i.forwardRef(({className:t,...s},r)=>e.jsx(Lr,{ref:r,className:v("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Tr,{className:"h-4 w-4"})}));Ka.displayName=Lr.displayName;const Wa=i.forwardRef(({className:t,...s},r)=>e.jsx(Pr,{ref:r,className:v("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ot,{className:"h-4 w-4"})}));Wa.displayName=Pr.displayName;const tt=i.forwardRef(({className:t,children:s,position:r="popper",...a},n)=>e.jsx(ai,{children:e.jsxs(Dr,{ref:n,className:v("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:r,...a,children:[e.jsx(Ka,{}),e.jsx(ni,{className:v("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(Wa,{})]})}));tt.displayName=Dr.displayName;const Ec=i.forwardRef(({className:t,...s},r)=>e.jsx(Or,{ref:r,className:v("px-2 py-1.5 text-sm font-semibold",t),...s}));Ec.displayName=Or.displayName;const ze=i.forwardRef(({className:t,children:s,...r},a)=>e.jsxs($r,{ref:a,className:v("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...r,children:[e.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(oi,{children:e.jsx(qe,{className:"h-4 w-4"})})}),e.jsx(ii,{children:s})]}));ze.displayName=$r.displayName;const Cc=i.forwardRef(({className:t,...s},r)=>e.jsx(Mr,{ref:r,className:v("-mx-1 my-1 h-px bg-muted",t),...s}));Cc.displayName=Mr.displayName;const Tc=t=>{switch(t){case 2:return"#22c55e";case 1:return"#3b82f6";case 3:return"#eab308";case 4:return"#ef4444";default:return"#6b7280"}};function Rc({partitions:t}){const s=i.useMemo(()=>{const a=new Map;return t.forEach(n=>{const o=n.state;a.set(o,(a.get(o)||0)+1)}),Array.from(a.entries()).sort((n,o)=>o[1]-n[1]).map(([n,o])=>({name:ga[n],value:o,color:Tc(n)}))},[t]),r=i.useMemo(()=>t.length,[t]);return s.length===0?null:e.jsxs("div",{className:"w-full h-[120px] relative",children:[e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center pointer-events-none",children:[e.jsx("div",{className:"text-xl font-bold",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Partitions"})]}),e.jsx(ct,{width:"100%",height:"100%",children:e.jsxs(Dt,{children:[e.jsx(Ot,{data:s,cx:"50%",cy:"50%",labelLine:!1,outerRadius:60,innerRadius:42,dataKey:"value",paddingAngle:1,strokeWidth:1,children:s.map(a=>e.jsx($t,{fill:a.color,stroke:"hsl(var(--background))"},`cell-${a.name}`))}),e.jsx(dt,{content:({active:a,payload:n})=>{if(!a||!n||!n[0])return null;const o=n[0].payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm",style:{backgroundColor:o.color}}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx("span",{className:"text-sm font-semibold",children:o.value})]})}})]})})]})}function Ac({idFilter:t,onIdFilterChange:s,stateFilter:r,onStateFilterChange:a,zoneFilter:n,onZoneFilterChange:o,ownerFilter:l,onOwnerFilterChange:c,uniqueStates:d,partitions:u}){const m=d.map(p=>({value:p,label:ga[parseInt(p)]})),f=new Set;u.forEach(p=>{p.owner_ids.forEach(g=>{const x=Es(g);x&&f.add(x)})});const y=Array.from(f).sort().map(p=>({value:p,label:p})),h=Array.from(new Set(u.map(p=>p.id.toString()))).sort((p,g)=>parseInt(p)-parseInt(g)).map(p=>({value:p,label:`Partition ${p}`}));return e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsx("div",{className:"flex-1 min-w-[200px]",children:e.jsx(xe,{placeholder:"Filter by owner name...",value:l,onChange:p=>c(p.target.value),className:"max-w-sm"})}),e.jsx(Fe,{options:m,selected:r,onChange:a,placeholder:"Filter by state",className:"w-[200px]"}),e.jsx(Fe,{options:y,selected:n,onChange:o,placeholder:"Filter by zone",className:"w-[200px]"}),e.jsx(Fe,{options:h,selected:t,onChange:s,placeholder:"Filter by partition ID",className:"w-[200px]"})]})}const ft=[{value:1,label:"Pending"},{value:2,label:"Active"},{value:3,label:"Inactive"},{value:4,label:"Deleted"}];function _c(){const[t,s]=i.useState(new Set),[r,a]=i.useState("id"),[n,o]=i.useState("asc"),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,f]=i.useState([]),[y,N]=i.useState(""),[h,p]=i.useState(!1),[g,x]=i.useState(),[b,j]=i.useState(!1),{toast:w}=zt(),{partitions:E,error:C,isLoading:A,fetchPartitions:B,changePartitionState:z,uniqueStates:Y,uniqueZones:K}=yc({isPaused:t.size>0}),M=i.useMemo(()=>E.flatMap(I=>I.owner_ids.map(P=>({...I,owner_id:P,owner_ids:[P],zone:Es(P)}))),[E]),W=i.useCallback(I=>{a(P=>P===I?(o(U=>U==="asc"?"desc":"asc"),I):(o("asc"),I))},[]),T=i.useCallback(I=>{s(P=>{const U=new Set(P);return U.has(I)?U.delete(I):U.add(I),U})},[]),O=i.useMemo(()=>M.filter(I=>{const P=l.length===0||l.includes(I.id.toString()),U=d.length===0||d.includes(I.state.toString()),S=m.length===0||m.includes(I.zone),R=y?I.owner_id.toLowerCase().includes(y.toLowerCase()):!0;return P&&U&&S&&R}),[M,l,d,m,y]),V=i.useMemo(()=>M.filter(I=>t.has(I.id)),[M,t]),Q=i.useCallback(async()=>{var I;if(!(t.size===0||!g))try{p(!0);const P=parseInt(g,10),{success:U,total:S}=await z(V.map(R=>R.id),g);U>0&&S===U?(w({title:"State Change Success",description:`Successfully changed state for ${U} partition${U!==1?"s":""} to ${(I=ft.find(R=>R.value===P))==null?void 0:I.label}`}),await B()):U<S&&w({title:"State Change Failed",variant:"destructive",description:`Failed to change state for ${S-U} partition${S-U!==1?"s":""}.`}),s(new Set),x(void 0)}catch{w({title:"Error",description:"An unexpected error occurred while changing partition states."})}finally{p(!1),j(!1)}},[t,g,V,z,B,w]),_={partitions:O,selectedPartitions:t,onSelectPartition:T,sortField:r,sortDirection:n,onSort:W,onStateChange:Q};return C?e.jsx(Ds,{error:C,ringName:"partition-ingester"}):e.jsxs("div",{className:"container space-y-6 p-6",children:[e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-8",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx(ae,{className:"text-3xl font-semibold tracking-tight",children:"Partition Ring Members"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View and manage partition ring instances with their current status and configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between min-h-[32px]",children:[e.jsx(Ha,{onRefresh:B,isPaused:t.size>0,isLoading:A}),t.size>0&&e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[t.size," partition",t.size!==1?"s":""," selected"]}),e.jsxs(Tt,{value:g,onValueChange:x,children:[e.jsx(et,{className:"w-[160px]",children:e.jsx(Rt,{placeholder:"Select new state"})}),e.jsx(tt,{children:ft.map(I=>e.jsx(ze,{value:I.value.toString(),children:I.label},I.value))})]}),e.jsxs(q,{onClick:()=>j(!0),disabled:h||!g,size:"sm",variant:"outline",children:[h&&e.jsx(he,{className:"mr-2 h-4 w-4 animate-spin"}),"Change State"]})]})]})]}),e.jsx("div",{className:"flex items-center",children:e.jsx("div",{className:"w-[250px]",children:e.jsx(Rc,{partitions:E})})})]})}),e.jsxs(te,{className:"space-y-6",children:[e.jsx(Ac,{idFilter:l,onIdFilterChange:c,stateFilter:d,onStateFilterChange:u,zoneFilter:m,onZoneFilterChange:f,ownerFilter:y,onOwnerFilterChange:N,uniqueStates:Y,uniqueZones:K,partitions:E}),e.jsx("div",{className:"rounded-md border bg-card",children:e.jsx(Sc,{..._})})]})]}),e.jsx(Ma,{open:b,onOpenChange:j,children:e.jsxs(_s,{children:[e.jsxs(Is,{children:[e.jsx(Ls,{children:"Confirm State Change"}),e.jsx(Ps,{children:"Are you sure you want to change the state of these partitions?"})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto",children:e.jsx("div",{className:"space-y-2",children:Array.from(new Set(V.map(I=>I.id))).map(I=>{var U,S;const P=E.find(R=>R.id===I);return P?e.jsx("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:["Partition ",I]}),e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium",Et(P.state)),children:(U=ft.find(R=>R.value===P.state))==null?void 0:U.label}),e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:v("inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium",Et(parseInt(g||"0",10))),children:(S=ft.find(R=>R.value===parseInt(g,10)))==null?void 0:S.label})]})},I):null})})}),e.jsxs(Fs,{children:[e.jsx(q,{variant:"outline",onClick:()=>j(!1),disabled:h,children:"Cancel"}),e.jsx(q,{onClick:Q,disabled:h,children:h?"Changing States...":"Confirm Changes"})]})]})})]})}function or(){const{ringName:t}=Nr(),s=Object.values(J).includes(t);return!t||!s?e.jsx(Ds,{}):t===J.PARTITION_INGESTER?e.jsx(_c,{}):e.jsx(hc,{ringName:t})}const pt=i.forwardRef(({className:t,children:s,...r},a)=>e.jsxs(Jr,{ref:a,className:v("relative overflow-hidden",t),...r,children:[e.jsx(gi,{className:"h-full w-full rounded-[inherit]",children:s}),e.jsx(Za,{}),e.jsx(fi,{})]}));pt.displayName=Jr.displayName;const Za=i.forwardRef(({className:t,orientation:s="vertical",...r},a)=>e.jsx(ea,{ref:a,orientation:s,className:v("flex touch-none select-none transition-colors",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:e.jsx(hi,{className:"relative flex-1 rounded-full bg-border"})}));Za.displayName=ea.displayName;const Vt=yi,Ut=vi,mt=i.forwardRef(({className:t,align:s="center",sideOffset:r=4,...a},n)=>e.jsx(na,{ref:n,align:s,sideOffset:r,className:v("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));mt.displayName=na.displayName;const Os=({date:t,className:s=""})=>{const r=_r(t,{addSuffix:!0}),a=wt(t,"yyyy-MM-dd HH:mm:ss"),n=wt(new Date(t.getTime()+t.getTimezoneOffset()*6e4),"yyyy-MM-dd HH:mm:ss");return e.jsxs(Vt,{children:[e.jsx(Ut,{children:e.jsx("div",{className:`inline-block ${s}`,children:r})}),e.jsx(mt,{className:"w-[280px]",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"UTC"}),e.jsx("span",{className:"font-mono",children:n})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"Local"}),e.jsx("span",{className:"font-mono",children:a})]})]})})]})};function Ic({current:t,parent:s,files:r,folders:a}){const n=It(),[,o]=at(),l=d=>{o({path:d})},c=d=>{n(`/storage/dataobj/metadata?path=${encodeURIComponent(t+"/"+d.name)}`)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{className:"h-12",children:[e.jsx(D,{children:"Name"}),e.jsx(D,{children:"Modified"}),e.jsx(D,{children:"Size"}),e.jsx(D,{})]})}),e.jsxs(Re,{children:[s!==t&&e.jsxs(X,{className:"h-12 cursor-pointer hover:bg-muted/50",onClick:()=>l(s||""),children:[e.jsx(F,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M15 19l-7-7 7-7"})}),".."]})}),e.jsx(F,{children:"-"}),e.jsx(F,{children:"-"}),e.jsx(F,{})]},"parent"),a.map(d=>e.jsxs(X,{className:"h-12 cursor-pointer hover:bg-muted/50",onClick:()=>l(t?`${t}/${d}`:d),children:[e.jsx(F,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Bo,{className:"mr-2 h-4 w-4"}),d]})}),e.jsx(F,{children:"-"}),e.jsx(F,{children:"-"}),e.jsx(F,{})]},d)),r.map(d=>e.jsxs(X,{className:"h-12 cursor-pointer hover:bg-muted/50",onClick:u=>{u.target.closest("a[download]")||c(d)},children:[e.jsx(F,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(zo,{className:"mr-2 h-4 w-4"}),d.name]})}),e.jsx(F,{children:e.jsx(Os,{date:new Date(d.lastModified)})}),e.jsx(F,{children:me(d.size)}),e.jsx(F,{children:e.jsx(q,{variant:"outline",size:"icon",asChild:!0,className:"h-8 w-8",children:e.jsx(ce,{to:d.downloadUrl,target:"_blank",download:!0,onClick:u=>u.stopPropagation(),children:e.jsx(Rr,{className:"h-4 w-4"})})})})]},d.name))]})]})})}function Fc(t){const{cluster:s}=ue(),r=i.useMemo(()=>Oe(s==null?void 0:s.members,"dataobj-explorer"),[s==null?void 0:s.members]);return Mt({queryKey:["explorer",t,r],queryFn:async()=>{if(!r)throw new Error("Node name not found");const a=await fetch(`/ui/api/v1/proxy/${r}/dataobj/api/v1/list?path=${encodeURIComponent(t)}`);if(!a.ok)throw new Error("Failed to fetch explorer data");const n=await a.json();return{...n,files:Lc(n.files).map(o=>({...o,downloadUrl:`/api/v1/proxy/${r}/dataobj/api/v1/download?file=${encodeURIComponent(t?`${t}/${o.name}`:o.name)}`}))}}})}const Lc=t=>[...t].sort((s,r)=>new Date(r.lastModified).getTime()-new Date(s.lastModified).getTime()),Pc=t=>{switch(t){case"S3":return{bg:"bg-orange-100",text:"text-orange-800",darkBg:"dark:bg-orange-900",darkText:"dark:text-orange-300"};case"GCS":return{bg:"bg-blue-100",text:"text-blue-800",darkBg:"dark:bg-blue-900",darkText:"dark:text-blue-300"};case"AZURE":return{bg:"bg-sky-100",text:"text-sky-800",darkBg:"dark:bg-sky-900",darkText:"dark:text-sky-300"};case"SWIFT":return{bg:"bg-red-100",text:"text-red-800",darkBg:"dark:bg-red-900",darkText:"dark:text-red-300"};case"COS":return{bg:"bg-purple-100",text:"text-purple-800",darkBg:"dark:bg-purple-900",darkText:"dark:text-purple-300"};case"ALIYUNOSS":return{bg:"bg-rose-100",text:"text-rose-800",darkBg:"dark:bg-rose-900",darkText:"dark:text-rose-300"};case"OCI":return{bg:"bg-red-100",text:"text-red-800",darkBg:"dark:bg-red-900",darkText:"dark:text-red-300"};case"OBS":return{bg:"bg-cyan-100",text:"text-cyan-800",darkBg:"dark:bg-cyan-900",darkText:"dark:text-cyan-300"};case"FILESYSTEM":return{bg:"bg-green-100",text:"text-green-800",darkBg:"dark:bg-green-900",darkText:"dark:text-green-300"};case"MEMORY":return{bg:"bg-yellow-100",text:"text-yellow-800",darkBg:"dark:bg-yellow-900",darkText:"dark:text-yellow-300"};default:return{bg:"bg-gray-100",text:"text-gray-800",darkBg:"dark:bg-gray-700",darkText:"dark:text-gray-300"}}};function Ya(){const[t,s]=Be.useState(""),{cluster:r}=ue(),a=i.useMemo(()=>Oe(r==null?void 0:r.members,"dataobj-explorer"),[r==null?void 0:r.members]);Be.useEffect(()=>{a&&fetch(`/ui/api/v1/proxy/${a}/dataobj/api/v1/provider`).then(d=>d.json()).then(d=>s(d.provider)).catch(console.error)},[a]);const[n]=at(),l=(n.get("path")||"").split("/").filter(Boolean),c=Pc(t);return e.jsx(ks,{children:e.jsxs(Ss,{children:[e.jsx(Nt,{children:e.jsx(kt,{asChild:!0,children:e.jsxs(ce,{to:"/storage/dataobj",className:`inline-flex items-center h-7 gap-2 px-3 py-1 text-xs font-medium ${c.bg} ${c.text} ${c.darkBg} ${c.darkText} rounded-full hover:ring-1 hover:ring-gray-300 dark:hover:ring-gray-600 transition-all duration-200`,children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",className:"w-4 h-4",fill:"currentColor",children:e.jsx("path",{d:"M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z"})}),t||""]})})}),l.length>0&&e.jsx(St,{}),l.map((d,u)=>{const m=l.slice(0,u+1).join("/"),f=u===l.length-1;return e.jsxs(Be.Fragment,{children:[e.jsx(Nt,{children:e.jsx(kt,{asChild:!0,children:f?e.jsx("span",{className:"text-gray-500",children:d}):e.jsx(ce,{to:`/storage/dataobj?path=${encodeURIComponent(m)}`,children:d})})}),u<l.length-1&&e.jsx(St,{})]},m)})]})})}function Dc(){const[t]=at(),s=t.get("path")||"",{data:r,isLoading:a,error:n}=Fc(s);return e.jsx(ke,{children:e.jsxs("div",{className:"flex h-full flex-col space-y-6",children:[e.jsx(Ya,{}),e.jsx(pt,{className:"h-full",children:e.jsx("div",{className:"grid gap-4",children:e.jsxs(ee,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:e.jsx("h2",{className:"text-3xl font-semibold tracking-tight",children:"Data Objects Explorer"})}),e.jsx(Qe,{children:e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The Data Objects Explorer allows you to explore the data objects in the cluster."})})]}),e.jsx(te,{children:a?e.jsx("div",{className:"flex items-center justify-center p-8",children:"Loading..."}):n?e.jsx("div",{className:"flex items-center justify-center p-8 text-destructive",children:n.message}):r?e.jsx(Ic,{current:r.current,parent:r.parent,files:r.files,folders:r.folders}):null})]})})})]})})}const Oc=Ee("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function be({className:t,variant:s,...r}){return e.jsx("div",{className:v(Oc({variant:s}),t),...r})}function $s({text:t,className:s,onCopy:r}){const[a,n]=i.useState(!1),o=()=>{navigator.clipboard.writeText(t).then(()=>{n(!0),r==null||r(),setTimeout(()=>n(!1),2e3)})};return e.jsx(q,{variant:"ghost",size:"sm",onClick:o,className:v("h-8 px-2",s),children:a?e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-4 w-4 mr-1"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ar,{className:"h-4 w-4 mr-1"}),"Copy"]})})}const qt=({compressed:t,uncompressed:s,showVisualization:r=!1})=>{if(t===0||s===0)return e.jsx("span",{className:"dark:text-gray-200",children:"-"});const a=s/t,n=a>1;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"font-medium whitespace-nowrap dark:text-gray-200",children:[a.toFixed(1),"x"]}),r&&n&&e.jsx("div",{className:"flex-1 h-2.5 bg-gray-100 dark:bg-gray-600 border border-gray-200 dark:border-gray-500 rounded relative",children:e.jsx("div",{className:"absolute inset-y-0 left-0 bg-blue-600 dark:bg-blue-500 rounded",style:{width:`${t/s*100}%`}})})]})},$c=t=>{switch(t){case"INT64":return"bg-blue-500/20 text-blue-700 dark:bg-blue-500/30 dark:text-blue-300 hover:bg-blue-500/30";case"BYTES":return"bg-red-500/20 text-red-700 dark:bg-red-500/30 dark:text-red-300 hover:bg-red-500/30";case"FLOAT64":return"bg-purple-500/20 text-purple-700 dark:bg-purple-500/30 dark:text-purple-300 hover:bg-purple-500/30";case"BOOL":return"bg-yellow-500/20 text-yellow-700 dark:bg-yellow-500/30 dark:text-yellow-300 hover:bg-yellow-500/30";case"STRING":return"bg-green-500/20 text-green-700 dark:bg-green-500/30 dark:text-green-300 hover:bg-green-500/30";case"TIMESTAMP":return"bg-orange-500/20 text-orange-700 dark:bg-orange-500/30 dark:text-orange-300 hover:bg-orange-500/30";default:return"bg-gray-500/20 text-gray-700 dark:bg-gray-500/30 dark:text-gray-300 hover:bg-gray-500/30"}};function Mc({metadata:t,filename:s,downloadUrl:r}){const[a,n]=i.useState(null),[o,l]=i.useState({}),c=p=>{n(a===p?null:p)},d=(p,g)=>{const x=`${p}-${g}`;l(b=>({...b,[x]:!b[x]}))},u=t.sections.reduce((p,g)=>p+g.totalCompressedSize,0),m=t.sections.reduce((p,g)=>p+g.totalUncompressedSize,0),f=t.sections.filter(p=>p.type==="SECTION_TYPE_STREAMS"),y=t.sections.filter(p=>p.type==="SECTION_TYPE_LOGS"),N=f==null?void 0:f.reduce((p,g)=>p+(g.columns[0].rows_count||0),0),h=y==null?void 0:y.reduce((p,g)=>p+(g.columns[0].rows_count||0),0);return e.jsxs(ee,{className:"w-full",children:[e.jsx(Bc,{filename:s,downloadUrl:r,lastModified:t.lastModified}),e.jsxs(te,{className:"space-y-8",children:[e.jsx(zc,{totalCompressed:u,totalUncompressed:m,sections:t.sections,streamCount:N,logCount:h}),e.jsx(Vc,{sections:t.sections,expandedSectionIndex:a,expandedColumns:o,onToggleSection:c,onToggleColumn:d})]})]})}function Bc({filename:t,downloadUrl:s,lastModified:r}){return e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ae,{className:"text-2xl font-semibold tracking-tight",children:"Thor Dataobj File"}),e.jsx(q,{asChild:!0,variant:"outline",children:e.jsxs(ce,{to:s,target:"_blank",download:!0,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Download"]})})]}),e.jsx(Qe,{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm text-foreground",children:t}),e.jsx($s,{text:t})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:"Last Modified:"}),e.jsx(Os,{date:new Date(r)})]})]})})})]})}function zc({totalCompressed:t,totalUncompressed:s,sections:r,streamCount:a,logCount:n}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsxs("div",{className:"rounded-lg bg-muted/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Compression"}),e.jsx(qt,{compressed:t,uncompressed:s,showVisualization:!0}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2",children:[me(t)," → ",me(s)]})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Sections"}),e.jsx("div",{className:"font-medium text-lg",children:r.length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:r.map(o=>o.type).join(", ")})]}),a&&e.jsxs("div",{className:"rounded-lg bg-muted/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Stream Count"}),e.jsx("div",{className:"font-medium text-lg",children:a.toLocaleString()})]}),n&&e.jsxs("div",{className:"rounded-lg bg-muted/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Log Count"}),e.jsx("div",{className:"font-medium text-lg",children:n.toLocaleString()})]})]})}function Vc({sections:t,expandedSectionIndex:s,expandedColumns:r,onToggleSection:a,onToggleColumn:n}){return e.jsx("div",{className:"divide-y divide-border",children:t.map((o,l)=>e.jsx(Uc,{section:o,sectionIndex:l,isExpanded:s===l,expandedColumns:r,onToggle:()=>a(l),onToggleColumn:c=>n(l,c)},l))})}function Uc({section:t,sectionIndex:s,isExpanded:r,expandedColumns:a,onToggle:n,onToggleColumn:o}){return e.jsxs("div",{className:"py-4",children:[e.jsxs("button",{className:"w-full flex justify-between items-center py-4 px-6 rounded-lg hover:bg-accent/50 transition-colors",onClick:n,children:[e.jsxs("h3",{className:"text-lg font-semibold",children:["Section #",s+1,": ",t.type]}),e.jsx("svg",{className:`w-5 h-5 transform transition-transform duration-300 ${r?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]}),r&&e.jsxs("div",{className:"mt-6 px-6",children:[e.jsx(qc,{section:t}),e.jsx(Gc,{columns:t.columns,sectionIndex:s,expandedColumns:a,onToggleColumn:o})]})]})}function qc({section:t}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-8",children:[e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Compression"}),e.jsx(qt,{compressed:t.totalCompressedSize,uncompressed:t.totalUncompressedSize,showVisualization:!0}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2",children:[me(t.totalCompressedSize)," →"," ",me(t.totalUncompressedSize)]})]}),e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Column Count"}),e.jsx("div",{className:"font-medium text-lg",children:t.columnCount})]}),e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-6 shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Type"}),e.jsx("div",{className:"font-medium text-lg flex items-center gap-2",children:e.jsx(be,{variant:"outline",className:"font-mono",children:t.type})})]})]})}function Gc({columns:t,sectionIndex:s,expandedColumns:r,onToggleColumn:a}){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("h4",{className:"text-lg font-medium",children:["Columns (",t.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.map((n,o)=>e.jsx(Hc,{column:n,isExpanded:r[`${s}-${o}`],onToggle:()=>a(o)},o))})]})}function Hc({column:t,isExpanded:s,onToggle:r}){return e.jsxs(ee,{className:"bg-card/50",children:[e.jsxs("button",{className:"w-full flex justify-between items-center p-6 hover:bg-accent/50 transition-colors rounded-t-lg",onClick:r,children:[e.jsxs("div",{children:[e.jsx("h5",{className:"font-medium text-lg",children:t.name?`${t.name} (${t.type})`:t.type}),e.jsx("div",{className:"text-sm text-muted-foreground mt-1 flex items-center gap-2",children:e.jsx(be,{variant:"secondary",className:v("font-mono text-xs",$c(t.value_type)),children:t.value_type})})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:["Compression:",e.jsx(be,{variant:"outline",className:"font-mono",children:t.compression||"NONE"})]}),e.jsx("svg",{className:`w-4 h-4 transform transition-transform ${s?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})]})]}),s&&e.jsxs(te,{className:"pt-6",children:[e.jsx(Kc,{column:t}),t.pages.length>0&&e.jsx(Wc,{pages:t.pages})]})]})}function Kc({column:t}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-6 mb-8",children:[e.jsxs("div",{className:"rounded-lg bg-muted p-6",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2 flex items-center gap-2",children:e.jsx(be,{variant:"outline",className:"font-mono",children:t.compression||"NONE"})}),e.jsx("div",{className:"font-medium",children:e.jsx(qt,{compressed:t.compressed_size,uncompressed:t.uncompressed_size})}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2",children:[me(t.compressed_size)," →"," ",me(t.uncompressed_size)]})]}),e.jsxs("div",{className:"rounded-lg bg-muted p-6",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Rows"}),e.jsx("div",{className:"font-medium text-lg",children:t.rows_count.toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg bg-muted p-6",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Values Count"}),e.jsx("div",{className:"font-medium text-lg",children:t.values_count.toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg bg-muted p-6",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"Offset"}),e.jsx("div",{className:"font-medium text-lg",children:me(t.metadata_offset)})]})]})}function Wc({pages:t}){return e.jsxs("div",{className:"mt-8",children:[e.jsxs("h6",{className:"text-base font-medium mb-4",children:["Pages (",t.length,")"]}),e.jsx("div",{className:"rounded-lg border border-border overflow-hidden bg-background",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-secondary/50 border-b border-border",children:[e.jsx("th",{className:"text-left p-4 font-medium text-muted-foreground",children:"#"}),e.jsx("th",{className:"text-left p-4 font-medium text-muted-foreground",children:"Rows"}),e.jsx("th",{className:"text-left p-4 font-medium text-muted-foreground",children:"Values"}),e.jsx("th",{className:"text-left p-4 font-medium text-muted-foreground",children:"Encoding"}),e.jsx("th",{className:"text-left p-4 font-medium text-muted-foreground",children:"Compression"})]})}),e.jsx("tbody",{children:t.map((s,r)=>e.jsxs("tr",{className:"border-t border-border hover:bg-accent/50 transition-colors",children:[e.jsx("td",{className:"p-4",children:r+1}),e.jsx("td",{className:"p-4",children:s.rows_count.toLocaleString()}),e.jsx("td",{className:"p-4",children:s.values_count.toLocaleString()}),e.jsx("td",{className:"p-4",children:e.jsx(be,{variant:"outline",className:"font-mono",children:s.encoding})}),e.jsx("td",{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{compressed:s.compressed_size,uncompressed:s.uncompressed_size}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",me(s.compressed_size)," →"," ",me(s.uncompressed_size),")"]})]})})]},r))})]})})]})}function Zc(t){const{cluster:s}=ue(),r=i.useMemo(()=>Oe(s==null?void 0:s.members,"dataobj-explorer"),[s==null?void 0:s.members]),a=i.useMemo(()=>`/api/v1/proxy/${r}/dataobj/api/v1/download?file=${encodeURIComponent(t||"")}`,[t,r]);return{...Mt({queryKey:["file-metadata",t,r],queryFn:async()=>{if(!t)throw new Error("No file path provided");if(!r)throw new Error("Node name not found");const o=await fetch(`/ui/api/v1/proxy/${r}/dataobj/api/v1/inspect?file=${encodeURIComponent(t)}`);if(!o.ok)throw new Error("Failed to fetch file metadata");return o.json()},enabled:!!t&&!!r}),downloadUrl:a}}function Yc(){const[t]=at(),s=t.get("path")||"",{data:r,downloadUrl:a,isLoading:n,error:o}=Zc(s);return e.jsx(ke,{children:e.jsxs("div",{className:"flex h-full flex-col space-y-6",children:[e.jsx(Ya,{}),e.jsx(pt,{className:"h-full",children:n?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(he,{className:"h-16 w-16 animate-spin"})}):o?e.jsxs(Ge,{variant:"destructive",children:[e.jsx(He,{children:"Error"}),e.jsx(Ke,{children:o.message})]}):r&&s?e.jsx(Mc,{metadata:r,filename:s,downloadUrl:a}):null})]})})}const Xc=["New","Starting","Running","Stopping","Terminated","Failed"],Qc=({nameFilter:t,targetFilter:s,selectedStates:r,onNameFilterChange:a,onTargetFilterChange:n,onStatesChange:o,onRefresh:l,availableTargets:c})=>{const d=Xc.map(m=>({label:m,value:m})),u=m=>{o(m)};return e.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto] gap-x-4 gap-y-2",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Node filters"}),e.jsx(xe,{value:t,onChange:m=>a(m.target.value),placeholder:"Filter by node name...",className:"w-[300px]"}),e.jsx(Fe,{options:c.map(m=>({value:m,label:m})),selected:s,onChange:n,placeholder:"All Targets",className:"w-[300px]"})]})}),e.jsxs("div",{className:"space-y-1.5 self-end",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Service states"}),e.jsx(Fe,{options:d,selected:r,onChange:u,placeholder:"Filter nodes by service states...",className:"w-full min-w-[300px]"})]}),e.jsx("div",{className:"self-end",children:e.jsx(q,{onClick:l,size:"sm",variant:"outline",className:"h-9 w-9",children:e.jsx(Vo,{className:"h-4 w-4"})})})]})},Jc=({services:t,error:s})=>{const r=()=>{if(s)return{className:"bg-red-500 dark:bg-red-500/80 hover:bg-red-600 dark:hover:bg-red-500 text-white border-transparent",tooltip:`Error: ${s}`,status:"error"};const o=t.every(c=>c.status==="Running"),l=t.every(c=>c.status==="Starting"||c.status==="Running");return o?{className:"bg-green-500 dark:bg-green-500/80 hover:bg-green-600 dark:hover:bg-green-500 text-white border-transparent",status:"healthy"}:l?{className:"bg-yellow-500 dark:bg-yellow-500/80 hover:bg-yellow-600 dark:hover:bg-yellow-500 text-white border-transparent",status:"pending"}:{className:"bg-red-500 dark:bg-red-500/80 hover:bg-red-600 dark:hover:bg-red-500 text-white border-transparent",status:"unhealthy"}},a=o=>{switch(o){case"Running":return"text-green-600 dark:text-green-400";case"Starting":return"text-yellow-600 dark:text-yellow-400";case"Failed":return"text-red-600 dark:text-red-400";case"Terminated":return"text-gray-600 dark:text-gray-400";case"Stopping":return"text-orange-600 dark:text-orange-400";case"New":return"text-blue-600 dark:text-blue-400";default:return"text-gray-600 dark:text-gray-400"}},{className:n}=r();return e.jsxs(Vt,{children:[e.jsx(Ut,{children:e.jsx("button",{type:"button",children:e.jsxs(be,{className:n,children:[t.length," services"]})})}),e.jsx(mt,{className:"w-80 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",sideOffset:5,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"font-medium border-b border-gray-200 dark:border-gray-700 pb-1",children:"Service Status"}),e.jsx("div",{className:"space-y-1",children:t.map((o,l)=>e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"mr-4 font-medium",children:o.service}),e.jsx("span",{className:`${a(o.status)}`,children:o.status})]},l))}),s&&e.jsx("div",{className:"mt-2 pt-2 border-t border-gray-200 dark:border-gray-700 text-red-600 dark:text-red-400",children:s})]})})]})},Ms=fo,st=ho,rt=xo,Ue=i.forwardRef(({className:t,sideOffset:s=4,...r},a)=>e.jsx(go,{children:e.jsx(br,{ref:a,sideOffset:s,className:v("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));Ue.displayName=br.displayName;function ed({isReady:t,message:s,className:r}){return e.jsx(Ms,{children:e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx("div",{className:v("flex items-center gap-2",r),children:e.jsx("div",{className:v("h-2.5 w-2.5 rounded-full",t?"bg-green-500":"bg-red-500")})})}),e.jsx(Ue,{children:e.jsx("p",{className:"text-sm",children:s||(t?"Ready":"Not Ready")})})]})})}const td=t=>{try{const s=cs(t);return Ze(s)?_r(s,{addSuffix:!0}):"Invalid date"}catch(s){return console.warn("Error parsing date:",t,s),"Invalid date"}},sd=({name:t,node:s,onNavigate:r})=>{var a,n;return e.jsxs(X,{className:"hover:bg-muted/50 cursor-pointer",onClick:()=>r(t),children:[e.jsx(F,{className:"font-medium",children:t}),e.jsx(F,{children:s.target}),e.jsx(F,{className:"font-mono text-sm",children:s.build.version}),e.jsx(F,{children:td(s.build.buildDate)}),e.jsx(F,{children:e.jsx(Jc,{services:s.services,error:s.error})}),e.jsx(F,{children:e.jsx(ed,{isReady:(a=s.ready)==null?void 0:a.isReady,message:(n=s.ready)==null?void 0:n.message})}),e.jsx(F,{children:e.jsxs(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:o=>{o.stopPropagation(),r(t)},children:[e.jsx(Ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"View details"})]})})]},t)},rd=({nodes:t,sortField:s,sortDirection:r,onSort:a})=>{const n=It(),o=(d,u)=>{const m=cs(d),f=cs(u);return!Ze(m)&&!Ze(f)?0:Ze(m)?Ze(f)?m.getTime()-f.getTime():-1:1},l=Object.entries(t).sort(([d,u],[m,f])=>{let y=0;switch(s){case"name":y=d.localeCompare(m);break;case"target":y=u.target.localeCompare(f.target);break;case"version":y=u.build.version.localeCompare(f.build.version);break;case"buildDate":y=o(u.build.buildDate,f.build.buildDate);break}return r==="asc"?y:-y}),c=d=>{n(`/nodes/${d}`)};return e.jsx("div",{className:"rounded-md border bg-card",children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{className:"hover:bg-transparent",children:[e.jsx(D,{className:"w-[300px]",children:e.jsx(Z,{title:"Node Name",field:"name",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Target",field:"target",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Version",field:"version",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Build Date",field:"buildDate",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[150px]",children:"Status"}),e.jsx(D,{className:"w-[50px]",children:"Ready"}),e.jsx(D,{className:"w-[100px]",children:"Actions"})]})}),e.jsxs(Re,{children:[l.map(([d,u])=>e.jsx(sd,{name:d,node:u,onNavigate:c},d)),l.length===0&&e.jsx(X,{children:e.jsx(F,{colSpan:7,className:"h-24 text-center",children:e.jsx("div",{className:"text-muted-foreground",children:"No nodes found"})})})]})]})})},ir=t=>`hsl(var(--chart-${t%6+1}))`;function ad({nodes:t}){const s=i.useMemo(()=>{const a=new Map;return Object.values(t).forEach(n=>{const o=n.target||"unknown";a.set(o,(a.get(o)||0)+1)}),Array.from(a.entries()).sort((n,o)=>o[1]-n[1]).map(([n,o],l)=>({name:n,value:o,color:ir(l)}))},[t]),r=i.useMemo(()=>Object.keys(t).length,[t]);return s.length===0?null:e.jsxs("div",{className:"w-full h-[120px] relative",children:[e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center pointer-events-none",children:[e.jsx("div",{className:"text-xl font-bold",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nodes"})]}),e.jsx(ct,{width:"100%",height:"100%",children:e.jsxs(Dt,{children:[e.jsx(Ot,{data:s,cx:"50%",cy:"50%",labelLine:!1,outerRadius:60,innerRadius:42,fill:"hsl(var(--chart-1))",dataKey:"value",paddingAngle:1,strokeWidth:1,children:s.map((a,n)=>e.jsx($t,{fill:ir(n),stroke:"hsl(var(--background))"},`cell-${a.name}`))}),e.jsx(dt,{content:({active:a,payload:n})=>{if(!a||!n||!n[0])return null;const o=n[0].payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm",style:{backgroundColor:o.color}}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx("span",{className:"text-sm font-semibold",children:o.value})]})}})]})})]})}class Xa extends Be.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",children:e.jsxs("div",{className:"bg-destructive/10 p-6 rounded-lg max-w-2xl w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-destructive mb-4",children:"Something went wrong"}),e.jsx("div",{className:"bg-background/50 p-4 rounded-md",children:e.jsx("pre",{className:"text-sm overflow-auto",children:(s=this.state.error)==null?void 0:s.message})}),e.jsx("button",{className:"mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90",onClick:()=>window.location.reload(),children:"Reload Page"})]})}):this.props.children}}const nd=()=>{const{cluster:t,error:s,refresh:r,isLoading:a}=ue(),[n,o]=i.useState(""),[l,c]=i.useState([]),[d,u]=i.useState(["New","Starting","Running","Stopping","Terminated","Failed"]),[m,f]=i.useState("name"),[y,N]=i.useState("asc"),h=x=>{x===m?N(y==="asc"?"desc":"asc"):(f(x),N("asc"))},p=()=>t?Object.entries(t.members).reduce((x,[b,j])=>{const w=b.toLowerCase().includes(n.toLowerCase()),E=!l||l.length===0||l.includes(j.target),C=d.length===0||j.services&&Array.isArray(j.services)&&j.services.some(A=>(A==null?void 0:A.status)&&d.includes(A.status));return w&&E&&C&&(x[b]=j),x},{}):{},g=()=>{if(!t)return[];const x=new Set;return Object.values(t.members).forEach(b=>{b.target&&x.add(b.target)}),Array.from(x).sort()};return e.jsx(ke,{children:e.jsxs(ee,{className:"shadow-sm",children:[e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-8",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-semibold tracking-tight",children:"Nodes"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View and manage Loki nodes in your cluster with their current status and configuration"})]}),e.jsx(Qc,{nameFilter:n,targetFilter:l,selectedStates:d,onNameFilterChange:o,onTargetFilterChange:c,onStatesChange:u,onRefresh:r,availableTargets:g(),isLoading:a})]}),e.jsx("div",{className:"flex items-center",children:e.jsx("div",{className:"w-[250px]",children:e.jsx(ad,{nodes:p()})})})]})}),e.jsx(te,{children:e.jsxs("div",{className:"space-y-4",children:[s&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(nt,{className:"h-4 w-4"}),e.jsx(He,{children:"Error"}),e.jsx(Ke,{children:s})]}),a&&e.jsxs("div",{className:"flex items-center justify-center py-4",children:[e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading..."})]}),!a&&!s&&e.jsx(rd,{nodes:p(),sortField:m,sortDirection:y,onSort:h})]})})]})})};function lr(){return e.jsx(Xa,{children:e.jsx(nd,{})})}const od=xi,Qa=i.forwardRef(({className:t,...s},r)=>e.jsx(ta,{ref:r,className:v("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...s}));Qa.displayName=ta.displayName;const yt=i.forwardRef(({className:t,...s},r)=>e.jsx(sa,{ref:r,className:v("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",t),...s}));yt.displayName=sa.displayName;const vt=i.forwardRef(({className:t,...s},r)=>e.jsx(ra,{ref:r,className:v("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));vt.displayName=ra.displayName;var id=Object.create,Gt=Object.defineProperty,ld=Object.defineProperties,cd=Object.getOwnPropertyDescriptor,dd=Object.getOwnPropertyDescriptors,Ja=Object.getOwnPropertyNames,At=Object.getOwnPropertySymbols,ud=Object.getPrototypeOf,Bs=Object.prototype.hasOwnProperty,en=Object.prototype.propertyIsEnumerable,cr=(t,s,r)=>s in t?Gt(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r,ge=(t,s)=>{for(var r in s||(s={}))Bs.call(s,r)&&cr(t,r,s[r]);if(At)for(var r of At(s))en.call(s,r)&&cr(t,r,s[r]);return t},Ht=(t,s)=>ld(t,dd(s)),tn=(t,s)=>{var r={};for(var a in t)Bs.call(t,a)&&s.indexOf(a)<0&&(r[a]=t[a]);if(t!=null&&At)for(var a of At(t))s.indexOf(a)<0&&en.call(t,a)&&(r[a]=t[a]);return r},pd=(t,s)=>function(){return s||(0,t[Ja(t)[0]])((s={exports:{}}).exports,s),s.exports},md=(t,s)=>{for(var r in s)Gt(t,r,{get:s[r],enumerable:!0})},gd=(t,s,r,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ja(s))!Bs.call(t,n)&&n!==r&&Gt(t,n,{get:()=>s[n],enumerable:!(a=cd(s,n))||a.enumerable});return t},fd=(t,s,r)=>(r=t!=null?id(ud(t)):{},gd(!t||!t.__esModule?Gt(r,"default",{value:t,enumerable:!0}):r,t)),hd=pd({"../../node_modules/.pnpm/[email protected]_patch_hash=vrxx3pzkik6jpmgpayxfjunetu/node_modules/prismjs/prism.js"(t,s){var r=function(){var a=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,o={},l={util:{encode:function h(p){return p instanceof c?new c(p.type,h(p.content),p.alias):Array.isArray(p)?p.map(h):p.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(h){return Object.prototype.toString.call(h).slice(8,-1)},objId:function(h){return h.__id||Object.defineProperty(h,"__id",{value:++n}),h.__id},clone:function h(p,g){g=g||{};var x,b;switch(l.util.type(p)){case"Object":if(b=l.util.objId(p),g[b])return g[b];x={},g[b]=x;for(var j in p)p.hasOwnProperty(j)&&(x[j]=h(p[j],g));return x;case"Array":return b=l.util.objId(p),g[b]?g[b]:(x=[],g[b]=x,p.forEach(function(w,E){x[E]=h(w,g)}),x);default:return p}},getLanguage:function(h){for(;h;){var p=a.exec(h.className);if(p)return p[1].toLowerCase();h=h.parentElement}return"none"},setLanguage:function(h,p){h.className=h.className.replace(RegExp(a,"gi"),""),h.classList.add("language-"+p)},isActive:function(h,p,g){for(var x="no-"+p;h;){var b=h.classList;if(b.contains(p))return!0;if(b.contains(x))return!1;h=h.parentElement}return!!g}},languages:{plain:o,plaintext:o,text:o,txt:o,extend:function(h,p){var g=l.util.clone(l.languages[h]);for(var x in p)g[x]=p[x];return g},insertBefore:function(h,p,g,x){x=x||l.languages;var b=x[h],j={};for(var w in b)if(b.hasOwnProperty(w)){if(w==p)for(var E in g)g.hasOwnProperty(E)&&(j[E]=g[E]);g.hasOwnProperty(w)||(j[w]=b[w])}var C=x[h];return x[h]=j,l.languages.DFS(l.languages,function(A,B){B===C&&A!=h&&(this[A]=j)}),j},DFS:function h(p,g,x,b){b=b||{};var j=l.util.objId;for(var w in p)if(p.hasOwnProperty(w)){g.call(p,w,p[w],x||w);var E=p[w],C=l.util.type(E);C==="Object"&&!b[j(E)]?(b[j(E)]=!0,h(E,g,null,b)):C==="Array"&&!b[j(E)]&&(b[j(E)]=!0,h(E,g,w,b))}}},plugins:{},highlight:function(h,p,g){var x={code:h,grammar:p,language:g};if(l.hooks.run("before-tokenize",x),!x.grammar)throw new Error('The language "'+x.language+'" has no grammar.');return x.tokens=l.tokenize(x.code,x.grammar),l.hooks.run("after-tokenize",x),c.stringify(l.util.encode(x.tokens),x.language)},tokenize:function(h,p){var g=p.rest;if(g){for(var x in g)p[x]=g[x];delete p.rest}var b=new m;return f(b,b.head,h),u(h,b,p,b.head,0),N(b)},hooks:{all:{},add:function(h,p){var g=l.hooks.all;g[h]=g[h]||[],g[h].push(p)},run:function(h,p){var g=l.hooks.all[h];if(!(!g||!g.length))for(var x=0,b;b=g[x++];)b(p)}},Token:c};function c(h,p,g,x){this.type=h,this.content=p,this.alias=g,this.length=(x||"").length|0}c.stringify=function h(p,g){if(typeof p=="string")return p;if(Array.isArray(p)){var x="";return p.forEach(function(C){x+=h(C,g)}),x}var b={type:p.type,content:h(p.content,g),tag:"span",classes:["token",p.type],attributes:{},language:g},j=p.alias;j&&(Array.isArray(j)?Array.prototype.push.apply(b.classes,j):b.classes.push(j)),l.hooks.run("wrap",b);var w="";for(var E in b.attributes)w+=" "+E+'="'+(b.attributes[E]||"").replace(/"/g,"&quot;")+'"';return"<"+b.tag+' class="'+b.classes.join(" ")+'"'+w+">"+b.content+"</"+b.tag+">"};function d(h,p,g,x){h.lastIndex=p;var b=h.exec(g);if(b&&x&&b[1]){var j=b[1].length;b.index+=j,b[0]=b[0].slice(j)}return b}function u(h,p,g,x,b,j){for(var w in g)if(!(!g.hasOwnProperty(w)||!g[w])){var E=g[w];E=Array.isArray(E)?E:[E];for(var C=0;C<E.length;++C){if(j&&j.cause==w+","+C)return;var A=E[C],B=A.inside,z=!!A.lookbehind,Y=!!A.greedy,K=A.alias;if(Y&&!A.pattern.global){var M=A.pattern.toString().match(/[imsuy]*$/)[0];A.pattern=RegExp(A.pattern.source,M+"g")}for(var W=A.pattern||A,T=x.next,O=b;T!==p.tail&&!(j&&O>=j.reach);O+=T.value.length,T=T.next){var V=T.value;if(p.length>h.length)return;if(!(V instanceof c)){var Q=1,_;if(Y){if(_=d(W,O,h,z),!_||_.index>=h.length)break;var S=_.index,I=_.index+_[0].length,P=O;for(P+=T.value.length;S>=P;)T=T.next,P+=T.value.length;if(P-=T.value.length,O=P,T.value instanceof c)continue;for(var U=T;U!==p.tail&&(P<I||typeof U.value=="string");U=U.next)Q++,P+=U.value.length;Q--,V=h.slice(O,P),_.index-=O}else if(_=d(W,0,V,z),!_)continue;var S=_.index,R=_[0],$=V.slice(0,S),L=V.slice(S+R.length),G=O+V.length;j&&G>j.reach&&(j.reach=G);var H=T.prev;$&&(H=f(p,H,$),O+=$.length),y(p,H,Q);var ne=new c(w,B?l.tokenize(R,B):R,K,R);if(T=f(p,H,ne),L&&f(p,T,L),Q>1){var de={cause:w+","+C,reach:G};u(h,p,g,T.prev,O,de),j&&de.reach>j.reach&&(j.reach=de.reach)}}}}}}function m(){var h={value:null,prev:null,next:null},p={value:null,prev:h,next:null};h.next=p,this.head=h,this.tail=p,this.length=0}function f(h,p,g){var x=p.next,b={value:g,prev:p,next:x};return p.next=b,x.prev=b,h.length++,b}function y(h,p,g){for(var x=p.next,b=0;b<g&&x!==h.tail;b++)x=x.next;p.next=x,x.prev=p,h.length-=b}function N(h){for(var p=[],g=h.head.next;g!==h.tail;)p.push(g.value),g=g.next;return p}return l}();s.exports=r,r.default=r}}),k=fd(hd());k.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},k.languages.markup.tag.inside["attr-value"].inside.entity=k.languages.markup.entity,k.languages.markup.doctype.inside["internal-subset"].inside=k.languages.markup,k.hooks.add("wrap",function(t){t.type==="entity"&&(t.attributes.title=t.content.replace(/&amp;/,"&"))}),Object.defineProperty(k.languages.markup.tag,"addInlined",{value:function(t,a){var r={},r=(r["language-"+a]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:k.languages[a]},r.cdata=/^<!\[CDATA\[|\]\]>$/i,{"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:r}}),a=(r["language-"+a]={pattern:/[\s\S]+/,inside:k.languages[a]},{});a[t]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return t}),"i"),lookbehind:!0,greedy:!0,inside:r},k.languages.insertBefore("markup","cdata",a)}}),Object.defineProperty(k.languages.markup.tag,"addAttribute",{value:function(t,s){k.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+t+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[s,"language-"+s],inside:k.languages[s]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),k.languages.html=k.languages.markup,k.languages.mathml=k.languages.markup,k.languages.svg=k.languages.markup,k.languages.xml=k.languages.extend("markup",{}),k.languages.ssml=k.languages.xml,k.languages.atom=k.languages.xml,k.languages.rss=k.languages.xml,function(t){var s={pattern:/\\[\\(){}[\]^$+*?|.]/,alias:"escape"},r=/\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\}|0[0-7]{0,2}|[123][0-7]{2}|c[a-zA-Z]|.)/,a="(?:[^\\\\-]|"+r.source+")",a=RegExp(a+"-"+a),n={pattern:/(<|')[^<>']+(?=[>']$)/,lookbehind:!0,alias:"variable"};t.languages.regex={"char-class":{pattern:/((?:^|[^\\])(?:\\\\)*)\[(?:[^\\\]]|\\[\s\S])*\]/,lookbehind:!0,inside:{"char-class-negation":{pattern:/(^\[)\^/,lookbehind:!0,alias:"operator"},"char-class-punctuation":{pattern:/^\[|\]$/,alias:"punctuation"},range:{pattern:a,inside:{escape:r,"range-punctuation":{pattern:/-/,alias:"operator"}}},"special-escape":s,"char-set":{pattern:/\\[wsd]|\\p\{[^{}]+\}/i,alias:"class-name"},escape:r}},"special-escape":s,"char-set":{pattern:/\.|\\[wsd]|\\p\{[^{}]+\}/i,alias:"class-name"},backreference:[{pattern:/\\(?![123][0-7]{2})[1-9]/,alias:"keyword"},{pattern:/\\k<[^<>']+>/,alias:"keyword",inside:{"group-name":n}}],anchor:{pattern:/[$^]|\\[ABbGZz]/,alias:"function"},escape:r,group:[{pattern:/\((?:\?(?:<[^<>']+>|'[^<>']+'|[>:]|<?[=!]|[idmnsuxU]+(?:-[idmnsuxU]+)?:?))?/,alias:"punctuation",inside:{"group-name":n}},{pattern:/\)/,alias:"punctuation"}],quantifier:{pattern:/(?:[+*?]|\{\d+(?:,\d*)?\})[?+]?/,alias:"number"},alternation:{pattern:/\|/,alias:"keyword"}}}(k),k.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},k.languages.javascript=k.languages.extend("clike",{"class-name":[k.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),k.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,k.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:k.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:k.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:k.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:k.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:k.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),k.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:k.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),k.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),k.languages.markup&&(k.languages.markup.tag.addInlined("script","javascript"),k.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript")),k.languages.js=k.languages.javascript,k.languages.actionscript=k.languages.extend("javascript",{keyword:/\b(?:as|break|case|catch|class|const|default|delete|do|dynamic|each|else|extends|final|finally|for|function|get|if|implements|import|in|include|instanceof|interface|internal|is|namespace|native|new|null|override|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|use|var|void|while|with)\b/,operator:/\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<<?|>>?>?|[!=]=?)=?|[~?@]/}),k.languages.actionscript["class-name"].alias="function",delete k.languages.actionscript.parameter,delete k.languages.actionscript["literal-property"],k.languages.markup&&k.languages.insertBefore("actionscript","string",{xml:{pattern:/(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\[\s\S]|(?!\2)[^\\])*\2)*\s*\/?>/,lookbehind:!0,inside:k.languages.markup}}),function(t){var s=/#(?!\{).+/,r={pattern:/#\{[^}]+\}/,alias:"variable"};t.languages.coffeescript=t.languages.extend("javascript",{comment:s,string:[{pattern:/'(?:\\[\s\S]|[^\\'])*'/,greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,greedy:!0,inside:{interpolation:r}}],keyword:/\b(?:and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/,"class-member":{pattern:/@(?!\d)\w+/,alias:"variable"}}),t.languages.insertBefore("coffeescript","comment",{"multiline-comment":{pattern:/###[\s\S]+?###/,alias:"comment"},"block-regex":{pattern:/\/{3}[\s\S]*?\/{3}/,alias:"regex",inside:{comment:s,interpolation:r}}}),t.languages.insertBefore("coffeescript","string",{"inline-javascript":{pattern:/`(?:\\[\s\S]|[^\\`])*`/,inside:{delimiter:{pattern:/^`|`$/,alias:"punctuation"},script:{pattern:/[\s\S]+/,alias:"language-javascript",inside:t.languages.javascript}}},"multiline-string":[{pattern:/'''[\s\S]*?'''/,greedy:!0,alias:"string"},{pattern:/"""[\s\S]*?"""/,greedy:!0,alias:"string",inside:{interpolation:r}}]}),t.languages.insertBefore("coffeescript","keyword",{property:/(?!\d)\w+(?=\s*:(?!:))/}),delete t.languages.coffeescript["template-string"],t.languages.coffee=t.languages.coffeescript}(k),function(t){var s=t.languages.javadoclike={parameter:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*@(?:arg|arguments|param)\s+)\w+/m,lookbehind:!0},keyword:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*|\{)@[a-z][a-zA-Z-]+\b/m,lookbehind:!0},punctuation:/[{}]/};Object.defineProperty(s,"addSupport",{value:function(r,a){(r=typeof r=="string"?[r]:r).forEach(function(n){var o=function(f){f.inside||(f.inside={}),f.inside.rest=a},l="doc-comment";if(c=t.languages[n]){var c,d=c[l];if((d=d||(c=t.languages.insertBefore(n,"comment",{"doc-comment":{pattern:/(^|[^\\])\/\*\*[^/][\s\S]*?(?:\*\/|$)/,lookbehind:!0,alias:"comment"}}))[l])instanceof RegExp&&(d=c[l]={pattern:d}),Array.isArray(d))for(var u=0,m=d.length;u<m;u++)d[u]instanceof RegExp&&(d[u]={pattern:d[u]}),o(d[u]);else o(d)}})}}),s.addSupport(["java","javascript","php"],s)}(k),function(t){var s=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/,s=(t.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+s.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+s.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+s.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+s.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:s,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},t.languages.css.atrule.inside.rest=t.languages.css,t.languages.markup);s&&(s.tag.addInlined("style","css"),s.tag.addAttribute("style","css"))}(k),function(t){var s=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,s=(t.languages.css.selector={pattern:t.languages.css.selector.pattern,lookbehind:!0,inside:s={"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,"pseudo-class":/:[-\w]+/,class:/\.[-\w]+/,id:/#[-\w]+/,attribute:{pattern:RegExp(`\\[(?:[^[\\]"']|`+s.source+")*\\]"),greedy:!0,inside:{punctuation:/^\[|\]$/,"case-sensitivity":{pattern:/(\s)[si]$/i,lookbehind:!0,alias:"keyword"},namespace:{pattern:/^(\s*)(?:(?!\s)[-*\w\xA0-\uFFFF])*\|(?!=)/,lookbehind:!0,inside:{punctuation:/\|$/}},"attr-name":{pattern:/^(\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+/,lookbehind:!0},"attr-value":[s,{pattern:/(=\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+(?=\s*$)/,lookbehind:!0}],operator:/[|~*^$]?=/}},"n-th":[{pattern:/(\(\s*)[+-]?\d*[\dn](?:\s*[+-]\s*\d+)?(?=\s*\))/,lookbehind:!0,inside:{number:/[\dn]+/,operator:/[+-]/}},{pattern:/(\(\s*)(?:even|odd)(?=\s*\))/i,lookbehind:!0}],combinator:/>|\+|~|\|\|/,punctuation:/[(),]/}},t.languages.css.atrule.inside["selector-function-argument"].inside=s,t.languages.insertBefore("css","property",{variable:{pattern:/(^|[^-\w\xA0-\uFFFF])--(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*/i,lookbehind:!0}}),{pattern:/(\b\d+)(?:%|[a-z]+(?![\w-]))/,lookbehind:!0}),r={pattern:/(^|[^\w.-])-?(?:\d+(?:\.\d+)?|\.\d+)/,lookbehind:!0};t.languages.insertBefore("css","function",{operator:{pattern:/(\s)[+\-*\/](?=\s)/,lookbehind:!0},hexcode:{pattern:/\B#[\da-f]{3,8}\b/i,alias:"color"},color:[{pattern:/(^|[^\w-])(?:AliceBlue|AntiqueWhite|Aqua|Aquamarine|Azure|Beige|Bisque|Black|BlanchedAlmond|Blue|BlueViolet|Brown|BurlyWood|CadetBlue|Chartreuse|Chocolate|Coral|CornflowerBlue|Cornsilk|Crimson|Cyan|DarkBlue|DarkCyan|DarkGoldenRod|DarkGr[ae]y|DarkGreen|DarkKhaki|DarkMagenta|DarkOliveGreen|DarkOrange|DarkOrchid|DarkRed|DarkSalmon|DarkSeaGreen|DarkSlateBlue|DarkSlateGr[ae]y|DarkTurquoise|DarkViolet|DeepPink|DeepSkyBlue|DimGr[ae]y|DodgerBlue|FireBrick|FloralWhite|ForestGreen|Fuchsia|Gainsboro|GhostWhite|Gold|GoldenRod|Gr[ae]y|Green|GreenYellow|HoneyDew|HotPink|IndianRed|Indigo|Ivory|Khaki|Lavender|LavenderBlush|LawnGreen|LemonChiffon|LightBlue|LightCoral|LightCyan|LightGoldenRodYellow|LightGr[ae]y|LightGreen|LightPink|LightSalmon|LightSeaGreen|LightSkyBlue|LightSlateGr[ae]y|LightSteelBlue|LightYellow|Lime|LimeGreen|Linen|Magenta|Maroon|MediumAquaMarine|MediumBlue|MediumOrchid|MediumPurple|MediumSeaGreen|MediumSlateBlue|MediumSpringGreen|MediumTurquoise|MediumVioletRed|MidnightBlue|MintCream|MistyRose|Moccasin|NavajoWhite|Navy|OldLace|Olive|OliveDrab|Orange|OrangeRed|Orchid|PaleGoldenRod|PaleGreen|PaleTurquoise|PaleVioletRed|PapayaWhip|PeachPuff|Peru|Pink|Plum|PowderBlue|Purple|RebeccaPurple|Red|RosyBrown|RoyalBlue|SaddleBrown|Salmon|SandyBrown|SeaGreen|SeaShell|Sienna|Silver|SkyBlue|SlateBlue|SlateGr[ae]y|Snow|SpringGreen|SteelBlue|Tan|Teal|Thistle|Tomato|Transparent|Turquoise|Violet|Wheat|White|WhiteSmoke|Yellow|YellowGreen)(?![\w-])/i,lookbehind:!0},{pattern:/\b(?:hsl|rgb)\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\)\B|\b(?:hsl|rgb)a\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*(?:0|0?\.\d+|1)\s*\)\B/i,inside:{unit:s,number:r,function:/[\w-]+(?=\()/,punctuation:/[(),]/}}],entity:/\\[\da-f]{1,8}/i,unit:s,number:r})}(k),function(t){var s=/[*&][^\s[\]{},]+/,r=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,a="(?:"+r.source+"(?:[ ]+"+s.source+")?|"+s.source+"(?:[ ]+"+r.source+")?)",n=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),o=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function l(c,d){d=(d||"").replace(/m/g,"")+"m";var u=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return a}).replace(/<<value>>/g,function(){return c});return RegExp(u,d)}t.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return a})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return a}).replace(/<<key>>/g,function(){return"(?:"+n+"|"+o+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:l(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:l(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:l(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:l(o),lookbehind:!0,greedy:!0},number:{pattern:l(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:r,important:s,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},t.languages.yml=t.languages.yaml}(k),function(t){var s=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function r(u){return u=u.replace(/<inner>/g,function(){return s}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+u+")")}var a=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,n=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return a}),o=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source,l=(t.languages.markdown=t.languages.extend("markup",{}),t.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:t.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+n+o+"(?:"+n+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+n+o+")(?:"+n+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(a),inside:t.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+n+")"+o+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+n+"$"),inside:{"table-header":{pattern:RegExp(a),alias:"important",inside:t.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:r(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:r(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:r(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:r(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(u){["url","bold","italic","strike","code-snippet"].forEach(function(m){u!==m&&(t.languages.markdown[u].inside.content.inside[m]=t.languages.markdown[m])})}),t.hooks.add("after-tokenize",function(u){u.language!=="markdown"&&u.language!=="md"||function m(f){if(f&&typeof f!="string")for(var y=0,N=f.length;y<N;y++){var h,p=f[y];p.type!=="code"?m(p.content):(h=p.content[1],p=p.content[3],h&&p&&h.type==="code-language"&&p.type==="code-block"&&typeof h.content=="string"&&(h=h.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp"),h="language-"+(h=(/[a-z][\w-]*/i.exec(h)||[""])[0].toLowerCase()),p.alias?typeof p.alias=="string"?p.alias=[p.alias,h]:p.alias.push(h):p.alias=[h]))}}(u.tokens)}),t.hooks.add("wrap",function(u){if(u.type==="code-block"){for(var m="",f=0,y=u.classes.length;f<y;f++){var N=u.classes[f],N=/language-(.+)/.exec(N);if(N){m=N[1];break}}var h,p=t.languages[m];p?u.content=t.highlight(function(g){return g=g.replace(l,""),g=g.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(x,b){var j;return(b=b.toLowerCase())[0]==="#"?(j=b[1]==="x"?parseInt(b.slice(2),16):Number(b.slice(1)),d(j)):c[b]||x})}(u.content),p,m):m&&m!=="none"&&t.plugins.autoloader&&(h="md-"+new Date().valueOf()+"-"+Math.floor(1e16*Math.random()),u.attributes.id=h,t.plugins.autoloader.loadLanguages(m,function(){var g=document.getElementById(h);g&&(g.innerHTML=t.highlight(g.textContent,t.languages[m],m))}))}}),RegExp(t.languages.markup.tag.pattern.source,"gi")),c={amp:"&",lt:"<",gt:">",quot:'"'},d=String.fromCodePoint||String.fromCharCode;t.languages.md=t.languages.markdown}(k),k.languages.graphql={comment:/#.*/,description:{pattern:/(?:"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*")(?=\s*[a-z_])/i,greedy:!0,alias:"string",inside:{"language-markdown":{pattern:/(^"(?:"")?)(?!\1)[\s\S]+(?=\1$)/,lookbehind:!0,inside:k.languages.markdown}}},string:{pattern:/"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},number:/(?:\B-|\b)\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,boolean:/\b(?:false|true)\b/,variable:/\$[a-z_]\w*/i,directive:{pattern:/@[a-z_]\w*/i,alias:"function"},"attr-name":{pattern:/\b[a-z_]\w*(?=\s*(?:\((?:[^()"]|"(?:\\.|[^\\"\r\n])*")*\))?:)/i,greedy:!0},"atom-input":{pattern:/\b[A-Z]\w*Input\b/,alias:"class-name"},scalar:/\b(?:Boolean|Float|ID|Int|String)\b/,constant:/\b[A-Z][A-Z_\d]*\b/,"class-name":{pattern:/(\b(?:enum|implements|interface|on|scalar|type|union)\s+|&\s*|:\s*|\[)[A-Z_]\w*/,lookbehind:!0},fragment:{pattern:/(\bfragment\s+|\.{3}\s*(?!on\b))[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-mutation":{pattern:/(\bmutation\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-query":{pattern:/(\bquery\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},keyword:/\b(?:directive|enum|extend|fragment|implements|input|interface|mutation|on|query|repeatable|scalar|schema|subscription|type|union)\b/,operator:/[!=|&]|\.{3}/,"property-query":/\w+(?=\s*\()/,object:/\w+(?=\s*\{)/,punctuation:/[!(){}\[\]:=,]/,property:/\w+/},k.hooks.add("after-tokenize",function(t){if(t.language==="graphql")for(var s=t.tokens.filter(function(h){return typeof h!="string"&&h.type!=="comment"&&h.type!=="scalar"}),r=0;r<s.length;){var a=s[r++];if(a.type==="keyword"&&a.content==="mutation"){var n=[];if(f(["definition-mutation","punctuation"])&&m(1).content==="("){r+=2;var o=y(/^\($/,/^\)$/);if(o===-1)continue;for(;r<o;r++){var l=m(0);l.type==="variable"&&(N(l,"variable-input"),n.push(l.content))}r=o+1}if(f(["punctuation","property-query"])&&m(0).content==="{"&&(r++,N(m(0),"property-mutation"),0<n.length)){var c=y(/^\{$/,/^\}$/);if(c!==-1)for(var d=r;d<c;d++){var u=s[d];u.type==="variable"&&0<=n.indexOf(u.content)&&N(u,"variable-input")}}}}function m(h){return s[r+h]}function f(h,p){p=p||0;for(var g=0;g<h.length;g++){var x=m(g+p);if(!x||x.type!==h[g])return}return 1}function y(h,p){for(var g=1,x=r;x<s.length;x++){var b=s[x],j=b.content;if(b.type==="punctuation"&&typeof j=="string"){if(h.test(j))g++;else if(p.test(j)&&--g===0)return x}}return-1}function N(h,p){var g=h.alias;g?Array.isArray(g)||(h.alias=g=[g]):h.alias=g=[],g.push(p)}}),k.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/},function(t){var s=t.languages.javascript["template-string"],r=s.pattern.source,a=s.inside.interpolation,n=a.inside["interpolation-punctuation"],o=a.pattern.source;function l(f,y){if(t.languages[f])return{pattern:RegExp("((?:"+y+")\\s*)"+r),lookbehind:!0,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},"embedded-code":{pattern:/[\s\S]+/,alias:f}}}}function c(f,y,N){return f={code:f,grammar:y,language:N},t.hooks.run("before-tokenize",f),f.tokens=t.tokenize(f.code,f.grammar),t.hooks.run("after-tokenize",f),f.tokens}function d(f,y,N){var g=t.tokenize(f,{interpolation:{pattern:RegExp(o),lookbehind:!0}}),h=0,p={},g=c(g.map(function(b){if(typeof b=="string")return b;for(var j,w,b=b.content;f.indexOf((w=h++,j="___"+N.toUpperCase()+"_"+w+"___"))!==-1;);return p[j]=b,j}).join(""),y,N),x=Object.keys(p);return h=0,function b(j){for(var w=0;w<j.length;w++){if(h>=x.length)return;var E,C,A,B,z,Y,K,M=j[w];typeof M=="string"||typeof M.content=="string"?(E=x[h],(K=(Y=typeof M=="string"?M:M.content).indexOf(E))!==-1&&(++h,C=Y.substring(0,K),z=p[E],A=void 0,(B={})["interpolation-punctuation"]=n,(B=t.tokenize(z,B)).length===3&&((A=[1,1]).push.apply(A,c(B[1],t.languages.javascript,"javascript")),B.splice.apply(B,A)),A=new t.Token("interpolation",B,a.alias,z),B=Y.substring(K+E.length),z=[],C&&z.push(C),z.push(A),B&&(b(Y=[B]),z.push.apply(z,Y)),typeof M=="string"?(j.splice.apply(j,[w,1].concat(z)),w+=z.length-1):M.content=z)):(K=M.content,Array.isArray(K)?b(K):b([K]))}}(g),new t.Token(N,g,"language-"+N,f)}t.languages.javascript["template-string"]=[l("css",/\b(?:styled(?:\([^)]*\))?(?:\s*\.\s*\w+(?:\([^)]*\))*)*|css(?:\s*\.\s*(?:global|resolve))?|createGlobalStyle|keyframes)/.source),l("html",/\bhtml|\.\s*(?:inner|outer)HTML\s*\+?=/.source),l("svg",/\bsvg/.source),l("markdown",/\b(?:markdown|md)/.source),l("graphql",/\b(?:gql|graphql(?:\s*\.\s*experimental)?)/.source),l("sql",/\bsql/.source),s].filter(Boolean);var u={javascript:!0,js:!0,typescript:!0,ts:!0,jsx:!0,tsx:!0};function m(f){return typeof f=="string"?f:Array.isArray(f)?f.map(m).join(""):m(f.content)}t.hooks.add("after-tokenize",function(f){f.language in u&&function y(N){for(var h=0,p=N.length;h<p;h++){var g,x,b,j=N[h];typeof j!="string"&&(g=j.content,Array.isArray(g)?j.type==="template-string"?(j=g[1],g.length===3&&typeof j!="string"&&j.type==="embedded-code"&&(x=m(j),j=j.alias,j=Array.isArray(j)?j[0]:j,b=t.languages[j])&&(g[1]=d(x,b,j))):y(g):typeof g!="string"&&y([g]))}}(f.tokens)})}(k),function(t){t.languages.typescript=t.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),t.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete t.languages.typescript.parameter,delete t.languages.typescript["literal-property"];var s=t.languages.extend("typescript",{});delete s["class-name"],t.languages.typescript["class-name"].inside=s,t.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:s}}}}),t.languages.ts=t.languages.typescript}(k),function(t){var s=t.languages.javascript,r=/\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})+\}/.source,a="(@(?:arg|argument|param|property)\\s+(?:"+r+"\\s+)?)";t.languages.jsdoc=t.languages.extend("javadoclike",{parameter:{pattern:RegExp(a+/(?:(?!\s)[$\w\xA0-\uFFFF.])+(?=\s|$)/.source),lookbehind:!0,inside:{punctuation:/\./}}}),t.languages.insertBefore("jsdoc","keyword",{"optional-parameter":{pattern:RegExp(a+/\[(?:(?!\s)[$\w\xA0-\uFFFF.])+(?:=[^[\]]+)?\](?=\s|$)/.source),lookbehind:!0,inside:{parameter:{pattern:/(^\[)[$\w\xA0-\uFFFF\.]+/,lookbehind:!0,inside:{punctuation:/\./}},code:{pattern:/(=)[\s\S]*(?=\]$)/,lookbehind:!0,inside:s,alias:"language-javascript"},punctuation:/[=[\]]/}},"class-name":[{pattern:RegExp(/(@(?:augments|class|extends|interface|memberof!?|template|this|typedef)\s+(?:<TYPE>\s+)?)[A-Z]\w*(?:\.[A-Z]\w*)*/.source.replace(/<TYPE>/g,function(){return r})),lookbehind:!0,inside:{punctuation:/\./}},{pattern:RegExp("(@[a-z]+\\s+)"+r),lookbehind:!0,inside:{string:s.string,number:s.number,boolean:s.boolean,keyword:t.languages.typescript.keyword,operator:/=>|\.\.\.|[&|?:*]/,punctuation:/[.,;=<>{}()[\]]/}}],example:{pattern:/(@example\s+(?!\s))(?:[^@\s]|\s+(?!\s))+?(?=\s*(?:\*\s*)?(?:@\w|\*\/))/,lookbehind:!0,inside:{code:{pattern:/^([\t ]*(?:\*\s*)?)\S.*$/m,lookbehind:!0,inside:s,alias:"language-javascript"}}}}),t.languages.javadoclike.addSupport("javascript",t.languages.jsdoc)}(k),function(t){t.languages.flow=t.languages.extend("javascript",{}),t.languages.insertBefore("flow","keyword",{type:[{pattern:/\b(?:[Bb]oolean|Function|[Nn]umber|[Ss]tring|[Ss]ymbol|any|mixed|null|void)\b/,alias:"class-name"}]}),t.languages.flow["function-variable"].pattern=/(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=\s*(?:function\b|(?:\([^()]*\)(?:\s*:\s*\w+)?|(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/i,delete t.languages.flow.parameter,t.languages.insertBefore("flow","operator",{"flow-punctuation":{pattern:/\{\||\|\}/,alias:"punctuation"}}),Array.isArray(t.languages.flow.keyword)||(t.languages.flow.keyword=[t.languages.flow.keyword]),t.languages.flow.keyword.unshift({pattern:/(^|[^$]\b)(?:Class|declare|opaque|type)\b(?!\$)/,lookbehind:!0},{pattern:/(^|[^$]\B)\$(?:Diff|Enum|Exact|Keys|ObjMap|PropertyType|Record|Shape|Subtype|Supertype|await)\b(?!\$)/,lookbehind:!0})}(k),k.languages.n4js=k.languages.extend("javascript",{keyword:/\b(?:Array|any|boolean|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|module|new|null|number|package|private|protected|public|return|set|static|string|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/}),k.languages.insertBefore("n4js","constant",{annotation:{pattern:/@+\w+/,alias:"operator"}}),k.languages.n4jsd=k.languages.n4js,function(t){function s(l,c){return RegExp(l.replace(/<ID>/g,function(){return/(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/.source}),c)}t.languages.insertBefore("javascript","function-variable",{"method-variable":{pattern:RegExp("(\\.\\s*)"+t.languages.javascript["function-variable"].pattern.source),lookbehind:!0,alias:["function-variable","method","function","property-access"]}}),t.languages.insertBefore("javascript","function",{method:{pattern:RegExp("(\\.\\s*)"+t.languages.javascript.function.source),lookbehind:!0,alias:["function","property-access"]}}),t.languages.insertBefore("javascript","constant",{"known-class-name":[{pattern:/\b(?:(?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)?Array|ArrayBuffer|BigInt|Boolean|DataView|Date|Error|Function|Intl|JSON|(?:Weak)?(?:Map|Set)|Math|Number|Object|Promise|Proxy|Reflect|RegExp|String|Symbol|WebAssembly)\b/,alias:"class-name"},{pattern:/\b(?:[A-Z]\w*)Error\b/,alias:"class-name"}]}),t.languages.insertBefore("javascript","keyword",{imports:{pattern:s(/(\bimport\b\s*)(?:<ID>(?:\s*,\s*(?:\*\s*as\s+<ID>|\{[^{}]*\}))?|\*\s*as\s+<ID>|\{[^{}]*\})(?=\s*\bfrom\b)/.source),lookbehind:!0,inside:t.languages.javascript},exports:{pattern:s(/(\bexport\b\s*)(?:\*(?:\s*as\s+<ID>)?(?=\s*\bfrom\b)|\{[^{}]*\})/.source),lookbehind:!0,inside:t.languages.javascript}}),t.languages.javascript.keyword.unshift({pattern:/\b(?:as|default|export|from|import)\b/,alias:"module"},{pattern:/\b(?:await|break|catch|continue|do|else|finally|for|if|return|switch|throw|try|while|yield)\b/,alias:"control-flow"},{pattern:/\bnull\b/,alias:["null","nil"]},{pattern:/\bundefined\b/,alias:"nil"}),t.languages.insertBefore("javascript","operator",{spread:{pattern:/\.{3}/,alias:"operator"},arrow:{pattern:/=>/,alias:"operator"}}),t.languages.insertBefore("javascript","punctuation",{"property-access":{pattern:s(/(\.\s*)#?<ID>/.source),lookbehind:!0},"maybe-class-name":{pattern:/(^|[^$\w\xA0-\uFFFF])[A-Z][$\w\xA0-\uFFFF]+/,lookbehind:!0},dom:{pattern:/\b(?:document|(?:local|session)Storage|location|navigator|performance|window)\b/,alias:"variable"},console:{pattern:/\bconsole(?=\s*\.)/,alias:"class-name"}});for(var r=["function","function-variable","method","method-variable","property-access"],a=0;a<r.length;a++){var o=r[a],n=t.languages.javascript[o],o=(n=t.util.type(n)==="RegExp"?t.languages.javascript[o]={pattern:n}:n).inside||{};(n.inside=o)["maybe-class-name"]=/^[A-Z][\s\S]*/}}(k),function(t){var s=t.util.clone(t.languages.javascript),r=/(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source,a=/(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source,n=/(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;function o(d,u){return d=d.replace(/<S>/g,function(){return r}).replace(/<BRACES>/g,function(){return a}).replace(/<SPREAD>/g,function(){return n}),RegExp(d,u)}n=o(n).source,t.languages.jsx=t.languages.extend("markup",s),t.languages.jsx.tag.pattern=o(/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source),t.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,t.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,t.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,t.languages.jsx.tag.inside.comment=s.comment,t.languages.insertBefore("inside","attr-name",{spread:{pattern:o(/<SPREAD>/.source),inside:t.languages.jsx}},t.languages.jsx.tag),t.languages.insertBefore("inside","special-attr",{script:{pattern:o(/=<BRACES>/.source),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:t.languages.jsx}}},t.languages.jsx.tag);function l(d){for(var u=[],m=0;m<d.length;m++){var f=d[m],y=!1;typeof f!="string"&&(f.type==="tag"&&f.content[0]&&f.content[0].type==="tag"?f.content[0].content[0].content==="</"?0<u.length&&u[u.length-1].tagName===c(f.content[0].content[1])&&u.pop():f.content[f.content.length-1].content!=="/>"&&u.push({tagName:c(f.content[0].content[1]),openedBraces:0}):0<u.length&&f.type==="punctuation"&&f.content==="{"?u[u.length-1].openedBraces++:0<u.length&&0<u[u.length-1].openedBraces&&f.type==="punctuation"&&f.content==="}"?u[u.length-1].openedBraces--:y=!0),(y||typeof f=="string")&&0<u.length&&u[u.length-1].openedBraces===0&&(y=c(f),m<d.length-1&&(typeof d[m+1]=="string"||d[m+1].type==="plain-text")&&(y+=c(d[m+1]),d.splice(m+1,1)),0<m&&(typeof d[m-1]=="string"||d[m-1].type==="plain-text")&&(y=c(d[m-1])+y,d.splice(m-1,1),m--),d[m]=new t.Token("plain-text",y,null,y)),f.content&&typeof f.content!="string"&&l(f.content)}}var c=function(d){return d?typeof d=="string"?d:typeof d.content=="string"?d.content:d.content.map(c).join(""):""};t.hooks.add("after-tokenize",function(d){d.language!=="jsx"&&d.language!=="tsx"||l(d.tokens)})}(k),function(t){var s=t.util.clone(t.languages.typescript),s=(t.languages.tsx=t.languages.extend("jsx",s),delete t.languages.tsx.parameter,delete t.languages.tsx["literal-property"],t.languages.tsx.tag);s.pattern=RegExp(/(^|[^\w$]|(?=<\/))/.source+"(?:"+s.pattern.source+")",s.pattern.flags),s.lookbehind=!0}(k),k.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp(/(^|[^"#])/.source+"(?:"+/"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source+"|"+/"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source+")"+/(?!["#])/.source),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp(/(^|[^"#])(#+)/.source+"(?:"+/"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source+"|"+/"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source+")\\2"),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp(/#/.source+"(?:"+/(?:elseif|if)\b/.source+"(?:[ ]*"+/(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source+")+|"+/(?:else|endif)\b/.source+")"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/},k.languages.swift["string-literal"].forEach(function(t){t.inside.interpolation.inside=k.languages.swift}),function(t){t.languages.kotlin=t.languages.extend("clike",{keyword:{pattern:/(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,lookbehind:!0},function:[{pattern:/(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,greedy:!0},{pattern:/(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,lookbehind:!0,greedy:!0}],number:/\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,operator:/\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/}),delete t.languages.kotlin["class-name"];var s={"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:t.languages.kotlin}};t.languages.insertBefore("kotlin","string",{"string-literal":[{pattern:/"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,alias:"multiline",inside:{interpolation:{pattern:/\$(?:[a-z_]\w*|\{[^{}]*\})/i,inside:s},string:/[\s\S]+/}},{pattern:/"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,alias:"singleline",inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,lookbehind:!0,inside:s},string:/[\s\S]+/}}],char:{pattern:/'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,greedy:!0}}),delete t.languages.kotlin.string,t.languages.insertBefore("kotlin","keyword",{annotation:{pattern:/\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,alias:"builtin"}}),t.languages.insertBefore("kotlin","function",{label:{pattern:/\b\w+@|@\w+\b/,alias:"symbol"}}),t.languages.kt=t.languages.kotlin,t.languages.kts=t.languages.kotlin}(k),k.languages.c=k.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/}),k.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}}),k.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},k.languages.c.string],char:k.languages.c.char,comment:k.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:k.languages.c}}}}),k.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/}),delete k.languages.c.boolean,k.languages.objectivec=k.languages.extend("c",{string:{pattern:/@?"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},keyword:/\b(?:asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|in|inline|int|long|register|return|self|short|signed|sizeof|static|struct|super|switch|typedef|typeof|union|unsigned|void|volatile|while)\b|(?:@interface|@end|@implementation|@protocol|@class|@public|@protected|@private|@property|@try|@catch|@finally|@throw|@synthesize|@dynamic|@selector)\b/,operator:/-[->]?|\+\+?|!=?|<<?=?|>>?=?|==?|&&?|\|\|?|[~^%?*\/@]/}),delete k.languages.objectivec["class-name"],k.languages.objc=k.languages.objectivec,k.languages.reason=k.languages.extend("clike",{string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^\\\r\n"])*"/,greedy:!0},"class-name":/\b[A-Z]\w*/,keyword:/\b(?:and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|for|fun|function|functor|if|in|include|inherit|initializer|lazy|let|method|module|mutable|new|nonrec|object|of|open|or|private|rec|sig|struct|switch|then|to|try|type|val|virtual|when|while|with)\b/,operator:/\.{3}|:[:=]|\|>|->|=(?:==?|>)?|<=?|>=?|[|^?'#!~`]|[+\-*\/]\.?|\b(?:asr|land|lor|lsl|lsr|lxor|mod)\b/}),k.languages.insertBefore("reason","class-name",{char:{pattern:/'(?:\\x[\da-f]{2}|\\o[0-3][0-7][0-7]|\\\d{3}|\\.|[^'\\\r\n])'/,greedy:!0},constructor:/\b[A-Z]\w*\b(?!\s*\.)/,label:{pattern:/\b[a-z]\w*(?=::)/,alias:"symbol"}}),delete k.languages.reason.function,function(t){for(var s=/\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source,r=0;r<2;r++)s=s.replace(/<self>/g,function(){return s});s=s.replace(/<self>/g,function(){return/[^\s\S]/.source}),t.languages.rust={comment:[{pattern:RegExp(/(^|[^\\])/.source+s),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},t.languages.rust["closure-params"].inside.rest=t.languages.rust,t.languages.rust.attribute.inside.string=t.languages.rust.string}(k),k.languages.go=k.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/}),k.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}}),delete k.languages.go["class-name"],function(t){var s=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,r=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return s.source});t.languages.cpp=t.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return s.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:s,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),t.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return r})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),t.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:t.languages.cpp}}}}),t.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),t.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:t.languages.extend("cpp",{})}}),t.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},t.languages.cpp["base-clause"])}(k),k.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},k.languages.python["string-interpolation"].inside.interpolation.inside.rest=k.languages.python,k.languages.py=k.languages.python,k.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}},k.languages.webmanifest=k.languages.json;var xd={};md(xd,{dracula:()=>yd,duotoneDark:()=>jd,duotoneLight:()=>Nd,github:()=>Sd,gruvboxMaterialDark:()=>eu,gruvboxMaterialLight:()=>su,jettwaveDark:()=>Hd,jettwaveLight:()=>Wd,nightOwl:()=>Cd,nightOwlLight:()=>Rd,oceanicNext:()=>_d,okaidia:()=>Fd,oneDark:()=>Yd,oneLight:()=>Qd,palenight:()=>Pd,shadesOfPurple:()=>Od,synthwave84:()=>Md,ultramin:()=>zd,vsDark:()=>sn,vsLight:()=>qd});var bd={plain:{color:"#F8F8F2",backgroundColor:"#282A36"},styles:[{types:["prolog","constant","builtin"],style:{color:"rgb(189, 147, 249)"}},{types:["inserted","function"],style:{color:"rgb(80, 250, 123)"}},{types:["deleted"],style:{color:"rgb(255, 85, 85)"}},{types:["changed"],style:{color:"rgb(255, 184, 108)"}},{types:["punctuation","symbol"],style:{color:"rgb(248, 248, 242)"}},{types:["string","char","tag","selector"],style:{color:"rgb(255, 121, 198)"}},{types:["keyword","variable"],style:{color:"rgb(189, 147, 249)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(98, 114, 164)"}},{types:["attr-name"],style:{color:"rgb(241, 250, 140)"}}]},yd=bd,vd={plain:{backgroundColor:"#2a2734",color:"#9a86fd"},styles:[{types:["comment","prolog","doctype","cdata","punctuation"],style:{color:"#6c6783"}},{types:["namespace"],style:{opacity:.7}},{types:["tag","operator","number"],style:{color:"#e09142"}},{types:["property","function"],style:{color:"#9a86fd"}},{types:["tag-id","selector","atrule-id"],style:{color:"#eeebff"}},{types:["attr-name"],style:{color:"#c4b9fe"}},{types:["boolean","string","entity","url","attr-value","keyword","control","directive","unit","statement","regex","atrule","placeholder","variable"],style:{color:"#ffcc99"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"#c4b9fe"}}]},jd=vd,wd={plain:{backgroundColor:"#faf8f5",color:"#728fcb"},styles:[{types:["comment","prolog","doctype","cdata","punctuation"],style:{color:"#b6ad9a"}},{types:["namespace"],style:{opacity:.7}},{types:["tag","operator","number"],style:{color:"#063289"}},{types:["property","function"],style:{color:"#b29762"}},{types:["tag-id","selector","atrule-id"],style:{color:"#2d2006"}},{types:["attr-name"],style:{color:"#896724"}},{types:["boolean","string","entity","url","attr-value","keyword","control","directive","unit","statement","regex","atrule"],style:{color:"#728fcb"}},{types:["placeholder","variable"],style:{color:"#93abdc"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"#896724"}}]},Nd=wd,kd={plain:{color:"#393A34",backgroundColor:"#f6f8fa"},styles:[{types:["comment","prolog","doctype","cdata"],style:{color:"#999988",fontStyle:"italic"}},{types:["namespace"],style:{opacity:.7}},{types:["string","attr-value"],style:{color:"#e3116c"}},{types:["punctuation","operator"],style:{color:"#393A34"}},{types:["entity","url","symbol","number","boolean","variable","constant","property","regex","inserted"],style:{color:"#36acaa"}},{types:["atrule","keyword","attr-name","selector"],style:{color:"#00a4db"}},{types:["function","deleted","tag"],style:{color:"#d73a49"}},{types:["function-variable"],style:{color:"#6f42c1"}},{types:["tag","selector","keyword"],style:{color:"#00009f"}}]},Sd=kd,Ed={plain:{color:"#d6deeb",backgroundColor:"#011627"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)",fontStyle:"italic"}},{types:["inserted","attr-name"],style:{color:"rgb(173, 219, 103)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(99, 119, 119)",fontStyle:"italic"}},{types:["string","url"],style:{color:"rgb(173, 219, 103)"}},{types:["variable"],style:{color:"rgb(214, 222, 235)"}},{types:["number"],style:{color:"rgb(247, 140, 108)"}},{types:["builtin","char","constant","function"],style:{color:"rgb(130, 170, 255)"}},{types:["punctuation"],style:{color:"rgb(199, 146, 234)"}},{types:["selector","doctype"],style:{color:"rgb(199, 146, 234)",fontStyle:"italic"}},{types:["class-name"],style:{color:"rgb(255, 203, 139)"}},{types:["tag","operator","keyword"],style:{color:"rgb(127, 219, 202)"}},{types:["boolean"],style:{color:"rgb(255, 88, 116)"}},{types:["property"],style:{color:"rgb(128, 203, 196)"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)"}}]},Cd=Ed,Td={plain:{color:"#403f53",backgroundColor:"#FBFBFB"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)",fontStyle:"italic"}},{types:["inserted","attr-name"],style:{color:"rgb(72, 118, 214)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(152, 159, 177)",fontStyle:"italic"}},{types:["string","builtin","char","constant","url"],style:{color:"rgb(72, 118, 214)"}},{types:["variable"],style:{color:"rgb(201, 103, 101)"}},{types:["number"],style:{color:"rgb(170, 9, 130)"}},{types:["punctuation"],style:{color:"rgb(153, 76, 195)"}},{types:["function","selector","doctype"],style:{color:"rgb(153, 76, 195)",fontStyle:"italic"}},{types:["class-name"],style:{color:"rgb(17, 17, 17)"}},{types:["tag"],style:{color:"rgb(153, 76, 195)"}},{types:["operator","property","keyword","namespace"],style:{color:"rgb(12, 150, 155)"}},{types:["boolean"],style:{color:"rgb(188, 84, 84)"}}]},Rd=Td,ie={char:"#D8DEE9",comment:"#999999",keyword:"#c5a5c5",primitive:"#5a9bcf",string:"#8dc891",variable:"#d7deea",boolean:"#ff8b50",punctuation:"#5FB3B3",tag:"#fc929e",function:"#79b6f2",className:"#FAC863",method:"#6699CC",operator:"#fc929e"},Ad={plain:{backgroundColor:"#282c34",color:"#ffffff"},styles:[{types:["attr-name"],style:{color:ie.keyword}},{types:["attr-value"],style:{color:ie.string}},{types:["comment","block-comment","prolog","doctype","cdata","shebang"],style:{color:ie.comment}},{types:["property","number","function-name","constant","symbol","deleted"],style:{color:ie.primitive}},{types:["boolean"],style:{color:ie.boolean}},{types:["tag"],style:{color:ie.tag}},{types:["string"],style:{color:ie.string}},{types:["punctuation"],style:{color:ie.string}},{types:["selector","char","builtin","inserted"],style:{color:ie.char}},{types:["function"],style:{color:ie.function}},{types:["operator","entity","url","variable"],style:{color:ie.variable}},{types:["keyword"],style:{color:ie.keyword}},{types:["atrule","class-name"],style:{color:ie.className}},{types:["important"],style:{fontWeight:"400"}},{types:["bold"],style:{fontWeight:"bold"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["namespace"],style:{opacity:.7}}]},_d=Ad,Id={plain:{color:"#f8f8f2",backgroundColor:"#272822"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"#f92672",fontStyle:"italic"}},{types:["inserted"],style:{color:"rgb(173, 219, 103)",fontStyle:"italic"}},{types:["comment"],style:{color:"#8292a2",fontStyle:"italic"}},{types:["string","url"],style:{color:"#a6e22e"}},{types:["variable"],style:{color:"#f8f8f2"}},{types:["number"],style:{color:"#ae81ff"}},{types:["builtin","char","constant","function","class-name"],style:{color:"#e6db74"}},{types:["punctuation"],style:{color:"#f8f8f2"}},{types:["selector","doctype"],style:{color:"#a6e22e",fontStyle:"italic"}},{types:["tag","operator","keyword"],style:{color:"#66d9ef"}},{types:["boolean"],style:{color:"#ae81ff"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)",opacity:.7}},{types:["tag","property"],style:{color:"#f92672"}},{types:["attr-name"],style:{color:"#a6e22e !important"}},{types:["doctype"],style:{color:"#8292a2"}},{types:["rule"],style:{color:"#e6db74"}}]},Fd=Id,Ld={plain:{color:"#bfc7d5",backgroundColor:"#292d3e"},styles:[{types:["comment"],style:{color:"rgb(105, 112, 152)",fontStyle:"italic"}},{types:["string","inserted"],style:{color:"rgb(195, 232, 141)"}},{types:["number"],style:{color:"rgb(247, 140, 108)"}},{types:["builtin","char","constant","function"],style:{color:"rgb(130, 170, 255)"}},{types:["punctuation","selector"],style:{color:"rgb(199, 146, 234)"}},{types:["variable"],style:{color:"rgb(191, 199, 213)"}},{types:["class-name","attr-name"],style:{color:"rgb(255, 203, 107)"}},{types:["tag","deleted"],style:{color:"rgb(255, 85, 114)"}},{types:["operator"],style:{color:"rgb(137, 221, 255)"}},{types:["boolean"],style:{color:"rgb(255, 88, 116)"}},{types:["keyword"],style:{fontStyle:"italic"}},{types:["doctype"],style:{color:"rgb(199, 146, 234)",fontStyle:"italic"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)"}},{types:["url"],style:{color:"rgb(221, 221, 221)"}}]},Pd=Ld,Dd={plain:{color:"#9EFEFF",backgroundColor:"#2D2A55"},styles:[{types:["changed"],style:{color:"rgb(255, 238, 128)"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)"}},{types:["inserted"],style:{color:"rgb(173, 219, 103)"}},{types:["comment"],style:{color:"rgb(179, 98, 255)",fontStyle:"italic"}},{types:["punctuation"],style:{color:"rgb(255, 255, 255)"}},{types:["constant"],style:{color:"rgb(255, 98, 140)"}},{types:["string","url"],style:{color:"rgb(165, 255, 144)"}},{types:["variable"],style:{color:"rgb(255, 238, 128)"}},{types:["number","boolean"],style:{color:"rgb(255, 98, 140)"}},{types:["attr-name"],style:{color:"rgb(255, 180, 84)"}},{types:["keyword","operator","property","namespace","tag","selector","doctype"],style:{color:"rgb(255, 157, 0)"}},{types:["builtin","char","constant","function","class-name"],style:{color:"rgb(250, 208, 0)"}}]},Od=Dd,$d={plain:{backgroundColor:"linear-gradient(to bottom, #2a2139 75%, #34294f)",backgroundImage:"#34294f",color:"#f92aad",textShadow:"0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3"},styles:[{types:["comment","block-comment","prolog","doctype","cdata"],style:{color:"#495495",fontStyle:"italic"}},{types:["punctuation"],style:{color:"#ccc"}},{types:["tag","attr-name","namespace","number","unit","hexcode","deleted"],style:{color:"#e2777a"}},{types:["property","selector"],style:{color:"#72f1b8",textShadow:"0 0 2px #100c0f, 0 0 10px #257c5575, 0 0 35px #21272475"}},{types:["function-name"],style:{color:"#6196cc"}},{types:["boolean","selector-id","function"],style:{color:"#fdfdfd",textShadow:"0 0 2px #001716, 0 0 3px #03edf975, 0 0 5px #03edf975, 0 0 8px #03edf975"}},{types:["class-name","maybe-class-name","builtin"],style:{color:"#fff5f6",textShadow:"0 0 2px #000, 0 0 10px #fc1f2c75, 0 0 5px #fc1f2c75, 0 0 25px #fc1f2c75"}},{types:["constant","symbol"],style:{color:"#f92aad",textShadow:"0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3"}},{types:["important","atrule","keyword","selector-class"],style:{color:"#f4eee4",textShadow:"0 0 2px #393a33, 0 0 8px #f39f0575, 0 0 2px #f39f0575"}},{types:["string","char","attr-value","regex","variable"],style:{color:"#f87c32"}},{types:["parameter"],style:{fontStyle:"italic"}},{types:["entity","url"],style:{color:"#67cdcc"}},{types:["operator"],style:{color:"ffffffee"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["entity"],style:{cursor:"help"}},{types:["inserted"],style:{color:"green"}}]},Md=$d,Bd={plain:{color:"#282a2e",backgroundColor:"#ffffff"},styles:[{types:["comment"],style:{color:"rgb(197, 200, 198)"}},{types:["string","number","builtin","variable"],style:{color:"rgb(150, 152, 150)"}},{types:["class-name","function","tag","attr-name"],style:{color:"rgb(40, 42, 46)"}}]},zd=Bd,Vd={plain:{color:"#9CDCFE",backgroundColor:"#1E1E1E"},styles:[{types:["prolog"],style:{color:"rgb(0, 0, 128)"}},{types:["comment"],style:{color:"rgb(106, 153, 85)"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"rgb(86, 156, 214)"}},{types:["number","inserted"],style:{color:"rgb(181, 206, 168)"}},{types:["constant"],style:{color:"rgb(100, 102, 149)"}},{types:["attr-name","variable"],style:{color:"rgb(156, 220, 254)"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"rgb(206, 145, 120)"}},{types:["selector"],style:{color:"rgb(215, 186, 125)"}},{types:["tag"],style:{color:"rgb(78, 201, 176)"}},{types:["tag"],languages:["markup"],style:{color:"rgb(86, 156, 214)"}},{types:["punctuation","operator"],style:{color:"rgb(212, 212, 212)"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"rgb(220, 220, 170)"}},{types:["class-name"],style:{color:"rgb(78, 201, 176)"}},{types:["char"],style:{color:"rgb(209, 105, 105)"}}]},sn=Vd,Ud={plain:{color:"#000000",backgroundColor:"#ffffff"},styles:[{types:["comment"],style:{color:"rgb(0, 128, 0)"}},{types:["builtin"],style:{color:"rgb(0, 112, 193)"}},{types:["number","variable","inserted"],style:{color:"rgb(9, 134, 88)"}},{types:["operator"],style:{color:"rgb(0, 0, 0)"}},{types:["constant","char"],style:{color:"rgb(129, 31, 63)"}},{types:["tag"],style:{color:"rgb(128, 0, 0)"}},{types:["attr-name"],style:{color:"rgb(255, 0, 0)"}},{types:["deleted","string"],style:{color:"rgb(163, 21, 21)"}},{types:["changed","punctuation"],style:{color:"rgb(4, 81, 165)"}},{types:["function","keyword"],style:{color:"rgb(0, 0, 255)"}},{types:["class-name"],style:{color:"rgb(38, 127, 153)"}}]},qd=Ud,Gd={plain:{color:"#f8fafc",backgroundColor:"#011627"},styles:[{types:["prolog"],style:{color:"#000080"}},{types:["comment"],style:{color:"#6A9955"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"#569CD6"}},{types:["number","inserted"],style:{color:"#B5CEA8"}},{types:["constant"],style:{color:"#f8fafc"}},{types:["attr-name","variable"],style:{color:"#9CDCFE"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"#cbd5e1"}},{types:["selector"],style:{color:"#D7BA7D"}},{types:["tag"],style:{color:"#0ea5e9"}},{types:["tag"],languages:["markup"],style:{color:"#0ea5e9"}},{types:["punctuation","operator"],style:{color:"#D4D4D4"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"#7dd3fc"}},{types:["class-name"],style:{color:"#0ea5e9"}},{types:["char"],style:{color:"#D16969"}}]},Hd=Gd,Kd={plain:{color:"#0f172a",backgroundColor:"#f1f5f9"},styles:[{types:["prolog"],style:{color:"#000080"}},{types:["comment"],style:{color:"#6A9955"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"#0c4a6e"}},{types:["number","inserted"],style:{color:"#B5CEA8"}},{types:["constant"],style:{color:"#0f172a"}},{types:["attr-name","variable"],style:{color:"#0c4a6e"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"#64748b"}},{types:["selector"],style:{color:"#D7BA7D"}},{types:["tag"],style:{color:"#0ea5e9"}},{types:["tag"],languages:["markup"],style:{color:"#0ea5e9"}},{types:["punctuation","operator"],style:{color:"#475569"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"#0e7490"}},{types:["class-name"],style:{color:"#0ea5e9"}},{types:["char"],style:{color:"#D16969"}}]},Wd=Kd,Zd={plain:{backgroundColor:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)"},styles:[{types:["comment","prolog","cdata"],style:{color:"hsl(220, 10%, 40%)"}},{types:["doctype","punctuation","entity"],style:{color:"hsl(220, 14%, 71%)"}},{types:["attr-name","class-name","maybe-class-name","boolean","constant","number","atrule"],style:{color:"hsl(29, 54%, 61%)"}},{types:["keyword"],style:{color:"hsl(286, 60%, 67%)"}},{types:["property","tag","symbol","deleted","important"],style:{color:"hsl(355, 65%, 65%)"}},{types:["selector","string","char","builtin","inserted","regex","attr-value"],style:{color:"hsl(95, 38%, 62%)"}},{types:["variable","operator","function"],style:{color:"hsl(207, 82%, 66%)"}},{types:["url"],style:{color:"hsl(187, 47%, 55%)"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"hsl(220, 14%, 71%)"}}]},Yd=Zd,Xd={plain:{backgroundColor:"hsl(230, 1%, 98%)",color:"hsl(230, 8%, 24%)"},styles:[{types:["comment","prolog","cdata"],style:{color:"hsl(230, 4%, 64%)"}},{types:["doctype","punctuation","entity"],style:{color:"hsl(230, 8%, 24%)"}},{types:["attr-name","class-name","boolean","constant","number","atrule"],style:{color:"hsl(35, 99%, 36%)"}},{types:["keyword"],style:{color:"hsl(301, 63%, 40%)"}},{types:["property","tag","symbol","deleted","important"],style:{color:"hsl(5, 74%, 59%)"}},{types:["selector","string","char","builtin","inserted","regex","attr-value","punctuation"],style:{color:"hsl(119, 34%, 47%)"}},{types:["variable","operator","function"],style:{color:"hsl(221, 87%, 60%)"}},{types:["url"],style:{color:"hsl(198, 99%, 37%)"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"hsl(230, 8%, 24%)"}}]},Qd=Xd,Jd={plain:{color:"#ebdbb2",backgroundColor:"#292828"},styles:[{types:["imports","class-name","maybe-class-name","constant","doctype","builtin","function"],style:{color:"#d8a657"}},{types:["property-access"],style:{color:"#7daea3"}},{types:["tag"],style:{color:"#e78a4e"}},{types:["attr-name","char","url","regex"],style:{color:"#a9b665"}},{types:["attr-value","string"],style:{color:"#89b482"}},{types:["comment","prolog","cdata","operator","inserted"],style:{color:"#a89984"}},{types:["delimiter","boolean","keyword","selector","important","atrule","property","variable","deleted"],style:{color:"#ea6962"}},{types:["entity","number","symbol"],style:{color:"#d3869b"}}]},eu=Jd,tu={plain:{color:"#654735",backgroundColor:"#f9f5d7"},styles:[{types:["delimiter","boolean","keyword","selector","important","atrule","property","variable","deleted"],style:{color:"#af2528"}},{types:["imports","class-name","maybe-class-name","constant","doctype","builtin"],style:{color:"#b4730e"}},{types:["string","attr-value"],style:{color:"#477a5b"}},{types:["property-access"],style:{color:"#266b79"}},{types:["function","attr-name","char","url"],style:{color:"#72761e"}},{types:["tag"],style:{color:"#b94c07"}},{types:["comment","prolog","cdata","operator","inserted"],style:{color:"#a89984"}},{types:["entity","number","symbol"],style:{color:"#924f79"}}]},su=tu,ru=t=>i.useCallback(s=>{var r=s,{className:a,style:n,line:o}=r,l=tn(r,["className","style","line"]);const c=Ht(ge({},l),{className:ys("token-line",a)});return typeof t=="object"&&"plain"in t&&(c.style=t.plain),typeof n=="object"&&(c.style=ge(ge({},c.style||{}),n)),c},[t]),au=t=>{const s=i.useCallback(({types:r,empty:a})=>{if(t!=null){{if(r.length===1&&r[0]==="plain")return a!=null?{display:"inline-block"}:void 0;if(r.length===1&&a!=null)return t[r[0]]}return Object.assign(a!=null?{display:"inline-block"}:{},...r.map(n=>t[n]))}},[t]);return i.useCallback(r=>{var a=r,{token:n,className:o,style:l}=a,c=tn(a,["token","className","style"]);const d=Ht(ge({},c),{className:ys("token",...n.types,o),children:n.content,style:s(n)});return l!=null&&(d.style=ge(ge({},d.style||{}),l)),d},[s])},nu=/\r\n|\r|\n/,dr=t=>{t.length===0?t.push({types:["plain"],content:` +`,empty:!0}):t.length===1&&t[0].content===""&&(t[0].content=` +`,t[0].empty=!0)},ur=(t,s)=>{const r=t.length;return r>0&&t[r-1]===s?t:t.concat(s)},ou=t=>{const s=[[]],r=[t],a=[0],n=[t.length];let o=0,l=0,c=[];const d=[c];for(;l>-1;){for(;(o=a[l]++)<n[l];){let u,m=s[l];const y=r[l][o];if(typeof y=="string"?(m=l>0?m:["plain"],u=y):(m=ur(m,y.type),y.alias&&(m=ur(m,y.alias)),u=y.content),typeof u!="string"){l++,s.push(m),r.push(u),a.push(0),n.push(u.length);continue}const N=u.split(nu),h=N.length;c.push({types:m,content:N[0]});for(let p=1;p<h;p++)dr(c),d.push(c=[]),c.push({types:m,content:N[p]})}l--,s.pop(),r.pop(),a.pop(),n.pop()}return dr(c),d},pr=ou,iu=({prism:t,code:s,grammar:r,language:a})=>i.useMemo(()=>{if(r==null)return pr([s]);const n={code:s,grammar:r,language:a,tokens:[]};return t.hooks.run("before-tokenize",n),n.tokens=t.tokenize(s,r),t.hooks.run("after-tokenize",n),pr(n.tokens)},[s,r,a,t]),lu=(t,s)=>{const{plain:r}=t,a=t.styles.reduce((n,o)=>{const{languages:l,style:c}=o;return l&&!l.includes(s)||o.types.forEach(d=>{const u=ge(ge({},n[d]),c);n[d]=u}),n},{});return a.root=r,a.plain=Ht(ge({},r),{backgroundColor:void 0}),a},cu=lu,du=({children:t,language:s,code:r,theme:a,prism:n})=>{const o=s.toLowerCase(),l=cu(a,o),c=ru(l),d=au(l),u=n.languages[o],m=iu({prism:n,language:o,code:r,grammar:u});return t({tokens:m,className:`prism-code language-${o}`,style:l!=null?l.root:{},getLineProps:c,getTokenProps:d})},uu=t=>i.createElement(du,Ht(ge({},t),{prism:t.prism||k,theme:t.theme||sn,code:t.code,language:t.language}));/*! Bundled license information: + +prismjs/prism.js: + (** + * Prism: Lightweight, robust, elegant syntax highlighting + * + * @license MIT <https://opensource.org/licenses/MIT> + * @author Lea Verou <https://lea.verou.me> + * @namespace + * @public + *) +*/const pu=(t,s)=>s.some(r=>{if(typeof r=="number")return t===r;const[a,n]=r.split(":").map(o=>parseInt(o));return a<=t&&t<=n}),mu=(t,s,r)=>r.some(([a,[n,o]])=>a===t&&n<=s&&s<=o),gu=(t,s)=>t.split(new RegExp(`(${s.map(([r])=>r).join("|")})`)).filter(Boolean),fu=t=>t.map(s=>{s=s.startsWith("/")?s:"/"+s;const[,r,a="0:Infinity"]=s.split("/"),[n,o=n]=a.split(":").map(l=>Number(l));return[r,[n,o]]}),rn=(t,s)=>()=>{const r=i.useContext(t);if(r===void 0)throw new Error(s);return r},Kt=t=>Object.assign(i.forwardRef(t),{displayName:t.displayName??t.name}),an=i.createContext(void 0),nn=i.createContext(void 0),on=rn(an,'Could not find nearest <CodeBlock /> component. Please wrap this component with a <CodeBlock /> component imported from "react-code-block".'),zs=rn(nn,'Could not find nearest <CodeBlock.Code /> component. Please wrap this component with <CodeBlock.Code /> component imported from "react-code-block".'),ye=({code:t,words:s=[],lines:r=[],children:a,...n})=>{const o=i.useMemo(()=>fu(s),[s]);return e.jsx(an.Provider,{value:{code:t.trim(),words:o,lines:r,...n},children:a})},hu=({as:t,children:s,...r},a)=>{const{lines:n,words:o,...l}=on(),c=t??"pre";return e.jsx(uu,{...l,children:d=>e.jsx(c,{...r,ref:a,children:d.tokens.map((u,m)=>{const f=m+1,y=pu(f,n);return e.jsx(nn.Provider,{value:{highlight:d,line:u,lineNumber:f},children:typeof s=="function"?s({isLineHighlighted:y,lineNumber:f},m):s},m)})})})},xu=({as:t,children:s,className:r,...a},n)=>{const{highlight:o,line:l}=zs(),{getLineProps:c}=o,d=t??"div";return e.jsx(d,{...c({line:l,className:r}),...a,ref:n,children:s})},bu=({as:t,children:s=({children:o})=>e.jsx("span",{children:o}),className:r,...a},n)=>{const{words:o}=on(),{line:l,highlight:c,lineNumber:d}=zs(),{getTokenProps:u}=c,m=t??"span";return e.jsx(Be.Fragment,{children:l.map((f,y)=>{const{children:N,...h}=u({token:f,className:r}),p=o.length?gu(N,o):[N];return e.jsx(Be.Fragment,{children:p.map((g,x)=>e.jsx(m,{...h,...a,ref:n,children:s({children:g,isTokenHighlighted:mu(g,d,o)})},x))},y)})})},yu=({as:t,...s},r)=>{const{lineNumber:a}=zs(),n=t??"span";return e.jsx(n,{...s,ref:r,children:a})};ye.Code=Kt(hu);ye.LineContent=Kt(xu);ye.Token=Kt(bu);ye.LineNumber=Kt(yu);const vu={plain:{color:"var(--foreground)",backgroundColor:"var(--muted)"},styles:[{types:["comment"],style:{color:"#6e7781",fontStyle:"italic"}},{types:["keyword","selector","changed"],style:{color:"#cf222e"}},{types:["constant","number","builtin"],style:{color:"#0550ae"}},{types:["string","attr-value"],style:{color:"#0a3069"}},{types:["function","attr-name"],style:{color:"#8250df"}},{types:["tag","operator"],style:{color:"#116329"}},{types:["variable","property"],style:{color:"#953800"}},{types:["punctuation"],style:{color:"#24292f"}}]},ju={plain:{color:"var(--foreground)",backgroundColor:"var(--muted)"},styles:[{types:["comment"],style:{color:"#8b949e",fontStyle:"italic"}},{types:["keyword","selector","changed"],style:{color:"#ff7b72"}},{types:["constant","number","builtin"],style:{color:"#79c0ff"}},{types:["string","attr-value"],style:{color:"#a5d6ff"}},{types:["function","attr-name"],style:{color:"#d2a8ff"}},{types:["tag","operator"],style:{color:"#7ee787"}},{types:["variable","property"],style:{color:"#ffa657"}},{types:["punctuation"],style:{color:"#c9d1d9"}}]};function as({code:t,language:s="typescript",fileName:r,className:a,maxLines:n=200}){const[o,l]=i.useState(!1),[c,d]=i.useState(!1),{theme:u}=Fi(),m=async()=>{await navigator.clipboard.writeText(t),l(!0),setTimeout(()=>l(!1),2e3)},f=t.split(` +`),y=f.length>n,N=c?t:f.slice(0,n).join(` +`);return e.jsxs("div",{className:v("relative group rounded-lg overflow-hidden",a),children:[r&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b bg-muted/50",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:r}),e.jsxs(q,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:m,children:[o?e.jsx(qe,{className:"h-4 w-4"}):e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Copy code"})]})]}),e.jsx(ye,{code:N,language:s,theme:u==="dark"?ju:vu,children:e.jsx(ye.Code,{className:"bg-muted/50 p-4 text-sm whitespace-pre-wrap break-words",children:e.jsx(ye.LineContent,{className:"max-w-full",children:e.jsx(ye.Token,{})})})}),y&&e.jsx("div",{className:"flex justify-center p-2 border-t bg-muted/50",children:e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>d(!c),className:"flex items-center gap-2",children:c?e.jsxs(e.Fragment,{children:["Show Less ",e.jsx(Tr,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show More (",f.length-n," more lines)"," ",e.jsx(ot,{className:"h-4 w-4"})]})})})]})}function wu(t){const[s,r]=i.useState(null),[a,n]=i.useState(!1),[o,l]=i.useState(null);return i.useEffect(()=>{if(!t){l("Node name is required");return}n(!0),l(null),fetch(`/ui/api/v1/proxy/${t}/ui/api/v1/cluster/nodes/self/details`).then(c=>{if(!c.ok)throw new Error(`Failed to fetch node details: ${c.statusText}`);return c.json()}).then(c=>{var d,u;c.target=((u=(d=c.config.match(/target:\s*([^\n]+)/))==null?void 0:d[1])==null?void 0:u.trim())||"",r(c),n(!1)}).catch(c=>{l(c instanceof Error?c.message:"An error occurred"),n(!1)})},[t]),{nodeDetails:s,isLoading:a,error:o}}function Nu(t,s){const[r,a]=i.useState(!1),[n,o]=i.useState(null),[l,c]=i.useState("");return i.useEffect(()=>{if(!s){c("");return}if(!t)return;const d=new AbortController;async function u(){a(!0),o(null);try{const m=await fetch(`/ui/api/v1/proxy/${t}/metrics`,{signal:d.signal});if(!m.ok)throw new Error(`Failed to fetch metrics: ${m.statusText}`);const f=await m.text();c(f)}catch(m){m instanceof Error?o(m.message):o("An unknown error occurred")}finally{a(!1)}}return u(),()=>{d.abort()}},[t,s]),{isLoading:r,error:n,metrics:l}}const ku={Running:"#10B981",Starting:"#F59E0B",New:"#3B82F6",Stopping:"#F59E0B",Terminated:"#6B7280",Failed:"#EF4444"};function Su({services:t}){const s=i.useMemo(()=>{const a=t.reduce((n,{status:o})=>{const l=o;return n.set(l,(n.get(l)||0)+1),n},new Map);return Array.from(a.entries()).sort((n,o)=>o[1]-n[1]).map(([n,o])=>({name:n,value:o,color:ku[n]}))},[t]),r=i.useMemo(()=>t.length,[t]);return s.length===0?null:e.jsxs("div",{className:"h-[180px] w-full flex items-center",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center pointer-events-none z-10",children:[e.jsx("div",{className:"text-2xl font-bold",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Services"})]}),e.jsx(ct,{width:"100%",height:180,children:e.jsxs(Dt,{margin:{top:0,right:0,bottom:0,left:0},children:[e.jsx(Ot,{data:s,cx:"50%",cy:"50%",labelLine:!1,outerRadius:70,innerRadius:50,dataKey:"value",paddingAngle:2,strokeWidth:2,children:s.map(a=>e.jsx($t,{fill:a.color,stroke:"hsl(var(--background))"},`cell-${a.name}`))}),e.jsx(dt,{content:({active:a,payload:n})=>{if(!a||!n||!n[0])return null;const o=n[0].payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm",style:{backgroundColor:o.color}}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx("span",{className:"text-sm font-semibold",children:o.value})]})}})]})})]}),e.jsx("div",{className:"flex flex-col gap-1.5 min-w-[120px] pl-4",children:s.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:a.color}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]}),e.jsx("span",{className:"font-medium tabular-nums",children:a.value})]},a.name))})]})}const Eu=t=>{switch(t){case"Running":return"text-green-600 dark:text-green-400";case"Starting":return"text-yellow-600 dark:text-yellow-400";case"Failed":return"text-red-600 dark:text-red-400";case"New":return"text-blue-600 dark:text-blue-400";case"Terminated":return"text-gray-600 dark:text-gray-400";default:return"text-gray-600 dark:text-gray-400"}};function Cu({services:t}){return e.jsx(pt,{className:"h-[180px] rounded-md border",children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{children:[e.jsx(D,{children:"Service"}),e.jsx(D,{className:"text-right",children:"Status"})]})}),e.jsx(Re,{children:t.map(s=>e.jsxs(X,{className:"hover:bg-muted/50",children:[e.jsx(F,{className:"font-medium",children:s.service}),e.jsx(F,{className:`text-right ${Eu(s.status)} font-medium`,children:s.status})]},s.service))})]})})}const Tu={aws:"text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400","aws-dynamo":"text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400",s3:"text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400",azure:"text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400",gcp:"text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400","gcp-columnkey":"text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400",gcs:"text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400",alibabacloud:"text-orange-600 bg-orange-100 dark:bg-orange-950 dark:text-orange-400",filesystem:"text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400",local:"text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400",boltdb:"text-emerald-600 bg-emerald-100 dark:bg-emerald-950 dark:text-emerald-400",cassandra:"text-blue-700 bg-blue-100 dark:bg-blue-950 dark:text-blue-400",bigtable:"text-red-600 bg-red-100 dark:bg-red-950 dark:text-red-400","bigtable-hashed":"text-red-600 bg-red-100 dark:bg-red-950 dark:text-red-400",bos:"text-cyan-600 bg-cyan-100 dark:bg-cyan-950 dark:text-cyan-400",cos:"text-green-600 bg-green-100 dark:bg-green-950 dark:text-green-400",swift:"text-orange-600 bg-orange-100 dark:bg-orange-950 dark:text-orange-400",inmemory:"text-purple-600 bg-purple-100 dark:bg-purple-950 dark:text-purple-400","grpc-store":"text-indigo-600 bg-indigo-100 dark:bg-indigo-950 dark:text-indigo-400"};function Ru({type:t,className:s}){const r=t.toLowerCase(),a=Tu[r]||"text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400";return e.jsx("span",{className:v("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",a,s),children:r})}const Au=Ee("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),le=i.forwardRef(({className:t,...s},r)=>e.jsx(yr,{ref:r,className:v(Au(),t),...s}));le.displayName=yr.displayName;function _u(t){const[s,r]=i.useState("info"),[a,n]=i.useState(!1),[o,l]=i.useState(null),[c,d]=i.useState(!1),u=f=>{const y=f.message.match(/Current log level is (\w+)/);return(y==null?void 0:y[1])||"info"};return i.useEffect(()=>{async function f(){if(t){n(!0),l(null);try{const y=await fetch(`/ui/api/v1/proxy/${t}/log_level`);if(!y.ok)throw new Error(`Failed to fetch log level: ${y.statusText}`);const N=await y.json();r(u(N))}catch(y){l(y instanceof Error?y.message:"Failed to fetch log level")}finally{n(!1)}}}f()},[t]),{logLevel:s,isLoading:a,error:o,success:c,setLogLevel:async f=>{if(t){n(!0),l(null),d(!1);try{const y=await fetch(`/ui/api/v1/proxy/${t}/log_level?log_level=${f}`,{method:"POST"});if(!y.ok)throw new Error(`Failed to update log level: ${y.statusText}`);const N=await y.json();if(N.status==="success"&&N.message.includes(f))r(f),d(!0),setTimeout(()=>d(!1),3e3);else throw new Error("Failed to update log level: Unexpected response")}catch(y){l(y instanceof Error?y.message:"Failed to update log level")}finally{n(!1)}}}}}const Iu=["debug","info","warn","error"];function Fu({nodeName:t,className:s}){const{logLevel:r,isLoading:a,error:n,success:o,setLogLevel:l}=_u(t),c=d=>{l(d)};return e.jsxs("div",{className:"relative flex items-center gap-2",children:[e.jsxs(Tt,{value:r,onValueChange:c,disabled:a,children:[e.jsx(et,{className:v("w-[180px]",s,a&&"opacity-50 cursor-not-allowed"),children:e.jsx(Rt,{placeholder:"Select log level"})}),e.jsx(tt,{children:Iu.map(d=>e.jsx(ze,{value:d,children:d},d))})]}),e.jsx(Ms,{children:e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsxs("div",{className:v("absolute -right-6 transition-all duration-300 ease-in-out",o||n?"opacity-100 translate-x-0":"opacity-0 translate-x-2"),children:[o&&e.jsx(qe,{className:"h-4 w-4 text-green-500 animate-in zoom-in-50 duration-300"}),n&&e.jsx(nt,{className:"h-4 w-4 text-red-500 animate-in zoom-in-50 duration-300"})]})}),e.jsxs(Ue,{side:"right",className:"text-xs",children:[o&&"Log level updated successfully",n&&n]})]})})]})}const ln=i.forwardRef(({className:t,...s},r)=>e.jsx(Br,{className:v("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...s,ref:r,children:e.jsx(di,{className:v("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));ln.displayName=Br.displayName;function Lu(t){return js({tag:"svg",attr:{viewBox:"0 0 384 512"},child:[{tag:"path",attr:{d:"M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z"},child:[]}]})(t)}function Pu(t){return js({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M220.8 123.3c1 .5 1.8 1.7 3 1.7 1.1 0 2.8-.4 2.9-1.5.2-1.4-1.9-2.3-3.2-2.9-1.7-.7-3.9-1-5.5-.1-.4.2-.8.7-.6 1.1.3 1.3 2.3 1.1 3.4 1.7zm-21.9 1.7c1.2 0 2-1.2 3-1.7 1.1-.6 3.1-.4 3.5-1.6.2-.4-.2-.9-.6-1.1-1.6-.9-3.8-.6-5.5.1-1.3.6-3.4 1.5-3.2 2.9.1 1 1.8 1.5 2.8 1.4zM420 403.8c-3.6-4-5.3-11.6-7.2-19.7-1.8-8.1-3.9-16.8-10.5-22.4-1.3-1.1-2.6-2.1-4-2.9-1.3-.8-2.7-1.5-4.1-2 9.2-27.3 5.6-54.5-3.7-79.1-11.4-30.1-31.3-56.4-46.5-74.4-17.1-21.5-33.7-41.9-33.4-72C311.1 85.4 315.7.1 234.8 0 132.4-.2 158 103.4 156.9 135.2c-1.7 23.4-6.4 41.8-22.5 64.7-18.9 22.5-45.5 58.8-58.1 96.7-6 17.9-8.8 36.1-6.2 53.3-6.5 5.8-11.4 14.7-16.6 20.2-4.2 4.3-10.3 5.9-17 8.3s-14 6-18.5 14.5c-2.1 3.9-2.8 8.1-2.8 12.4 0 3.9.6 7.9 1.2 11.8 1.2 8.1 2.5 15.7.8 20.8-5.2 14.4-5.9 24.4-2.2 31.7 3.8 7.3 11.4 10.5 20.1 12.3 17.3 3.6 40.8 2.7 59.3 12.5 19.8 10.4 39.9 14.1 55.9 10.4 11.6-2.6 21.1-9.6 25.9-20.2 12.5-.1 26.3-5.4 48.3-6.6 14.9-1.2 33.6 5.3 55.1 4.1.6 2.3 1.4 4.6 2.5 6.7v.1c8.3 16.7 23.8 24.3 40.3 23 16.6-1.3 34.1-11 48.3-27.9 13.6-16.4 36-23.2 50.9-32.2 7.4-4.5 13.4-10.1 13.9-18.3.4-8.2-4.4-17.3-15.5-29.7zM223.7 87.3c9.8-22.2 34.2-21.8 44-.4 6.5 14.2 3.6 30.9-4.3 40.4-1.6-.8-5.9-2.6-12.6-4.9 1.1-1.2 3.1-2.7 3.9-4.6 4.8-11.8-.2-27-9.1-27.3-7.3-.5-13.9 10.8-11.8 23-4.1-2-9.4-3.5-13-4.4-1-6.9-.3-14.6 2.9-21.8zM183 75.8c10.1 0 20.8 14.2 19.1 33.5-3.5 1-7.1 2.5-10.2 4.6 1.2-8.9-3.3-20.1-9.6-19.6-8.4.7-9.8 21.2-1.8 28.1 1 .8 1.9-.2-5.9 5.5-15.6-14.6-10.5-52.1 8.4-52.1zm-13.6 60.7c6.2-4.6 13.6-10 14.1-10.5 4.7-4.4 13.5-14.2 27.9-14.2 7.1 0 15.6 2.3 25.9 8.9 6.3 4.1 11.3 4.4 22.6 9.3 8.4 3.5 13.7 9.7 10.5 18.2-2.6 7.1-11 14.4-22.7 18.1-11.1 3.6-19.8 16-38.2 14.9-3.9-.2-7-1-9.6-2.1-8-3.5-12.2-10.4-20-15-8.6-4.8-13.2-10.4-14.7-15.3-1.4-4.9 0-9 4.2-12.3zm3.3 334c-2.7 35.1-43.9 34.4-75.3 18-29.9-15.8-68.6-6.5-76.5-21.9-2.4-4.7-2.4-12.7 2.6-26.4v-.2c2.4-7.6.6-16-.6-23.9-1.2-7.8-1.8-15 .9-20 3.5-6.7 8.5-9.1 14.8-11.3 10.3-3.7 11.8-3.4 19.6-9.9 5.5-5.7 9.5-12.9 14.3-18 5.1-5.5 10-8.1 17.7-6.9 8.1 1.2 15.1 6.8 21.9 16l19.6 35.6c9.5 19.9 43.1 48.4 41 68.9zm-1.4-25.9c-4.1-6.6-9.6-13.6-14.4-19.6 7.1 0 14.2-2.2 16.7-8.9 2.3-6.2 0-14.9-7.4-24.9-13.5-18.2-38.3-32.5-38.3-32.5-13.5-8.4-21.1-18.7-24.6-29.9s-3-23.3-.3-35.2c5.2-22.9 18.6-45.2 27.2-59.2 2.3-1.7.8 3.2-8.7 20.8-8.5 16.1-24.4 53.3-2.6 82.4.6-20.7 5.5-41.8 13.8-61.5 12-27.4 37.3-74.9 39.3-112.7 1.1.8 4.6 3.2 6.2 4.1 4.6 2.7 8.1 6.7 12.6 10.3 12.4 10 28.5 9.2 42.4 1.2 6.2-3.5 11.2-7.5 15.9-9 9.9-3.1 17.8-8.6 22.3-15 7.7 30.4 25.7 74.3 37.2 95.7 6.1 11.4 18.3 35.5 23.6 64.6 3.3-.1 7 .4 10.9 1.4 13.8-35.7-11.7-74.2-23.3-84.9-4.7-4.6-4.9-6.6-2.6-6.5 12.6 11.2 29.2 33.7 35.2 59 2.8 11.6 3.3 23.7.4 35.7 16.4 6.8 35.9 17.9 30.7 34.8-2.2-.1-3.2 0-4.2 0 3.2-10.1-3.9-17.6-22.8-26.1-19.6-8.6-36-8.6-38.3 12.5-12.1 4.2-18.3 14.7-21.4 27.3-2.8 11.2-3.6 24.7-4.4 39.9-.5 7.7-3.6 18-6.8 29-32.1 22.9-76.7 32.9-114.3 7.2zm257.4-11.5c-.9 16.8-41.2 19.9-63.2 46.5-13.2 15.7-29.4 24.4-43.6 25.5s-26.5-4.8-33.7-19.3c-4.7-11.1-2.4-23.1 1.1-36.3 3.7-14.2 9.2-28.8 9.9-40.6.8-15.2 1.7-28.5 4.2-38.7 2.6-10.3 6.6-17.2 13.7-21.1.3-.2.7-.3 1-.5.8 13.2 7.3 26.6 18.8 29.5 12.6 3.3 30.7-7.5 38.4-16.3 9-.3 15.7-.9 22.6 5.1 9.9 8.5 7.1 30.3 17.1 41.6 10.6 11.6 14 19.5 13.7 24.6zM173.3 148.7c2 1.9 4.7 4.5 8 7.1 6.6 5.2 15.8 10.6 27.3 10.6 11.6 0 22.5-5.9 31.8-10.8 4.9-2.6 10.9-7 14.8-10.4s5.9-6.3 3.1-6.6-2.6 2.6-6 5.1c-4.4 3.2-9.7 7.4-13.9 9.8-7.4 4.2-19.5 10.2-29.9 10.2s-18.7-4.8-24.9-9.7c-3.1-2.5-5.7-5-7.7-6.9-1.5-1.4-1.9-4.6-4.3-4.9-1.4-.1-1.8 3.7 1.7 6.5z"},child:[]}]})(t)}function Du(t){return js({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 93.7l183.6-25.3v177.4H0V93.7zm0 324.6l183.6 25.3V268.4H0v149.9zm203.8 28L448 480V268.4H203.8v177.9zm0-380.6v180.1H448V32L203.8 65.7z"},child:[]}]})(t)}const Ou=t=>{const s=t.toLowerCase();return s.includes("darwin")||s.includes("mac")?e.jsx(Lu,{className:"h-4 w-4"}):s.includes("linux")?e.jsx(Pu,{className:"h-4 w-4"}):s.includes("windows")?e.jsx(Du,{className:"h-4 w-4"}):null},$u=t=>{const s=t.toLowerCase();return s==="oss"?"bg-blue-500/20 text-blue-700 dark:bg-blue-500/30 dark:text-blue-300 hover:bg-blue-500/30":s==="enterprise"?"bg-yellow-500/20 text-yellow-700 dark:bg-yellow-500/30 dark:text-yellow-300 hover:bg-yellow-500/30":""};function Mu({build:t,edition:s,os:r,arch:a}){const n=Ou(r);return e.jsxs(ee,{children:[e.jsx(se,{children:e.jsx(ae,{children:"Version Information"})}),e.jsx(te,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Version"}),e.jsx("p",{className:"text-sm",children:t.version})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Branch"}),e.jsx("p",{className:"text-sm",children:t.branch})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Go Version"}),e.jsx("p",{className:"text-sm",children:t.goVersion})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Edition"}),e.jsx("div",{children:e.jsx(be,{className:$u(s),children:s.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Architecture"}),e.jsx("p",{className:"text-sm",children:a})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"OS"}),e.jsxs("div",{className:"flex items-center gap-2",children:[n,e.jsx("p",{className:"text-sm",children:r})]})]})]})]})})]})}function Bu({nodeName:t,className:s}){const[r,a]=i.useState({isReady:!1,message:"Checking status..."}),[n,o]=i.useState(!0);return i.useEffect(()=>{const l=async()=>{try{const u=await fetch(`/ui/api/v1/proxy/${t}/ready`),m=await u.text();a({isReady:u.ok&&m.includes("ready"),message:u.ok?"Ready":m})}catch(u){a({isReady:!1,message:u instanceof Error?u.message:"Failed to check status"})}};l();const c=setInterval(l,3e3),d=setInterval(()=>{o(u=>!u)},1e3);return()=>{clearInterval(c),clearInterval(d)}},[t]),e.jsxs("div",{className:v("flex items-center gap-2",s),children:[e.jsx("span",{className:v("text-sm",r.isReady?"text-muted-foreground":"text-red-500"),children:r.message}),e.jsx("div",{className:v("h-2.5 w-2.5 rounded-full transition-opacity duration-150",r.isReady?"bg-green-500":"bg-red-500",n?"opacity-100":"opacity-30")})]})}const zu=[{name:"allocs",description:"A sampling of all past memory allocations"},{name:"block",description:"Stack traces that led to blocking on synchronization primitives"},{name:"heap",description:"A sampling of memory allocations of live objects"},{name:"mutex",description:"Stack traces of holders of contended mutexes"},{name:"profile",urlSuffix:"?seconds=15",description:"CPU profile (15 seconds)",displayName:"profile"},{name:"goroutine",description:"Stack traces of all current goroutines (debug=1)",variants:[{suffix:"?debug=0",label:"Basic",description:"Basic goroutine info"},{suffix:"?debug=1",label:"Standard",description:"Standard goroutine stack traces"},{suffix:"?debug=2",label:"Full",description:"Full goroutine stack dump with additional info"}]},{name:"threadcreate",description:"Stack traces that led to the creation of new OS threads",urlSuffix:"?debug=1",displayName:"threadcreate"},{name:"trace",description:"A trace of execution of the current program",urlSuffix:"?debug=1",displayName:"trace"}];function Vu({nodeName:t}){const s=r=>{window.open(`/ui/api/v1/proxy/${t}/debug/pprof/${r}`,"_blank")};return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Profiling Tools:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:zu.map(r=>r.variants?r.variants.map(a=>e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>s(`${r.name}${a.suffix}`),children:`${r.name} (${a.label})`})}),e.jsx(Ue,{children:e.jsx("p",{children:a.description})})]},`${r.name}${a.suffix}`)):e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>s(`${r.name}${r.urlSuffix||""}`),children:r.displayName||r.name})}),e.jsx(Ue,{children:e.jsx("p",{children:r.description})})]},r.name))})]})}function Uu(){const{nodeName:t}=Nr(),[s,r]=i.useState("config"),{nodeDetails:a,isLoading:n,error:o}=wu(t),{metrics:l,isLoading:c,error:d}=Nu(t,s==="raw-metrics"),[u,m]=i.useState(!1);return n?e.jsx("div",{className:"container space-y-6 p-6",children:e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading..."})]})}):a?e.jsx(ke,{children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-1",children:e.jsx(ae,{children:e.jsx("h2",{className:"text-3xl font-semibold tracking-tight",children:e.jsxs("div",{className:"flex items-center gap-2",children:[a.target," - ",t,e.jsx($s,{text:t||""})]})})})}),e.jsx(Bu,{nodeName:t||""})]})}),e.jsxs(te,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(Mu,{build:a.build,edition:a.edition,os:a.os,arch:a.arch}),e.jsxs(ee,{children:[e.jsx(se,{children:e.jsx(ae,{children:"Cluster Information"})}),e.jsx(te,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Cluster ID"}),e.jsx("p",{className:"text-sm",children:a.clusterID})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Created"}),e.jsx("p",{className:"text-sm",children:wt(a.clusterSeededAt,"PPpp")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Storage"}),e.jsx("p",{children:e.jsx(Ru,{type:(a.metrics.store_object_type||"filesystem").toLowerCase(),className:""})})]})]})})]}),e.jsxs(ee,{children:[e.jsxs(se,{className:"flex flex-row items-center justify-between",children:[e.jsx(ae,{children:"Service Status"}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(le,{htmlFor:"view-mode",children:"Table View"}),e.jsx(ln,{id:"view-mode",checked:u,onCheckedChange:m})]})]}),e.jsx(te,{children:u?e.jsx(Cu,{services:a.services}):e.jsx(Su,{services:a.services})})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mr-4",children:[e.jsx(le,{children:"Log Level"}),e.jsx(Fu,{nodeName:t||""})]}),e.jsx(Vu,{nodeName:t||""})]}),e.jsx("div",{children:e.jsxs(od,{defaultValue:"config",onValueChange:r,children:[e.jsxs(Qa,{children:[e.jsx(yt,{value:"config",children:"Configuration"}),e.jsx(yt,{value:"metrics",children:"Analytics"}),e.jsx(yt,{value:"raw-metrics",children:"Raw Metrics"})]}),e.jsx(vt,{value:"config",className:"mt-6",children:e.jsx(as,{language:"yaml",code:a.config,fileName:"loki.yaml"})}),e.jsx(vt,{value:"metrics",className:"mt-6",children:a.metrics&&e.jsx(as,{code:JSON.stringify(a.metrics,null,2),language:"json",fileName:"analytics.json"})}),e.jsx(vt,{value:"raw-metrics",className:"mt-6",children:c?e.jsxs("div",{className:"flex items-center justify-center p-6",children:[e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading metrics..."})]}):d?e.jsx("div",{className:"bg-red-50 dark:bg-red-900 border-l-4 border-red-400 p-4",children:e.jsx("p",{className:"text-sm text-red-700 dark:text-red-200",children:d})}):l?e.jsx(as,{code:l,language:"yaml",fileName:"metrics"}):null})]})})]})]})}):e.jsx("div",{className:"container space-y-6 p-6",children:e.jsx("div",{className:"bg-red-50 dark:bg-red-900 border-l-4 border-red-400 p-4",children:e.jsx("div",{className:"flex",children:e.jsx("div",{className:"ml-3",children:e.jsx("p",{className:"text-sm text-red-700 dark:text-red-200",children:o||`Node "${t}" not found`})})})})})}function qu(){return e.jsx(Xa,{children:e.jsx(Uu,{})})}function Ae(){return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[80vh] p-4",children:[e.jsx(Uo,{className:"h-16 w-16 text-muted-foreground mb-6"}),e.jsx("h1",{className:"text-4xl font-bold text-center mb-4",children:"Coming Soon"}),e.jsx("p",{className:"text-lg text-muted-foreground text-center max-w-md",children:"We're working hard to bring you this feature. Stay tuned for updates!"})]})}const cn=Ee("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),Gu=i.forwardRef(({className:t,variant:s,size:r,...a},n)=>e.jsx(zr,{ref:n,className:v(cn({variant:s,size:r,className:t})),...a}));Gu.displayName=zr.displayName;const dn=i.createContext({size:"default",variant:"default"}),un=i.forwardRef(({className:t,variant:s,size:r,children:a,...n},o)=>e.jsx(Vr,{ref:o,className:v("flex items-center justify-center gap-1",t),...n,children:e.jsx(dn.Provider,{value:{variant:s,size:r},children:a})}));un.displayName=Vr.displayName;const pn=i.forwardRef(({className:t,children:s,variant:r,size:a,...n},o)=>{const l=i.useContext(dn);return e.jsx(Ur,{ref:o,className:v(cn({variant:l.variant||r,size:l.size||a}),t),...n,children:s})});pn.displayName=Ur.displayName;const _t={Received:"received",Processing:"processed"},Hu=t=>{const{cluster:s}=ue(),r=i.useMemo(()=>Oe(s==null?void 0:s.members,ya.compactor),[s==null?void 0:s.members]),{data:a,isLoading:n,error:o}=Mt({queryKey:["deletes",t,r],queryFn:async()=>{try{return(await Promise.all(t.map(async c=>{const d=await fetch(`/ui/api/v1/proxy/${r}/compactor/ui/api/v1/deletes?status=${c}`);if(!d.ok){const u=await d.text();throw new Error(u||`HTTP error! status: ${d.status}`)}return d.json()}))).flat()}catch(l){throw l instanceof Error?l:new Error("Failed to fetch delete requests")}},enabled:!!r});return{data:a,isLoading:n,error:o}},Ku=({selectedStatus:t,onStatusChange:s,queryFilter:r,onQueryFilterChange:a})=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Status"}),e.jsx(un,{type:"multiple",value:t,onValueChange:n=>{n.length>0&&s(n)},className:"justify-start",children:Object.entries(_t).map(([n,o])=>e.jsx(pn,{value:o,"aria-label":`Toggle ${n.toLowerCase()} status`,className:"capitalize",children:n},o))})]}),e.jsx(xe,{type:"search",placeholder:"Filter by query...",value:r,onChange:n=>a(n.target.value),className:"w-[300px]"})]}),Wu=({status:t})=>{const s=t===_t.Received?"secondary":"default";return e.jsx(be,{variant:s,className:"capitalize",children:t})},Zu=({start:t,end:s})=>{const r=Jo(Zs(t/1e3),Zs(s/1e3)),a=n=>{const o=new Date(n);return wt(new Date(o.getTime()+o.getTimezoneOffset()*6e4),"yyyy-MM-dd HH:mm:ss")};return e.jsxs(Vt,{children:[e.jsx(Ut,{children:e.jsx("span",{className:"cursor-default",children:r})}),e.jsx(mt,{className:"w-fit",children:e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"From"}),e.jsx("span",{className:"font-mono",children:a(t)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center",children:"To"}),e.jsx("span",{className:"font-mono",children:a(s)})]})]})})})]})},Yu=({requests:t,sortField:s,sortDirection:r,onSort:a})=>{const n=[...t].sort((o,l)=>{let c=0,d,u;switch(s){case"status":c=o.status.localeCompare(l.status);break;case"user":c=o.user_id.localeCompare(l.user_id);break;case"createdAt":c=o.created_at-l.created_at;break;case"duration":d=o.end_time-o.start_time,u=l.end_time-l.start_time,c=d-u;break}return r==="asc"?c:-c});return e.jsx("div",{className:"rounded-md border bg-card",children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{className:"hover:bg-transparent",children:[e.jsx(D,{className:"w-[80px]",children:e.jsx(Z,{title:"Status",field:"status",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[100px]",children:e.jsx(Z,{title:"User",field:"user",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[200px]",children:e.jsx(Z,{title:"Created At",field:"createdAt",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[150px]",children:e.jsx(Z,{title:"Range",field:"duration",sortField:s,sortDirection:r,onSort:a})}),e.jsx(D,{className:"w-[100px]",children:"Deleted Lines"}),e.jsx(D,{children:"Query"})]})}),e.jsxs(Re,{children:[n.map(o=>e.jsxs(X,{children:[e.jsx(F,{className:"px-4",children:e.jsx(Wu,{status:o.status})}),e.jsx(F,{children:o.user_id}),e.jsx(F,{children:e.jsx(Os,{date:new Date(o.created_at)})}),e.jsx(F,{children:e.jsx(Zu,{start:o.start_time,end:o.end_time})}),e.jsx(F,{children:o.deleted_lines}),e.jsx(F,{children:e.jsx("code",{className:"font-mono text-sm whitespace-pre-wrap break-all",children:o.query})})]},`${o.request_id}-${o.start_time}-${o.end_time}`)),n.length===0&&e.jsx(X,{children:e.jsx(F,{colSpan:7,className:"h-24 text-center",children:e.jsx("div",{className:"text-muted-foreground",children:"No delete requests found"})})})]})]})})},Xu=()=>{const[t,s]=i.useState([_t.Received,_t.Processing]),[r,a]=i.useState(""),[n,o]=i.useState("createdAt"),[l,c]=i.useState("desc"),{data:d,isLoading:u,error:m}=Hu(t),f=i.useMemo(()=>!d||!r?d:d.filter(N=>N.query.toLowerCase().includes(r.toLowerCase())),[d,r]),y=N=>{N===n?c(l==="asc"?"desc":"asc"):(o(N),c("desc"))};return e.jsx(ke,{children:e.jsxs(ee,{className:"shadow-sm",children:[e.jsx(se,{children:e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-semibold tracking-tight",children:"Delete Requests"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View and manage delete requests in your cluster"})]}),e.jsx(q,{variant:"default",asChild:!0,children:e.jsxs(ce,{to:"/tenants/deletes/new",children:[e.jsx(qo,{className:"mr-2 h-4 w-4"}),"New Delete Request"]})})]}),e.jsx(Ku,{selectedStatus:t,onStatusChange:s,queryFilter:r,onQueryFilterChange:a})]})}),e.jsx(te,{children:e.jsxs("div",{className:"space-y-4",children:[m&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(nt,{className:"h-4 w-4"}),e.jsx(He,{children:"Error"}),e.jsx(Ke,{children:m.message})]}),u&&e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(he,{className:"h-16 w-16 animate-spin"})}),!u&&!m&&f&&e.jsx(Yu,{requests:f,sortField:n,sortDirection:l,onSort:y})]})})]})})},mn=Pi,gn=i.createContext({}),Ie=({...t})=>e.jsx(gn.Provider,{value:{name:t.name},children:e.jsx(Di,{...t})}),Wt=()=>{const t=i.useContext(gn),s=i.useContext(fn),{getFieldState:r,formState:a}=Li(),n=r(t.name,a);if(!t)throw new Error("useFormField should be used within <FormField>");const{id:o}=s;return{id:o,name:t.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...n}},fn=i.createContext({}),ve=i.forwardRef(({className:t,...s},r)=>{const a=i.useId();return e.jsx(fn.Provider,{value:{id:a},children:e.jsx("div",{ref:r,className:v("space-y-2",t),...s})})});ve.displayName="FormItem";const fe=i.forwardRef(({className:t,...s},r)=>{const{error:a,formItemId:n}=Wt();return e.jsx(le,{ref:r,className:v(a&&"text-destructive",t),htmlFor:n,...s})});fe.displayName="FormLabel";const je=i.forwardRef(({...t},s)=>{const{error:r,formItemId:a,formDescriptionId:n,formMessageId:o}=Wt();return e.jsx(Se,{ref:s,id:a,"aria-describedby":r?`${n} ${o}`:`${n}`,"aria-invalid":!!r,...t})});je.displayName="FormControl";const hn=i.forwardRef(({className:t,...s},r)=>{const{formDescriptionId:a}=Wt();return e.jsx("p",{ref:r,id:a,className:v("text-[0.8rem] text-muted-foreground",t),...s})});hn.displayName="FormDescription";const we=i.forwardRef(({className:t,children:s,...r},a)=>{const{error:n,formMessageId:o}=Wt(),l=n?String(n==null?void 0:n.message):s;return l?e.jsx("p",{ref:a,id:o,className:v("text-[0.8rem] font-medium text-destructive",t),...r,children:l}):null});we.displayName="FormMessage";const xn=i.forwardRef(({className:t,...s},r)=>e.jsx("textarea",{className:v("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:r,...s}));xn.displayName="Textarea";var Qu=function(t,s){for(var r={};t.length;){var a=t[0],n=a.code,o=a.message,l=a.path.join(".");if(!r[l])if("unionErrors"in a){var c=a.unionErrors[0].errors[0];r[l]={message:c.message,type:c.code}}else r[l]={message:o,type:n};if("unionErrors"in a&&a.unionErrors.forEach(function(m){return m.errors.forEach(function(f){return t.push(f)})}),s){var d=r[l].types,u=d&&d[a.code];r[l]=Mi(l,s,r,n,u?[].concat(u,a.message):a.message)}t.shift()}return r},bn=function(t,s,r){return r===void 0&&(r={}),function(a,n,o){try{return Promise.resolve(function(l,c){try{var d=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](a,s)).then(function(u){return o.shouldUseNativeValidation&&Oi({},o),{errors:{},values:r.raw?a:u}})}catch(u){return c(u)}return d&&d.then?d.then(void 0,c):d}(0,function(l){if(function(c){return Array.isArray(c==null?void 0:c.errors)}(l))return{values:{},errors:$i(Qu(l.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw l}))}catch(l){return Promise.reject(l)}}};const Ju=ia({tenant_id:Ye().min(1,"Tenant ID is required"),query:Ye().min(1,"Query is required"),start_time:Xs(),end_time:Xs().refine(t=>t>new Date(Date.now()-7*24*60*60*1e3),"End time must be after start time")}),ep=()=>{const t=It(),s=Ai(),[r,a]=i.useState(null),[n,o]=i.useState(!1),{cluster:l}=ue(),c=i.useMemo(()=>Oe(l==null?void 0:l.members,ya.compactor),[l==null?void 0:l.members]),d=la({resolver:bn(Ju),defaultValues:{tenant_id:"",query:"",start_time:new Date(Date.now()-7*24*60*60*1e3),end_time:new Date}}),u=i.useCallback(async(N,h=!1)=>{if(N.trim()){o(!0);try{const p=await fetch(`/ui/api/v1/proxy/${c}/loki/api/v1/format_query?query=${N}`,{method:"POST"}),g=await p.json();if(!p.ok||g.status==="invalid-query")throw new Error(g.error||"Invalid LogQL query");d.clearErrors("query"),h&&d.setValue("query",g.data)}catch(p){d.setError("query",{message:p instanceof Error?p.message:"Invalid LogQL query"})}finally{o(!1)}}},[d,c]),m=i.useMemo(()=>ki(N=>u(N,!1),1e3),[u]),f=async N=>{const h=new URLSearchParams;h.append("query",N.query),h.append("start",Math.floor(N.start_time.getTime()/1e3).toString()),h.append("end",Math.floor(N.end_time.getTime()/1e3).toString());try{const p=await fetch(`/ui/api/v1/proxy/${c}/compactor/ui/api/v1/deletes?${h.toString()}`,{method:"POST",headers:{"X-Scope-OrgID":N.tenant_id}});if(!p.ok){const g=await p.text();throw new Error(g||"Failed to create delete request")}await s.invalidateQueries({queryKey:["deletes"]}),t("/tenants/deletes")}catch(p){console.error("Error creating delete request:",p),a(p instanceof Error?p.message:"Failed to create delete request")}},y=i.useMemo(()=>{const N=d.watch("start_time"),h=d.watch("end_time");return ei(ti({start:N,end:h}),{format:["years","months","weeks","days","hours","minutes"],zero:!1})},[d]);return e.jsx(ke,{children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsx(ae,{children:"New Delete Request"})}),e.jsxs(te,{children:[r&&e.jsxs(Ge,{variant:"destructive",className:"mb-6",children:[e.jsx(nt,{className:"h-4 w-4"}),e.jsx(He,{children:"Error"}),e.jsx(Ke,{children:r})]}),e.jsx(mn,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(f),className:"space-y-8",children:[e.jsx(Ie,{control:d.control,name:"tenant_id",render:({field:N})=>e.jsxs(ve,{children:[e.jsx(fe,{children:"TENANT ID"}),e.jsx(je,{children:e.jsx(xe,{placeholder:"Enter tenant ID",...N})}),e.jsx(we,{})]})}),e.jsx(Ie,{control:d.control,name:"query",render:({field:N})=>e.jsxs(ve,{children:[e.jsx(fe,{children:"LOGQL QUERY"}),e.jsx(je,{children:e.jsxs("div",{className:"relative",children:[e.jsx(xn,{placeholder:'{app="example"}',className:"font-mono",...N,onChange:h=>{N.onChange(h),m(h.target.value)},onBlur:async h=>{N.onBlur(),h.target.value&&await u(h.target.value,!0)}}),n&&e.jsx("div",{className:"absolute right-3 top-3",children:e.jsx(he,{className:"h-5 w-5 animate-spin"})})]})}),e.jsx(hn,{children:"Enter a LogQL query with labels in curly braces"}),e.jsx(we,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-8",children:[e.jsx(Ie,{control:d.control,name:"start_time",render:({field:N})=>e.jsxs(ve,{children:[e.jsx(fe,{children:"START TIME"}),e.jsx(je,{children:e.jsx(Ys,{selected:N.value,onChange:N.onChange,showTimeSelect:!0,timeFormat:"HH:mm",timeIntervals:15,dateFormat:"yyyy-MM-dd HH:mm",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})}),e.jsx(we,{})]})}),e.jsx(Ie,{control:d.control,name:"end_time",render:({field:N})=>e.jsxs(ve,{children:[e.jsx(fe,{children:"END TIME"}),e.jsx(je,{children:e.jsx(Ys,{selected:N.value,onChange:N.onChange,showTimeSelect:!0,timeFormat:"HH:mm",timeIntervals:15,dateFormat:"yyyy-MM-dd HH:mm",minDate:d.watch("start_time"),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})}),e.jsx(we,{})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(fe,{children:"DURATION"}),e.jsx("div",{className:"h-10 flex items-center",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:y})})]})]}),e.jsxs("div",{className:"flex justify-end space-x-3 pt-6 border-t",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t("/tenants/deletes"),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:!d.formState.isValid||d.formState.isSubmitting,children:d.formState.isSubmitting?"Creating...":"Create Delete Request"})]})]})})]})]})})},tp={light:"",dark:".dark"},yn=i.createContext(null);function vn(){const t=i.useContext(yn);if(!t)throw new Error("useChart must be used within a <ChartContainer />");return t}const jn=i.forwardRef(({id:t,className:s,children:r,config:a,...n},o)=>{const l=i.useId(),c=`chart-${t||l.replace(/:/g,"")}`;return e.jsx(yn.Provider,{value:{config:a},children:e.jsxs("div",{"data-chart":c,ref:o,className:v("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",s),...n,children:[e.jsx(sp,{id:c,config:a}),e.jsx(ct,{children:r})]})})});jn.displayName="Chart";const sp=({id:t,config:s})=>{const r=Object.entries(s).filter(([,a])=>a.theme||a.color);return r.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(tp).map(([a,n])=>` +${n} [data-chart=${t}] { +${r.map(([o,l])=>{var d;const c=((d=l.theme)==null?void 0:d[a])||l.color;return c?` --color-${o}: ${c};`:null}).join(` +`)} +} +`).join(` +`)}}):null},rp=dt,wn=i.forwardRef(({active:t,payload:s,className:r,indicator:a="dot",hideLabel:n=!1,hideIndicator:o=!1,label:l,labelFormatter:c,labelClassName:d,formatter:u,color:m,nameKey:f,labelKey:y},N)=>{const{config:h}=vn(),p=i.useMemo(()=>{var E;if(n||!(s!=null&&s.length))return null;const[x]=s,b=`${y||x.dataKey||x.name||"value"}`,j=gs(h,x,b),w=!y&&typeof l=="string"?((E=h[l])==null?void 0:E.label)||l:j==null?void 0:j.label;return c?e.jsx("div",{className:v("font-medium",d),children:c(w,s)}):w?e.jsx("div",{className:v("font-medium",d),children:w}):null},[l,c,s,n,d,h,y]);if(!t||!(s!=null&&s.length))return null;const g=s.length===1&&a!=="dot";return e.jsxs("div",{ref:N,className:v("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",r),children:[g?null:p,e.jsx("div",{className:"grid gap-1.5",children:s.map((x,b)=>{const j=`${f||x.name||x.dataKey||"value"}`,w=gs(h,x,j),E=m||x.payload.fill||x.color;return e.jsx("div",{className:v("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",a==="dot"&&"items-center"),children:u&&(x==null?void 0:x.value)!==void 0&&x.name?u(x.value,x.name,x,b,x.payload):e.jsxs(e.Fragment,{children:[w!=null&&w.icon?e.jsx(w.icon,{}):!o&&e.jsx("div",{className:v("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":a==="dot","w-1":a==="line","w-0 border-[1.5px] border-dashed bg-transparent":a==="dashed","my-0.5":g&&a==="dashed"}),style:{"--color-bg":E,"--color-border":E}}),e.jsxs("div",{className:v("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?p:null,e.jsx("span",{className:"text-muted-foreground",children:(w==null?void 0:w.label)||x.name})]}),x.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:x.value.toLocaleString()})]})]})},x.dataKey)})})]})});wn.displayName="ChartTooltip";const ap=i.forwardRef(({className:t,hideIcon:s=!1,payload:r,verticalAlign:a="bottom",nameKey:n},o)=>{const{config:l}=vn();return r!=null&&r.length?e.jsx("div",{ref:o,className:v("flex items-center justify-center gap-4",a==="top"?"pb-3":"pt-3",t),children:r.map(c=>{const d=`${n||c.dataKey||"value"}`,u=gs(l,c,d);return e.jsxs("div",{className:v("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[u!=null&&u.icon&&!s?e.jsx(u.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:c.color}}),u==null?void 0:u.label]},c.value)})}):null});ap.displayName="ChartLegend";function gs(t,s,r){if(typeof s!="object"||s===null)return;const a="payload"in s&&typeof s.payload=="object"&&s.payload!==null?s.payload:void 0;let n=r;return r in s&&typeof s[r]=="string"?n=s[r]:a&&r in a&&typeof a[r]=="string"&&(n=a[r]),n in t?t[n]:t[r]}const np=ji,op=wi,ip=Ni,lp=ia({tenant:Ye().min(1,"Tenant ID is required"),since:Ye(),matcher:Ye().default("{}")}),cp=[{value:"1h",label:"Last 1 hour"},{value:"3h",label:"Last 3 hours"},{value:"6h",label:"Last 6 hours"},{value:"12h",label:"Last 12 hours"},{value:"24h",label:"Last 24 hours"}];function dp({values:t,totalValues:s}){return e.jsx("div",{className:"space-y-2 py-2",children:t.map(({value:r,count:a})=>e.jsxs("div",{className:"grid grid-cols-[200px_1fr_80px] items-center gap-4",children:[e.jsx(be,{variant:"outline",className:"font-mono text-xs justify-self-start overflow-hidden",children:r}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${a/s*100}%`}})}),e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums justify-self-end",children:[(a/s*100).toFixed(1),"%"]})]},r))})}function up(){const{cluster:t}=ue(),{toast:s}=zt(),[r,a]=i.useState(null),[n,o]=i.useState("uniqueValues"),[l,c]=i.useState("desc"),[d,u]=i.useState("uniqueValues"),[m,f]=i.useState(new Set),y=la({resolver:bn(lp),defaultValues:{matcher:"{}",since:"1h"}}),N=Oe(t==null?void 0:t.members,"query-frontend"),{isLoading:h,refetch:p}=Mt({queryKey:["analyze-labels"],queryFn:async()=>{try{const w=y.getValues(),E=new Date,C=new Date(E.getTime()-pp(w.since)),A=await fetch(`/ui/api/v1/proxy/${N}/loki/api/v1/series?match[]=${encodeURIComponent(w.matcher)}&start=${C.getTime()*1e6}&end=${E.getTime()*1e6}`,{headers:{"X-Scope-OrgID":w.tenant}});if(!A.ok){const M=await A.text();throw new Error(M||"Failed to fetch series")}const B=await A.json(),z=new Map,Y=new Map;B.data.forEach(M=>{Object.entries(M).forEach(([W,T])=>{z.has(W)||(z.set(W,{uniqueValues:new Set,inStreams:0}),Y.set(W,new Map));const O=z.get(W),V=Y.get(W);O.uniqueValues.add(T),O.inStreams++,V.set(T,(V.get(T)||0)+1)})});const K=Array.from(z.entries()).map(([M,W])=>{const T=Array.from(Y.get(M).entries()).map(([O,V])=>({value:O,count:V})).sort((O,V)=>V.count-O.count).slice(0,5);return{name:M,uniqueValues:W.uniqueValues.size,inStreams:W.inStreams,sampleValues:T}});return K.sort((M,W)=>W.uniqueValues-M.uniqueValues),a({totalStreams:B.data.length,uniqueLabels:z.size,labels:K}),B}catch(w){throw s({variant:"destructive",title:"Error analyzing labels",description:w instanceof Error?w.message:"An unexpected error occurred"}),w}},enabled:!1});function g(){p()}const x=i.useMemo(()=>{const w=document.createElement("style"),E=(r==null?void 0:r.labels.slice(0,10).map((C,A)=>{const B=A*137.5%360;return`--chart-color-${A}: hsl(${B}, 70%, 50%);`}).join(` +`))||"";return w.textContent=`:root { ${E} }`,document.head.appendChild(w),()=>w.remove()},[r]);i.useEffect(()=>x,[x]);const b={value:{label:d==="uniqueValues"?"Unique Values":"Found In Streams",theme:{light:"var(--chart-color-0)",dark:"var(--chart-color-0)"}}},j=i.useMemo(()=>r?[...r.labels].sort((w,E)=>{let C=0;switch(n){case"name":C=w.name.localeCompare(E.name);break;case"uniqueValues":C=w.uniqueValues-E.uniqueValues;break;case"inStreams":C=w.inStreams-E.inStreams;break;case"cardinality":C=w.uniqueValues/w.inStreams-E.uniqueValues/E.inStreams;break}return l==="asc"?C:-C}):[],[r,n,l]);return e.jsxs("div",{className:"container mx-auto p-4 space-y-6",children:[e.jsxs(ee,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Analyze Labels"}),e.jsx(Qe,{children:"Analyze label distribution across your log streams"})]}),e.jsx(te,{children:e.jsx(mn,{...y,children:e.jsxs("form",{onSubmit:y.handleSubmit(g),className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(Ie,{control:y.control,name:"tenant",render:({field:w})=>e.jsxs(ve,{className:"flex flex-col space-y-1.5",children:[e.jsx(fe,{children:"Tenant ID"}),e.jsx(je,{children:e.jsx(xe,{placeholder:"Enter tenant ID...",...w})}),e.jsx(we,{className:"text-xs"})]})}),e.jsx(Ie,{control:y.control,name:"since",render:({field:w})=>e.jsxs(ve,{className:"flex flex-col space-y-1.5",children:[e.jsx(fe,{children:"Time Range"}),e.jsxs(Tt,{onValueChange:w.onChange,defaultValue:w.value,children:[e.jsx(je,{children:e.jsx(et,{children:e.jsx(Rt,{placeholder:"Select time range"})})}),e.jsx(tt,{children:cp.map(E=>e.jsx(ze,{value:E.value,children:E.label},E.value))})]}),e.jsx(we,{className:"text-xs"})]})}),e.jsx(Ie,{control:y.control,name:"matcher",render:({field:w})=>e.jsxs(ve,{className:"flex flex-col space-y-1.5",children:[e.jsx(fe,{children:"Matcher"}),e.jsx(je,{children:e.jsx(xe,{placeholder:"Enter matcher... (default: {})",...w})}),e.jsx(we,{className:"text-xs"})]})}),e.jsx(q,{type:"submit",disabled:h,className:"self-end h-10",children:h?"Analyzing...":"Analyze"})]})})})]}),r&&e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row",children:[e.jsxs("div",{className:"flex flex-1 flex-col justify-center gap-1 px-6 py-5 sm:py-6",children:[e.jsx(ae,{children:"Label Distribution"}),e.jsx(Qe,{children:"Top 20 labels by unique values"})]}),e.jsxs("div",{className:"flex",children:[e.jsxs("div",{className:"relative z-30 flex flex-1 flex-col justify-center gap-1 px-6 py-4 text-left sm:px-8 sm:py-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Total Streams"}),e.jsx("span",{className:"text-lg font-bold leading-none sm:text-3xl",children:r.totalStreams.toLocaleString()})]}),e.jsxs("div",{className:"relative z-30 flex flex-1 flex-col justify-center gap-1 border-l px-6 py-4 text-left sm:px-8 sm:py-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Unique Labels"}),e.jsx("span",{className:"text-lg font-bold leading-none sm:text-3xl",children:r.uniqueLabels.toLocaleString()})]})]})]}),e.jsxs(te,{className:"px-2 sm:p-6",children:[e.jsx("div",{className:"mb-4",children:e.jsxs(Tt,{value:d,onValueChange:w=>u(w),children:[e.jsx(et,{className:"w-[200px]",children:e.jsx(Rt,{placeholder:"Select metric"})}),e.jsxs(tt,{children:[e.jsx(ze,{value:"uniqueValues",children:"Unique Values"}),e.jsx(ze,{value:"inStreams",children:"Found In Streams"})]})]})}),e.jsx(jn,{config:b,className:"aspect-auto h-[500px] w-full",children:e.jsxs(Si,{data:r.labels.slice(0,20).map((w,E)=>({name:w.name,value:d==="uniqueValues"?w.uniqueValues:w.inStreams,fill:`var(--chart-color-${E})`})),layout:"vertical",margin:{right:24},barSize:452/Math.min(20,r.labels.length)*.6,maxBarSize:24,children:[e.jsx(Ei,{horizontal:!1}),e.jsx(Ci,{dataKey:"name",type:"category",tickLine:!1,axisLine:!1,width:90,fontSize:11,interval:0}),e.jsx(Ti,{type:"number",tickLine:!1,axisLine:!1,tickMargin:8}),e.jsx(rp,{content:e.jsx(wn,{className:"w-[200px]"})}),e.jsx(Ri,{dataKey:"value",fillOpacity:.8,radius:[4,4,0,0]})]})})]})]}),e.jsxs(ee,{children:[e.jsx(se,{children:e.jsx(ae,{children:"Label Details"})}),e.jsx(te,{children:e.jsxs(Ce,{children:[e.jsx(Te,{children:e.jsxs(X,{children:[e.jsx(D,{children:e.jsx(Z,{title:"Label Name",field:"name",sortField:n,sortDirection:l,onSort:w=>{w===n?c(l==="asc"?"desc":"asc"):(o(w),c("desc"))}})}),e.jsx(D,{children:e.jsx(Z,{title:"Unique Values",field:"uniqueValues",sortField:n,sortDirection:l,onSort:w=>{w===n?c(l==="asc"?"desc":"asc"):(o(w),c("desc"))}})}),e.jsx(D,{children:e.jsx(Z,{title:"Found In Streams",field:"inStreams",sortField:n,sortDirection:l,onSort:w=>{w===n?c(l==="asc"?"desc":"asc"):(o(w),c("desc"))}})}),e.jsx(D,{children:e.jsx(Z,{title:"Cardinality %",field:"cardinality",sortField:n,sortDirection:l,onSort:w=>{w===n?c(l==="asc"?"desc":"asc"):(o(w),c("desc"))}})})]})}),e.jsx(Re,{children:j.map(w=>e.jsx(np,{asChild:!0,open:m.has(w.name),onOpenChange:E=>{const C=new Set(m);E?C.add(w.name):C.delete(w.name),f(C)},children:e.jsxs(e.Fragment,{children:[e.jsxs(X,{children:[e.jsx(F,{className:"font-medium",children:e.jsxs(op,{className:"flex items-center gap-2 hover:text-primary",children:[e.jsx(ot,{className:v("h-4 w-4 transition-transform",m.has(w.name)&&"rotate-180")}),w.name]})}),e.jsx(F,{children:w.uniqueValues.toLocaleString()}),e.jsx(F,{children:w.inStreams.toLocaleString()}),e.jsxs(F,{children:[(w.uniqueValues/w.inStreams*100).toFixed(2),"%"]})]}),e.jsx(ip,{asChild:!0,children:e.jsx(X,{children:e.jsx(F,{colSpan:4,className:"border-t-0 bg-muted/5",children:e.jsx("div",{className:"px-4",children:e.jsx(dp,{values:w.sampleValues,totalValues:w.inStreams})})})})})]})},w.name))})]})})]})]})]})}function pp(t){const s=parseInt(t),a=t.slice(-1)==="h"?36e5:0;return s*a}const Nn=[{path:"/",breadcrumb:"Home",element:e.jsx(lr,{})},{path:"/nodes",breadcrumb:"Nodes",element:e.jsx(lr,{})},{path:"/nodes/:nodeName",breadcrumb:Ki,element:e.jsx(qu,{})},{path:"/versions",breadcrumb:"Versions",element:e.jsx(Ae,{})},{path:"/rings",breadcrumb:"Rings",element:e.jsx(or,{})},{path:"/rings/:ringName",breadcrumb:Wi,element:e.jsx(or,{})},{path:"/storage",breadcrumb:"Storage",element:e.jsx(Ae,{})},{path:"/storage/object",breadcrumb:"Object Storage",element:e.jsx(Ae,{})},{path:"/storage/dataobj",breadcrumb:"Data Objects",element:e.jsx(Dc,{})},{path:"/storage/dataobj/metadata",breadcrumb:"File Metadata",element:e.jsx(Yc,{})},{path:"/tenants",breadcrumb:"Tenants",element:e.jsx(Ae,{})},{path:"/tenants/deletes",breadcrumb:"Deletes",element:e.jsx(Xu,{})},{path:"/tenants/deletes/new",element:e.jsx(ep,{}),breadcrumb:"New Delete Request"},{path:"/tenants/analyze-labels",element:e.jsx(up,{}),breadcrumb:"Analyze Labels"},{path:"/tenants/limits",breadcrumb:"Limits",element:e.jsx(Ae,{})},{path:"/tenants/labels",breadcrumb:"Labels",element:e.jsx(Ae,{})},{path:"/rules",breadcrumb:"Rules",element:e.jsx(Ae,{})},{path:"/404",breadcrumb:"404",element:e.jsx(Zi,{})}];function mp(){const t=So(Nn,{disableDefaults:!0});return e.jsx(ks,{children:e.jsx(Ss,{children:t.map(({match:s,breadcrumb:r},a)=>e.jsxs(i.Fragment,{children:[e.jsx(Nt,{className:a===0?"hidden md:block":"",children:a===t.length-1?e.jsx(pa,{children:r}):e.jsx(kt,{asChild:!0,children:e.jsx(ce,{to:s.pathname,children:r})})}),a<t.length-1&&e.jsx(St,{className:a===0?"hidden md:block":""})]},s.pathname))})})}function kn(){const s=window.location.pathname.match(/(.*\/ui\/)/);return(s==null?void 0:s[1])||"/ui/"}function gp(){const{cluster:t,isLoading:s}=ue(),[r,a]=i.useState(!0);i.useEffect(()=>{let l;return s?a(!0):l=setTimeout(()=>{a(!1)},500),()=>{l&&clearTimeout(l)}},[s]);const n=()=>{if(!(t!=null&&t.members))return"v0.0.0";const l=new Map;Object.values(t.members).forEach(u=>{if(!u.build.version)return;const m=u.build.version;l.set(m,(l.get(m)||0)+1)});let c="v0.0.0",d=0;return l.forEach((u,m)=>{u>d&&(d=u,c=m)}),c},o=()=>{if(!(t!=null&&t.members))return[];const l=new Set,c=new Map;return Object.values(t.members).forEach(d=>{const u=d.build.version;l.add(u),c.set(u,{revision:d.build.revision,branch:d.build.branch,buildUser:d.build.buildUser,buildDate:d.build.buildDate,goVersion:d.build.goVersion})}),Array.from(l).map(d=>({version:d??"v0.0.0",info:c.get(d)??{revision:"v0.0.0",branch:"v0.0.0",buildUser:"v0.0.0",buildDate:"v0.0.0",goVersion:"v0.0.0"}}))};return{mostCommonVersion:n(),versionInfos:o(),isLoading:r}}function fp(){const{mostCommonVersion:t,versionInfos:s,isLoading:r}=gp(),[a,n]=i.useState(!1),o=()=>s.map(({version:l,info:c})=>`Version: ${l} +Revision: ${c.revision} +Branch: ${c.branch} +Build User: ${c.buildUser} +Build Date: ${c.buildDate} +Go Version: ${c.goVersion} +`).join(` +`);return e.jsxs(Vt,{open:a,onOpenChange:n,children:[e.jsx(Ut,{asChild:!0,children:e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx("button",{onClick:()=>n(!a),className:v("transition-opacity duration-200 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded px-1 -mx-1",{"opacity-0":r,"opacity-100":!r}),children:t}),r&&e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"h-3 w-3 animate-spin"}),"Loading..."]})]})}),e.jsx(mt,{side:"bottom",align:"start",className:"w-[400px]",children:e.jsxs("div",{className:"p-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"font-semibold",children:"Build Information"}),!r&&s.length>0&&e.jsx($s,{text:o()})]}),e.jsx("div",{className:v("transition-opacity duration-200",{"opacity-0":r,"opacity-100":!r}),children:s.length>0?s.map(({version:l,info:c})=>e.jsxs("div",{className:"mb-2 last:mb-0",children:[e.jsx("div",{className:"font-semibold",children:l}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{children:["Revision: ",c.revision]}),e.jsxs("div",{children:["Branch: ",c.branch]}),e.jsxs("div",{children:["Build User: ",c.buildUser]}),e.jsxs("div",{children:["Build Date: ",c.buildDate]}),e.jsxs("div",{children:["Go Version: ",c.goVersion]})]})]},l)):e.jsx("div",{className:"text-sm text-muted-foreground",children:"No build information available"})}),r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:"Loading build information..."})]})]})})]})}const ns=768;function hp(){const[t,s]=i.useState(void 0);return i.useEffect(()=>{const r=window.matchMedia(`(max-width: ${ns-1}px)`),a=()=>{s(window.innerWidth<ns)};return r.addEventListener("change",a),s(window.innerWidth<ns),()=>r.removeEventListener("change",a)},[]),!!t}const Vs=i.forwardRef(({className:t,orientation:s="horizontal",decorative:r=!0,...a},n)=>e.jsx(oa,{ref:n,decorative:r,orientation:s,className:v("shrink-0 bg-border",s==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",t),...a}));Vs.displayName=oa.displayName;const xp=ws,bp=Ns,Sn=i.forwardRef(({className:t,...s},r)=>e.jsx(it,{className:v("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s,ref:r}));Sn.displayName=it.displayName;const yp=Ee("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),En=i.forwardRef(({side:t="right",className:s,children:r,...a},n)=>e.jsxs(bp,{children:[e.jsx(Sn,{}),e.jsxs(lt,{ref:n,className:v(yp({side:t}),s),...a,children:[e.jsxs(aa,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e.jsx(vs,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),r]})]}));En.displayName=lt.displayName;const vp=i.forwardRef(({className:t,...s},r)=>e.jsx(Lt,{ref:r,className:v("text-lg font-semibold text-foreground",t),...s}));vp.displayName=Lt.displayName;const jp=i.forwardRef(({className:t,...s},r)=>e.jsx(Pt,{ref:r,className:v("text-sm text-muted-foreground",t),...s}));jp.displayName=Pt.displayName;function mr({className:t,...s}){return e.jsx("div",{className:v("animate-pulse rounded-md bg-primary/10",t),...s})}const wp="sidebar:state",Np=60*60*24*7,kp="16rem",Sp="18rem",Ep="3rem",Cp="b",Cn=i.createContext(null);function Zt(){const t=i.useContext(Cn);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const Tn=i.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:r,className:a,style:n,children:o,...l},c)=>{const d=hp(),[u,m]=i.useState(!1),[f,y]=i.useState(t),N=s??f,h=i.useCallback(b=>{const j=typeof b=="function"?b(N):b;r?r(j):y(j),document.cookie=`${wp}=${j}; path=/; max-age=${Np}`},[r,N]),p=i.useCallback(()=>d?m(b=>!b):h(b=>!b),[d,h,m]);i.useEffect(()=>{const b=j=>{j.key===Cp&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),p())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[p]);const g=N?"expanded":"collapsed",x=i.useMemo(()=>({state:g,open:N,setOpen:h,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:p}),[g,N,h,d,u,m,p]);return e.jsx(Cn.Provider,{value:x,children:e.jsx(Ms,{delayDuration:0,children:e.jsx("div",{style:{"--sidebar-width":kp,"--sidebar-width-icon":Ep,...n},className:v("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",a),ref:c,...l,children:o})})})});Tn.displayName="SidebarProvider";const Rn=i.forwardRef(({side:t="left",variant:s="sidebar",collapsible:r="offcanvas",className:a,children:n,...o},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=Zt();return r==="none"?e.jsx("div",{className:v("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",a),ref:l,...o,children:n}):c?e.jsx(xp,{open:u,onOpenChange:m,...o,children:e.jsx(En,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":Sp},side:t,children:e.jsx("div",{className:"flex h-full w-full flex-col",children:n})})}):e.jsxs("div",{ref:l,className:"group peer hidden text-sidebar-foreground md:block","data-state":d,"data-collapsible":d==="collapsed"?r:"","data-variant":s,"data-side":t,children:[e.jsx("div",{className:v("relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",s==="floating"||s==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:v("fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",t==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",s==="floating"||s==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",a),...o,children:e.jsx("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow",children:n})})]})});Rn.displayName="Sidebar";const An=i.forwardRef(({className:t,onClick:s,...r},a)=>{const{toggleSidebar:n}=Zt();return e.jsxs(q,{ref:a,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:v("h-7 w-7",t),onClick:o=>{s==null||s(o),n()},...r,children:[e.jsx(Go,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});An.displayName="SidebarTrigger";const _n=i.forwardRef(({className:t,...s},r)=>{const{toggleSidebar:a}=Zt();return e.jsx("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:a,title:"Toggle Sidebar",className:v("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),...s})});_n.displayName="SidebarRail";const In=i.forwardRef(({className:t,...s},r)=>e.jsx("main",{ref:r,className:v("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",t),...s}));In.displayName="SidebarInset";const Tp=i.forwardRef(({className:t,...s},r)=>e.jsx(xe,{ref:r,"data-sidebar":"input",className:v("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...s}));Tp.displayName="SidebarInput";const Fn=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"header",className:v("flex flex-col gap-2 p-2",t),...s}));Fn.displayName="SidebarHeader";const Rp=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"footer",className:v("flex flex-col gap-2 p-2",t),...s}));Rp.displayName="SidebarFooter";const Ap=i.forwardRef(({className:t,...s},r)=>e.jsx(Vs,{ref:r,"data-sidebar":"separator",className:v("mx-2 w-auto bg-sidebar-border",t),...s}));Ap.displayName="SidebarSeparator";const Ln=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"content",className:v("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...s}));Ln.displayName="SidebarContent";const Pn=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"group",className:v("relative flex w-full min-w-0 flex-col p-2",t),...s}));Pn.displayName="SidebarGroup";const _p=i.forwardRef(({className:t,asChild:s=!1,...r},a)=>{const n=s?Se:"div";return e.jsx(n,{ref:a,"data-sidebar":"group-label",className:v("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),...r})});_p.displayName="SidebarGroupLabel";const Ip=i.forwardRef(({className:t,asChild:s=!1,...r},a)=>{const n=s?Se:"button";return e.jsx(n,{ref:a,"data-sidebar":"group-action",className:v("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",t),...r})});Ip.displayName="SidebarGroupAction";const Fp=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"group-content",className:v("w-full text-sm",t),...s}));Fp.displayName="SidebarGroupContent";const fs=i.forwardRef(({className:t,...s},r)=>e.jsx("ul",{ref:r,"data-sidebar":"menu",className:v("flex w-full min-w-0 flex-col gap-1",t),...s}));fs.displayName="SidebarMenu";const Us=i.forwardRef(({className:t,...s},r)=>e.jsx("li",{ref:r,"data-sidebar":"menu-item",className:v("group/menu-item relative",t),...s}));Us.displayName="SidebarMenuItem";const Lp=Ee("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),qs=i.forwardRef(({asChild:t=!1,isActive:s=!1,variant:r="default",size:a="default",tooltip:n,className:o,...l},c)=>{const d=t?Se:"button",{isMobile:u,state:m}=Zt(),f=e.jsx(d,{ref:c,"data-sidebar":"menu-button","data-size":a,"data-active":s,className:v(Lp({variant:r,size:a}),o),...l});return n?(typeof n=="string"&&(n={children:n}),e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:f}),e.jsx(Ue,{side:"right",align:"center",hidden:m!=="collapsed"||u,...n})]})):f});qs.displayName="SidebarMenuButton";const Pp=i.forwardRef(({className:t,asChild:s=!1,showOnHover:r=!1,...a},n)=>{const o=s?Se:"button";return e.jsx(o,{ref:n,"data-sidebar":"menu-action",className:v("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),...a})});Pp.displayName="SidebarMenuAction";const Dp=i.forwardRef(({className:t,...s},r)=>e.jsx("div",{ref:r,"data-sidebar":"menu-badge",className:v("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),...s}));Dp.displayName="SidebarMenuBadge";const Op=i.forwardRef(({className:t,showIcon:s=!1,...r},a)=>{const n=i.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{ref:a,"data-sidebar":"menu-skeleton",className:v("flex h-8 items-center gap-2 rounded-md px-2",t),...r,children:[s&&e.jsx(mr,{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx(mr,{className:"h-4 max-w-[--skeleton-width] flex-1","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});Op.displayName="SidebarMenuSkeleton";const Dn=i.forwardRef(({className:t,...s},r)=>e.jsx("ul",{ref:r,"data-sidebar":"menu-sub",className:v("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),...s}));Dn.displayName="SidebarMenuSub";const On=i.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));On.displayName="SidebarMenuSubItem";const $n=i.forwardRef(({asChild:t=!1,size:s="md",isActive:r,className:a,...n},o)=>{const l=t?Se:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:v("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",a),...n})});$n.displayName="SidebarMenuSubButton";function $p(t,s){const[r,a]=i.useState(s);return i.useEffect(()=>{if(!(t!=null&&t.members))return;const n=s.map(o=>o.title==="Rings"&&t.members?{...o,items:el(t.members)}:o);a(n)},[t==null?void 0:t.members,s]),r}const os=[{title:"Cluster",url:"/nodes",icon:e.jsx(Ho,{className:"h-4 w-4"}),items:[{title:"Nodes",url:"/nodes"},{title:"Rollouts & Versions",url:"/versions"}]},{title:"Rings",url:"/rings",icon:e.jsx(Cr,{className:"h-4 w-4"}),items:[]},{title:"Storage",url:"/storage",icon:e.jsx(Ko,{className:"h-4 w-4"}),items:[{title:"Object Storage",url:"/storage/object"},{title:"Data Objects",url:"/storage/dataobj"}]},{title:"Tenants",url:"/tenants",icon:e.jsx(Wo,{className:"h-4 w-4"}),items:[{title:"Analyze Labels",url:"/tenants/analyze-labels"},{title:"Deletes",url:"/tenants/deletes"},{title:"Limits",url:"/tenants/limits"},{title:"Labels",url:"/tenants/labels"}]},{title:"Rules",url:"/rules",icon:e.jsx(Zo,{className:"h-4 w-4"}),items:[]},{title:"Documentation",url:"https://grafana.com/docs/loki/latest/",icon:e.jsx(Yo,{className:"h-4 w-4"}),items:[]}];function Mp(t){return e.jsx(_n,{...t,className:v("after:bg-border/40 hover:after:bg-border","hover:bg-muted/50",t.className)})}const gr="loki-sidebar-open-sections",Bp=i.memo(function({item:s,isOpen:r,isActive:a,onToggle:n}){return e.jsxs(Us,{children:[e.jsx(qs,{asChild:!0,isActive:a(s.url),onClick:()=>n(s.title),children:e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s.icon,e.jsx(ce,{to:`${s.url}`,target:s.url.includes("http")?"_blank":"_self",children:s.title})]}),s.items&&s.items.length>0&&e.jsx(ot,{className:v("h-4 w-4 transition-transform duration-200",r?"rotate-0":"-rotate-90")})]})}),s.items&&s.items.length>0&&r&&e.jsx(Dn,{children:s.items.map(o=>e.jsx(On,{children:e.jsx($n,{asChild:!0,isActive:a(o.url),children:e.jsx(ce,{to:`${o.url}`,children:o.title})})},o.title))})]})});function zp({...t}){const s=kn(),r=Eo(),{cluster:a}=ue(),n=r.pathname.replace(s,"/"),[o,l]=i.useState(()=>{const m=localStorage.getItem(gr);if(m)try{return JSON.parse(m)}catch{return os.reduce((f,y)=>({...f,[y.title]:!0}),{})}return os.reduce((f,y)=>({...f,[y.title]:!0}),{})}),c=$p(a,os),d=i.useCallback(m=>m==="/"?n==="/":n.startsWith(m),[n]),u=i.useCallback(m=>{l(f=>{const y={...f,[m]:!f[m]};return localStorage.setItem(gr,JSON.stringify(y)),y})},[]);return e.jsxs(Rn,{...t,children:[e.jsx(Fn,{className:"py-4",children:e.jsx(fs,{children:e.jsx(Us,{children:e.jsx(qs,{size:"lg",asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4",children:[e.jsx("img",{src:"https://grafana.com/media/docs/loki/logo-grafana-loki.png",alt:"Loki Logo",className:"h-7 w-7"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm font-semibold leading-none",children:"Grafana Loki"}),e.jsx(fp,{})]})]})})})})}),e.jsx(pt,{className:"flex-1",children:e.jsx(Ln,{children:e.jsx(Pn,{children:e.jsx(fs,{children:c.map(m=>e.jsx(i.Fragment,{children:e.jsx(Bp,{item:m,isOpen:o[m.title],isActive:d,onToggle:u})},m.title))})})})}),e.jsx(Mp,{})]})}function Vp(){const[t,s]=i.useState(!1);i.useEffect(()=>{const a=()=>{s(window.scrollY>300)};return window.addEventListener("scroll",a),()=>window.removeEventListener("scroll",a)},[]);const r=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?e.jsx(q,{onClick:r,size:"icon",className:"fixed bottom-8 right-8 rounded-full shadow-lg transition-all duration-300","aria-label":"Back to top",children:e.jsx(ls,{className:"h-4 w-4"})}):null}var Gs="ToastProvider",[Hs,Up,qp]=bi("Toast"),[Mn,Fm]=hr("Toast",[qp]),[Gp,Yt]=Mn(Gs),Bn=t=>{const{__scopeToast:s,label:r="Notification",duration:a=5e3,swipeDirection:n="right",swipeThreshold:o=50,children:l}=t,[c,d]=i.useState(null),[u,m]=i.useState(0),f=i.useRef(!1),y=i.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${Gs}\`. Expected non-empty \`string\`.`),e.jsx(Hs.Provider,{scope:s,children:e.jsx(Gp,{scope:s,label:r,duration:a,swipeDirection:n,swipeThreshold:o,toastCount:u,viewport:c,onViewportChange:d,onToastAdd:i.useCallback(()=>m(N=>N+1),[]),onToastRemove:i.useCallback(()=>m(N=>N-1),[]),isFocusedToastEscapeKeyDownRef:f,isClosePausedRef:y,children:l})})};Bn.displayName=Gs;var zn="ToastViewport",Hp=["F8"],hs="toast.viewportPause",xs="toast.viewportResume",Vn=i.forwardRef((t,s)=>{const{__scopeToast:r,hotkey:a=Hp,label:n="Notifications ({hotkey})",...o}=t,l=Yt(zn,r),c=Up(r),d=i.useRef(null),u=i.useRef(null),m=i.useRef(null),f=i.useRef(null),y=vr(s,f,l.onViewportChange),N=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),h=l.toastCount>0;i.useEffect(()=>{const g=x=>{var j;a.length!==0&&a.every(w=>x[w]||x.code===w)&&((j=f.current)==null||j.focus())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[a]),i.useEffect(()=>{const g=d.current,x=f.current;if(h&&g&&x){const b=()=>{if(!l.isClosePausedRef.current){const C=new CustomEvent(hs);x.dispatchEvent(C),l.isClosePausedRef.current=!0}},j=()=>{if(l.isClosePausedRef.current){const C=new CustomEvent(xs);x.dispatchEvent(C),l.isClosePausedRef.current=!1}},w=C=>{!g.contains(C.relatedTarget)&&j()},E=()=>{g.contains(document.activeElement)||j()};return g.addEventListener("focusin",b),g.addEventListener("focusout",w),g.addEventListener("pointermove",b),g.addEventListener("pointerleave",E),window.addEventListener("blur",b),window.addEventListener("focus",j),()=>{g.removeEventListener("focusin",b),g.removeEventListener("focusout",w),g.removeEventListener("pointermove",b),g.removeEventListener("pointerleave",E),window.removeEventListener("blur",b),window.removeEventListener("focus",j)}}},[h,l.isClosePausedRef]);const p=i.useCallback(({tabbingDirection:g})=>{const b=c().map(j=>{const w=j.ref.current,E=[w,...nm(w)];return g==="forwards"?E:E.reverse()});return(g==="forwards"?b.reverse():b).flat()},[c]);return i.useEffect(()=>{const g=f.current;if(g){const x=b=>{var E,C,A;const j=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!j){const B=document.activeElement,z=b.shiftKey;if(b.target===g&&z){(E=u.current)==null||E.focus();return}const M=p({tabbingDirection:z?"backwards":"forwards"}),W=M.findIndex(T=>T===B);is(M.slice(W+1))?b.preventDefault():z?(C=u.current)==null||C.focus():(A=m.current)==null||A.focus()}};return g.addEventListener("keydown",x),()=>g.removeEventListener("keydown",x)}},[c,p]),e.jsxs(bo,{ref:d,role:"region","aria-label":n.replace("{hotkey}",N),tabIndex:-1,style:{pointerEvents:h?void 0:"none"},children:[h&&e.jsx(bs,{ref:u,onFocusFromOutsideViewport:()=>{const g=p({tabbingDirection:"forwards"});is(g)}}),e.jsx(Hs.Slot,{scope:r,children:e.jsx(re.ol,{tabIndex:-1,...o,ref:y})}),h&&e.jsx(bs,{ref:m,onFocusFromOutsideViewport:()=>{const g=p({tabbingDirection:"backwards"});is(g)}})]})});Vn.displayName=zn;var Un="ToastFocusProxy",bs=i.forwardRef((t,s)=>{const{__scopeToast:r,onFocusFromOutsideViewport:a,...n}=t,o=Yt(Un,r);return e.jsx(jr,{"aria-hidden":!0,tabIndex:0,...n,ref:s,style:{position:"fixed"},onFocus:l=>{var u;const c=l.relatedTarget;!((u=o.viewport)!=null&&u.contains(c))&&a()}})});bs.displayName=Un;var Xt="Toast",Kp="toast.swipeStart",Wp="toast.swipeMove",Zp="toast.swipeCancel",Yp="toast.swipeEnd",qn=i.forwardRef((t,s)=>{const{forceMount:r,open:a,defaultOpen:n,onOpenChange:o,...l}=t,[c=!0,d]=yo({prop:a,defaultProp:n,onChange:o});return e.jsx(vo,{present:r||c,children:e.jsx(Jp,{open:c,...l,ref:s,onClose:()=>d(!1),onPause:jt(t.onPause),onResume:jt(t.onResume),onSwipeStart:pe(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:pe(t.onSwipeMove,u=>{const{x:m,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${f}px`)}),onSwipeCancel:pe(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:pe(t.onSwipeEnd,u=>{const{x:m,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${f}px`),d(!1)})})})});qn.displayName=Xt;var[Xp,Qp]=Mn(Xt,{onClose(){}}),Jp=i.forwardRef((t,s)=>{const{__scopeToast:r,type:a="foreground",duration:n,open:o,onClose:l,onEscapeKeyDown:c,onPause:d,onResume:u,onSwipeStart:m,onSwipeMove:f,onSwipeCancel:y,onSwipeEnd:N,...h}=t,p=Yt(Xt,r),[g,x]=i.useState(null),b=vr(s,T=>x(T)),j=i.useRef(null),w=i.useRef(null),E=n||p.duration,C=i.useRef(0),A=i.useRef(E),B=i.useRef(0),{onToastAdd:z,onToastRemove:Y}=p,K=jt(()=>{var O;(g==null?void 0:g.contains(document.activeElement))&&((O=p.viewport)==null||O.focus()),l()}),M=i.useCallback(T=>{!T||T===1/0||(window.clearTimeout(B.current),C.current=new Date().getTime(),B.current=window.setTimeout(K,T))},[K]);i.useEffect(()=>{const T=p.viewport;if(T){const O=()=>{M(A.current),u==null||u()},V=()=>{const Q=new Date().getTime()-C.current;A.current=A.current-Q,window.clearTimeout(B.current),d==null||d()};return T.addEventListener(hs,V),T.addEventListener(xs,O),()=>{T.removeEventListener(hs,V),T.removeEventListener(xs,O)}}},[p.viewport,E,d,u,M]),i.useEffect(()=>{o&&!p.isClosePausedRef.current&&M(E)},[o,E,p.isClosePausedRef,M]),i.useEffect(()=>(z(),()=>Y()),[z,Y]);const W=i.useMemo(()=>g?Xn(g):null,[g]);return p.viewport?e.jsxs(e.Fragment,{children:[W&&e.jsx(em,{__scopeToast:r,role:"status","aria-live":a==="foreground"?"assertive":"polite","aria-atomic":!0,children:W}),e.jsx(Xp,{scope:r,onClose:K,children:wr.createPortal(e.jsx(Hs.ItemSlot,{scope:r,children:e.jsx(jo,{asChild:!0,onEscapeKeyDown:pe(c,()=>{p.isFocusedToastEscapeKeyDownRef.current||K(),p.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(re.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":p.swipeDirection,...h,ref:b,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:pe(t.onKeyDown,T=>{T.key==="Escape"&&(c==null||c(T.nativeEvent),T.nativeEvent.defaultPrevented||(p.isFocusedToastEscapeKeyDownRef.current=!0,K()))}),onPointerDown:pe(t.onPointerDown,T=>{T.button===0&&(j.current={x:T.clientX,y:T.clientY})}),onPointerMove:pe(t.onPointerMove,T=>{if(!j.current)return;const O=T.clientX-j.current.x,V=T.clientY-j.current.y,Q=!!w.current,_=["left","right"].includes(p.swipeDirection),I=["left","up"].includes(p.swipeDirection)?Math.min:Math.max,P=_?I(0,O):0,U=_?0:I(0,V),S=T.pointerType==="touch"?10:2,R={x:P,y:U},$={originalEvent:T,delta:R};Q?(w.current=R,ht(Wp,f,$,{discrete:!1})):fr(R,p.swipeDirection,S)?(w.current=R,ht(Kp,m,$,{discrete:!1}),T.target.setPointerCapture(T.pointerId)):(Math.abs(O)>S||Math.abs(V)>S)&&(j.current=null)}),onPointerUp:pe(t.onPointerUp,T=>{const O=w.current,V=T.target;if(V.hasPointerCapture(T.pointerId)&&V.releasePointerCapture(T.pointerId),w.current=null,j.current=null,O){const Q=T.currentTarget,_={originalEvent:T,delta:O};fr(O,p.swipeDirection,p.swipeThreshold)?ht(Yp,N,_,{discrete:!0}):ht(Zp,y,_,{discrete:!0}),Q.addEventListener("click",I=>I.preventDefault(),{once:!0})}})})})}),p.viewport)})]}):null}),em=t=>{const{__scopeToast:s,children:r,...a}=t,n=Yt(Xt,s),[o,l]=i.useState(!1),[c,d]=i.useState(!1);return rm(()=>l(!0)),i.useEffect(()=>{const u=window.setTimeout(()=>d(!0),1e3);return()=>window.clearTimeout(u)},[]),c?null:e.jsx(wo,{asChild:!0,children:e.jsx(jr,{...a,children:o&&e.jsxs(e.Fragment,{children:[n.label," ",r]})})})},tm="ToastTitle",Gn=i.forwardRef((t,s)=>{const{__scopeToast:r,...a}=t;return e.jsx(re.div,{...a,ref:s})});Gn.displayName=tm;var sm="ToastDescription",Hn=i.forwardRef((t,s)=>{const{__scopeToast:r,...a}=t;return e.jsx(re.div,{...a,ref:s})});Hn.displayName=sm;var Kn="ToastAction",Wn=i.forwardRef((t,s)=>{const{altText:r,...a}=t;return r.trim()?e.jsx(Yn,{altText:r,asChild:!0,children:e.jsx(Ks,{...a,ref:s})}):(console.error(`Invalid prop \`altText\` supplied to \`${Kn}\`. Expected non-empty \`string\`.`),null)});Wn.displayName=Kn;var Zn="ToastClose",Ks=i.forwardRef((t,s)=>{const{__scopeToast:r,...a}=t,n=Qp(Zn,r);return e.jsx(Yn,{asChild:!0,children:e.jsx(re.button,{type:"button",...a,ref:s,onClick:pe(t.onClick,n.onClose)})})});Ks.displayName=Zn;var Yn=i.forwardRef((t,s)=>{const{__scopeToast:r,altText:a,...n}=t;return e.jsx(re.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":a||void 0,...n,ref:s})});function Xn(t){const s=[];return Array.from(t.childNodes).forEach(a=>{if(a.nodeType===a.TEXT_NODE&&a.textContent&&s.push(a.textContent),am(a)){const n=a.ariaHidden||a.hidden||a.style.display==="none",o=a.dataset.radixToastAnnounceExclude==="";if(!n)if(o){const l=a.dataset.radixToastAnnounceAlt;l&&s.push(l)}else s.push(...Xn(a))}}),s}function ht(t,s,r,{discrete:a}){const n=r.originalEvent.currentTarget,o=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:r});s&&n.addEventListener(t,s,{once:!0}),a?ko(n,o):n.dispatchEvent(o)}var fr=(t,s,r=0)=>{const a=Math.abs(t.x),n=Math.abs(t.y),o=a>n;return s==="left"||s==="right"?o&&a>r:!o&&n>r};function rm(t=()=>{}){const s=jt(t);No(()=>{let r=0,a=0;return r=window.requestAnimationFrame(()=>a=window.requestAnimationFrame(s)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(a)}},[s])}function am(t){return t.nodeType===t.ELEMENT_NODE}function nm(t){const s=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:a=>{const n=a.tagName==="INPUT"&&a.type==="hidden";return a.disabled||a.hidden||n?NodeFilter.FILTER_SKIP:a.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)s.push(r.currentNode);return s}function is(t){const s=document.activeElement;return t.some(r=>r===s?!0:(r.focus(),document.activeElement!==s))}var om=Bn,Qn=Vn,Jn=qn,eo=Gn,to=Hn,so=Wn,ro=Ks;const im=om,ao=i.forwardRef(({className:t,...s},r)=>e.jsx(Qn,{ref:r,className:v("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",t),...s}));ao.displayName=Qn.displayName;const lm=Ee("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),no=i.forwardRef(({className:t,variant:s,...r},a)=>e.jsx(Jn,{ref:a,className:v(lm({variant:s}),t),...r}));no.displayName=Jn.displayName;const cm=i.forwardRef(({className:t,...s},r)=>e.jsx(so,{ref:r,className:v("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",t),...s}));cm.displayName=so.displayName;const oo=i.forwardRef(({className:t,...s},r)=>e.jsx(ro,{ref:r,className:v("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...s,children:e.jsx(vs,{className:"h-4 w-4"})}));oo.displayName=ro.displayName;const io=i.forwardRef(({className:t,...s},r)=>e.jsx(eo,{ref:r,className:v("text-sm font-semibold [&+div]:text-xs",t),...s}));io.displayName=eo.displayName;const lo=i.forwardRef(({className:t,...s},r)=>e.jsx(to,{ref:r,className:v("text-sm opacity-90",t),...s}));lo.displayName=to.displayName;function dm(){const{toasts:t}=zt();return e.jsxs(im,{children:[t.map(function({id:s,title:r,description:a,action:n,...o}){return e.jsxs(no,{...o,children:[e.jsxs("div",{className:"grid gap-1",children:[r&&e.jsx(io,{children:r}),a&&e.jsx(lo,{children:a})]}),n,e.jsx(oo,{})]},s)}),e.jsx(ao,{})]})}function um({children:t}){return e.jsx("div",{className:"flex min-h-screen",children:e.jsxs(Tn,{children:[e.jsx(zp,{}),e.jsxs(In,{children:[e.jsxs("header",{className:"flex h-16 shrink-0 items-center gap-2 border-b px-4",children:[e.jsx(An,{}),e.jsx(Vs,{orientation:"vertical",className:"mr-2 h-4"}),e.jsx(mp,{}),e.jsx("div",{className:"ml-auto px-4",children:e.jsx(Hi,{})})]}),e.jsx("main",{className:"flex flex-1 flex-col",children:t}),e.jsx(dm,{}),e.jsx(Vp,{})]})]})})}var pm=function(){return null};const mm=new _i({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:!1,staleTime:5*60*1e3}}});function gm({children:t}){return e.jsxs(Ii,{client:mm,children:[t,e.jsx(pm,{initialIsOpen:!1})]})}function fm({children:t}){const[s,r]=i.useState(null),[a,n]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useCallback(async()=>{if(!c.current){c.current=!0,l(!0);try{const m=await fetch("/ui/api/v1/cluster/nodes");if(!m.ok)throw new Error(`Failed to fetch cluster data: ${m.statusText}`);const f=await m.json();r(f),n(null)}catch(m){n(m instanceof Error?m.message:"An unknown error occurred")}finally{l(!1),c.current=!1}}},[]),u=i.useCallback(async()=>{await d()},[d]);return i.useEffect(()=>{d()},[d]),e.jsx(fa.Provider,{value:{cluster:s,error:a,isLoading:o,refresh:u},children:t})}function hm(){return e.jsx(gm,{children:e.jsx(qi,{defaultTheme:"dark",storageKey:"loki-ui-theme",children:e.jsx(fm,{children:e.jsx(um,{children:e.jsx(Co,{children:Nn.map(t=>e.jsx(To,{path:t.path,element:t.element},t.path))})})})})})}const xm=kn(),bm=Ro([{path:"*",element:e.jsx(hm,{})}],{basename:xm,future:{v7_relativeSplatPath:!0}}),co=document.getElementById("root");if(!co)throw new Error("Root element not found");ca(co).render(e.jsx(i.StrictMode,{children:e.jsx(Ao,{router:bm,future:{v7_startTransition:!0}})})); diff --git a/pkg/ui/frontend/dist/assets/query-management-DbWM5GrR.js b/pkg/ui/frontend/dist/assets/query-management-DbWM5GrR.js new file mode 100644 index 0000000000000..47a82c4617148 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/query-management-DbWM5GrR.js @@ -0,0 +1 @@ +var at=t=>{throw TypeError(t)};var He=(t,e,s)=>e.has(t)||at("Cannot "+s);var r=(t,e,s)=>(He(t,e,"read from private field"),s?s.call(t):e.get(t)),l=(t,e,s)=>e.has(t)?at("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),u=(t,e,s,i)=>(He(t,e,"write to private field"),i?i.call(t,s):e.set(t,s),s),p=(t,e,s)=>(He(t,e,"access private method"),s);var ke=(t,e,s,i)=>({set _(n){u(t,e,n,s)},get _(){return r(t,e,i)}});import{r as L}from"./react-core-D_V7s-9r.js";import{j as jt}from"./radix-core-ByqQ8fsu.js";var Ue=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},de=typeof window>"u"||"Deno"in globalThis;function k(){}function kt(t,e){return typeof t=="function"?t(e):t}function Ge(t){return typeof t=="number"&&t>=0&&t!==1/0}function Ft(t,e){return Math.max(t+(e||0)-Date.now(),0)}function pe(t,e){return typeof t=="function"?t(e):t}function G(t,e){return typeof t=="function"?t(e):t}function ut(t,e){const{type:s="all",exact:i,fetchStatus:n,predicate:a,queryKey:h,stale:c}=t;if(h){if(i){if(e.queryHash!==st(h,e.options))return!1}else if(!Te(e.queryKey,h))return!1}if(s!=="all"){const d=e.isActive();if(s==="active"&&!d||s==="inactive"&&d)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||n&&n!==e.state.fetchStatus||a&&!a(e))}function ht(t,e){const{exact:s,status:i,predicate:n,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(s){if(Me(e.options.mutationKey)!==Me(a))return!1}else if(!Te(e.options.mutationKey,a))return!1}return!(i&&e.state.status!==i||n&&!n(e))}function st(t,e){return((e==null?void 0:e.queryKeyHashFn)||Me)(t)}function Me(t){return JSON.stringify(t,(e,s)=>Be(s)?Object.keys(s).sort().reduce((i,n)=>(i[n]=s[n],i),{}):s)}function Te(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?!Object.keys(e).some(s=>!Te(t[s],e[s])):!1}function Qt(t,e){if(t===e)return t;const s=ot(t)&&ot(e);if(s||Be(t)&&Be(e)){const i=s?t:Object.keys(t),n=i.length,a=s?e:Object.keys(e),h=a.length,c=s?[]:{};let d=0;for(let w=0;w<h;w++){const b=s?w:a[w];(!s&&i.includes(b)||s)&&t[b]===void 0&&e[b]===void 0?(c[b]=void 0,d++):(c[b]=Qt(t[b],e[b]),c[b]===t[b]&&t[b]!==void 0&&d++)}return n===h&&d===n?t:c}return e}function Ne(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0}function ot(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Be(t){if(!ct(t))return!1;const e=t.constructor;if(e===void 0)return!0;const s=e.prototype;return!(!ct(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function ct(t){return Object.prototype.toString.call(t)==="[object Object]"}function Lt(t){return new Promise(e=>{setTimeout(e,t)})}function ze(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Qt(t,e):e}function Kt(t,e,s=0){const i=[...t,e];return s&&i.length>s?i.slice(1):i}function Ht(t,e,s=0){const i=[e,...t];return s&&i.length>s?i.slice(0,-1):i}var it=Symbol();function Et(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===it?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}var re,X,me,bt,_t=(bt=class extends Ue{constructor(){super();l(this,re);l(this,X);l(this,me);u(this,me,e=>{if(!de&&window.addEventListener){const s=()=>e();return window.addEventListener("visibilitychange",s,!1),()=>{window.removeEventListener("visibilitychange",s)}}})}onSubscribe(){r(this,X)||this.setEventListener(r(this,me))}onUnsubscribe(){var e;this.hasListeners()||((e=r(this,X))==null||e.call(this),u(this,X,void 0))}setEventListener(e){var s;u(this,me,e),(s=r(this,X))==null||s.call(this),u(this,X,e(i=>{typeof i=="boolean"?this.setFocused(i):this.onFocus()}))}setFocused(e){r(this,re)!==e&&(u(this,re,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(s=>{s(e)})}isFocused(){var e;return typeof r(this,re)=="boolean"?r(this,re):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},re=new WeakMap,X=new WeakMap,me=new WeakMap,bt),rt=new _t,be,Y,ge,gt,Gt=(gt=class extends Ue{constructor(){super();l(this,be,!0);l(this,Y);l(this,ge);u(this,ge,e=>{if(!de&&window.addEventListener){const s=()=>e(!0),i=()=>e(!1);return window.addEventListener("online",s,!1),window.addEventListener("offline",i,!1),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",i)}}})}onSubscribe(){r(this,Y)||this.setEventListener(r(this,ge))}onUnsubscribe(){var e;this.hasListeners()||((e=r(this,Y))==null||e.call(this),u(this,Y,void 0))}setEventListener(e){var s;u(this,ge,e),(s=r(this,Y))==null||s.call(this),u(this,Y,e(this.setOnline.bind(this)))}setOnline(e){r(this,be)!==e&&(u(this,be,e),this.listeners.forEach(i=>{i(e)}))}isOnline(){return r(this,be)}},be=new WeakMap,Y=new WeakMap,ge=new WeakMap,gt),Ke=new Gt;function Ve(){let t,e;const s=new Promise((n,a)=>{t=n,e=a});s.status="pending",s.catch(()=>{});function i(n){Object.assign(s,n),delete s.resolve,delete s.reject}return s.resolve=n=>{i({status:"fulfilled",value:n}),t(n)},s.reject=n=>{i({status:"rejected",reason:n}),e(n)},s}function Nt(t){return Math.min(1e3*2**t,3e4)}function Dt(t){return(t??"online")==="online"?Ke.isOnline():!0}var Mt=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function _e(t){return t instanceof Mt}function Tt(t){let e=!1,s=0,i=!1,n;const a=Ve(),h=f=>{var y;i||(C(new Mt(f)),(y=t.abort)==null||y.call(t))},c=()=>{e=!0},d=()=>{e=!1},w=()=>rt.isFocused()&&(t.networkMode==="always"||Ke.isOnline())&&t.canRun(),b=()=>Dt(t.networkMode)&&t.canRun(),o=f=>{var y;i||(i=!0,(y=t.onSuccess)==null||y.call(t,f),n==null||n(),a.resolve(f))},C=f=>{var y;i||(i=!0,(y=t.onError)==null||y.call(t,f),n==null||n(),a.reject(f))},g=()=>new Promise(f=>{var y;n=Q=>{(i||w())&&f(Q)},(y=t.onPause)==null||y.call(t)}).then(()=>{var f;n=void 0,i||(f=t.onContinue)==null||f.call(t)}),S=()=>{if(i)return;let f;const y=s===0?t.initialPromise:void 0;try{f=y??t.fn()}catch(Q){f=Promise.reject(Q)}Promise.resolve(f).then(o).catch(Q=>{var K;if(i)return;const T=t.retry??(de?0:3),R=t.retryDelay??Nt,D=typeof R=="function"?R(s,Q):R,U=T===!0||typeof T=="number"&&s<T||typeof T=="function"&&T(s,Q);if(e||!U){C(Q);return}s++,(K=t.onFail)==null||K.call(t,s,Q),Lt(D).then(()=>w()?void 0:g()).then(()=>{e?C(Q):S()})})};return{promise:a,cancel:h,continue:()=>(n==null||n(),a),cancelRetry:c,continueRetry:d,canStart:b,start:()=>(b()?S():g().then(S),a)}}function Bt(){let t=[],e=0,s=c=>{c()},i=c=>{c()},n=c=>setTimeout(c,0);const a=c=>{e?t.push(c):n(()=>{s(c)})},h=()=>{const c=t;t=[],c.length&&n(()=>{i(()=>{c.forEach(d=>{s(d)})})})};return{batch:c=>{let d;e++;try{d=c()}finally{e--,e||h()}return d},batchCalls:c=>(...d)=>{a(()=>{c(...d)})},schedule:a,setNotifyFunction:c=>{s=c},setBatchNotifyFunction:c=>{i=c},setScheduler:c=>{n=c}}}var E=Bt(),ne,vt,At=(vt=class{constructor(){l(this,ne)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ge(this.gcTime)&&u(this,ne,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(de?1/0:5*60*1e3))}clearGcTimeout(){r(this,ne)&&(clearTimeout(r(this,ne)),u(this,ne,void 0))}},ne=new WeakMap,vt),ve,we,j,ae,M,Ae,ue,H,$,wt,zt=(wt=class extends At{constructor(e){super();l(this,H);l(this,ve);l(this,we);l(this,j);l(this,ae);l(this,M);l(this,Ae);l(this,ue);u(this,ue,!1),u(this,Ae,e.defaultOptions),this.setOptions(e.options),this.observers=[],u(this,ae,e.client),u(this,j,r(this,ae).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,u(this,ve,Vt(this.options)),this.state=e.state??r(this,ve),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=r(this,M))==null?void 0:e.promise}setOptions(e){this.options={...r(this,Ae),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&r(this,j).remove(this)}setData(e,s){const i=ze(this.state.data,e,this.options);return p(this,H,$).call(this,{data:i,type:"success",dataUpdatedAt:s==null?void 0:s.updatedAt,manual:s==null?void 0:s.manual}),i}setState(e,s){p(this,H,$).call(this,{type:"setState",state:e,setStateOptions:s})}cancel(e){var i,n;const s=(i=r(this,M))==null?void 0:i.promise;return(n=r(this,M))==null||n.cancel(e),s?s.then(k).catch(k):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(r(this,ve))}isActive(){return this.observers.some(e=>G(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===it||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Ft(this.state.dataUpdatedAt,e)}onFocus(){var s;const e=this.observers.find(i=>i.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(s=r(this,M))==null||s.continue()}onOnline(){var s;const e=this.observers.find(i=>i.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(s=r(this,M))==null||s.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),r(this,j).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(s=>s!==e),this.observers.length||(r(this,M)&&(r(this,ue)?r(this,M).cancel({revert:!0}):r(this,M).cancelRetry()),this.scheduleGc()),r(this,j).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||p(this,H,$).call(this,{type:"invalidate"})}fetch(e,s){var d,w,b;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(s!=null&&s.cancelRefetch))this.cancel({silent:!0});else if(r(this,M))return r(this,M).continueRetry(),r(this,M).promise}if(e&&this.setOptions(e),!this.options.queryFn){const o=this.observers.find(C=>C.options.queryFn);o&&this.setOptions(o.options)}const i=new AbortController,n=o=>{Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(u(this,ue,!0),i.signal)})},a=()=>{const o=Et(this.options,s),C={client:r(this,ae),queryKey:this.queryKey,meta:this.meta};return n(C),u(this,ue,!1),this.options.persister?this.options.persister(o,C,this):o(C)},h={fetchOptions:s,options:this.options,queryKey:this.queryKey,client:r(this,ae),state:this.state,fetchFn:a};n(h),(d=this.options.behavior)==null||d.onFetch(h,this),u(this,we,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((w=h.fetchOptions)==null?void 0:w.meta))&&p(this,H,$).call(this,{type:"fetch",meta:(b=h.fetchOptions)==null?void 0:b.meta});const c=o=>{var C,g,S,f;_e(o)&&o.silent||p(this,H,$).call(this,{type:"error",error:o}),_e(o)||((g=(C=r(this,j).config).onError)==null||g.call(C,o,this),(f=(S=r(this,j).config).onSettled)==null||f.call(S,this.state.data,o,this)),this.scheduleGc()};return u(this,M,Tt({initialPromise:s==null?void 0:s.initialPromise,fn:h.fetchFn,abort:i.abort.bind(i),onSuccess:o=>{var C,g,S,f;if(o===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(o)}catch(y){c(y);return}(g=(C=r(this,j).config).onSuccess)==null||g.call(C,o,this),(f=(S=r(this,j).config).onSettled)==null||f.call(S,o,this.state.error,this),this.scheduleGc()},onError:c,onFail:(o,C)=>{p(this,H,$).call(this,{type:"failed",failureCount:o,error:C})},onPause:()=>{p(this,H,$).call(this,{type:"pause"})},onContinue:()=>{p(this,H,$).call(this,{type:"continue"})},retry:h.options.retry,retryDelay:h.options.retryDelay,networkMode:h.options.networkMode,canRun:()=>!0})),r(this,M).start()}},ve=new WeakMap,we=new WeakMap,j=new WeakMap,ae=new WeakMap,M=new WeakMap,Ae=new WeakMap,ue=new WeakMap,H=new WeakSet,$=function(e){const s=i=>{switch(e.type){case"failed":return{...i,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...i,fetchStatus:"paused"};case"continue":return{...i,fetchStatus:"fetching"};case"fetch":return{...i,...It(i.data,this.options),fetchMeta:e.meta??null};case"success":return{...i,data:e.data,dataUpdateCount:i.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=e.error;return _e(n)&&n.revert&&r(this,we)?{...r(this,we),fetchStatus:"idle"}:{...i,error:n,errorUpdateCount:i.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:i.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...i,isInvalidated:!0};case"setState":return{...i,...e.state}}};this.state=s(this.state),E.batch(()=>{this.observers.forEach(i=>{i.onQueryUpdate()}),r(this,j).notify({query:this,type:"updated",action:e})})},wt);function It(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Dt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Vt(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,i=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var N,Ct,$t=(Ct=class extends Ue{constructor(e={}){super();l(this,N);this.config=e,u(this,N,new Map)}build(e,s,i){const n=s.queryKey,a=s.queryHash??st(n,s);let h=this.get(a);return h||(h=new zt({client:e,queryKey:n,queryHash:a,options:e.defaultQueryOptions(s),state:i,defaultOptions:e.getQueryDefaults(n)}),this.add(h)),h}add(e){r(this,N).has(e.queryHash)||(r(this,N).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const s=r(this,N).get(e.queryHash);s&&(e.destroy(),s===e&&r(this,N).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){E.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return r(this,N).get(e)}getAll(){return[...r(this,N).values()]}find(e){const s={exact:!0,...e};return this.getAll().find(i=>ut(s,i))}findAll(e={}){const s=this.getAll();return Object.keys(e).length>0?s.filter(i=>ut(e,i)):s}notify(e){E.batch(()=>{this.listeners.forEach(s=>{s(e)})})}onFocus(){E.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){E.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},N=new WeakMap,Ct),B,I,he,z,J,Ot,Wt=(Ot=class extends At{constructor(e){super();l(this,z);l(this,B);l(this,I);l(this,he);this.mutationId=e.mutationId,u(this,I,e.mutationCache),u(this,B,[]),this.state=e.state||Jt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){r(this,B).includes(e)||(r(this,B).push(e),this.clearGcTimeout(),r(this,I).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){u(this,B,r(this,B).filter(s=>s!==e)),this.scheduleGc(),r(this,I).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){r(this,B).length||(this.state.status==="pending"?this.scheduleGc():r(this,I).remove(this))}continue(){var e;return((e=r(this,he))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var n,a,h,c,d,w,b,o,C,g,S,f,y,Q,T,R,D,U,K,A;u(this,he,Tt({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(F,O)=>{p(this,z,J).call(this,{type:"failed",failureCount:F,error:O})},onPause:()=>{p(this,z,J).call(this,{type:"pause"})},onContinue:()=>{p(this,z,J).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>r(this,I).canRun(this)}));const s=this.state.status==="pending",i=!r(this,he).canStart();try{if(!s){p(this,z,J).call(this,{type:"pending",variables:e,isPaused:i}),await((a=(n=r(this,I).config).onMutate)==null?void 0:a.call(n,e,this));const O=await((c=(h=this.options).onMutate)==null?void 0:c.call(h,e));O!==this.state.context&&p(this,z,J).call(this,{type:"pending",context:O,variables:e,isPaused:i})}const F=await r(this,he).start();return await((w=(d=r(this,I).config).onSuccess)==null?void 0:w.call(d,F,e,this.state.context,this)),await((o=(b=this.options).onSuccess)==null?void 0:o.call(b,F,e,this.state.context)),await((g=(C=r(this,I).config).onSettled)==null?void 0:g.call(C,F,null,this.state.variables,this.state.context,this)),await((f=(S=this.options).onSettled)==null?void 0:f.call(S,F,null,e,this.state.context)),p(this,z,J).call(this,{type:"success",data:F}),F}catch(F){try{throw await((Q=(y=r(this,I).config).onError)==null?void 0:Q.call(y,F,e,this.state.context,this)),await((R=(T=this.options).onError)==null?void 0:R.call(T,F,e,this.state.context)),await((U=(D=r(this,I).config).onSettled)==null?void 0:U.call(D,void 0,F,this.state.variables,this.state.context,this)),await((A=(K=this.options).onSettled)==null?void 0:A.call(K,void 0,F,e,this.state.context)),F}finally{p(this,z,J).call(this,{type:"error",error:F})}}finally{r(this,I).runNext(this)}}},B=new WeakMap,I=new WeakMap,he=new WeakMap,z=new WeakSet,J=function(e){const s=i=>{switch(e.type){case"failed":return{...i,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...i,isPaused:!0};case"continue":return{...i,isPaused:!1};case"pending":return{...i,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...i,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...i,data:void 0,error:e.error,failureCount:i.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=s(this.state),E.batch(()=>{r(this,B).forEach(i=>{i.onMutationUpdate(e)}),r(this,I).notify({mutation:this,type:"updated",action:e})})},Ot);function Jt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var W,_,Ie,Rt,Xt=(Rt=class extends Ue{constructor(e={}){super();l(this,W);l(this,_);l(this,Ie);this.config=e,u(this,W,new Set),u(this,_,new Map),u(this,Ie,0)}build(e,s,i){const n=new Wt({mutationCache:this,mutationId:++ke(this,Ie)._,options:e.defaultMutationOptions(s),state:i});return this.add(n),n}add(e){r(this,W).add(e);const s=Le(e);if(typeof s=="string"){const i=r(this,_).get(s);i?i.push(e):r(this,_).set(s,[e])}this.notify({type:"added",mutation:e})}remove(e){if(r(this,W).delete(e)){const s=Le(e);if(typeof s=="string"){const i=r(this,_).get(s);if(i)if(i.length>1){const n=i.indexOf(e);n!==-1&&i.splice(n,1)}else i[0]===e&&r(this,_).delete(s)}}this.notify({type:"removed",mutation:e})}canRun(e){const s=Le(e);if(typeof s=="string"){const i=r(this,_).get(s),n=i==null?void 0:i.find(a=>a.state.status==="pending");return!n||n===e}else return!0}runNext(e){var i;const s=Le(e);if(typeof s=="string"){const n=(i=r(this,_).get(s))==null?void 0:i.find(a=>a!==e&&a.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){E.batch(()=>{r(this,W).forEach(e=>{this.notify({type:"removed",mutation:e})}),r(this,W).clear(),r(this,_).clear()})}getAll(){return Array.from(r(this,W))}find(e){const s={exact:!0,...e};return this.getAll().find(i=>ht(s,i))}findAll(e={}){return this.getAll().filter(s=>ht(e,s))}notify(e){E.batch(()=>{this.listeners.forEach(s=>{s(e)})})}resumePausedMutations(){const e=this.getAll().filter(s=>s.state.isPaused);return E.batch(()=>Promise.all(e.map(s=>s.continue().catch(k))))}},W=new WeakMap,_=new WeakMap,Ie=new WeakMap,Rt);function Le(t){var e;return(e=t.options.scope)==null?void 0:e.id}function lt(t){return{onFetch:(e,s)=>{var b,o,C,g,S;const i=e.options,n=(C=(o=(b=e.fetchOptions)==null?void 0:b.meta)==null?void 0:o.fetchMore)==null?void 0:C.direction,a=((g=e.state.data)==null?void 0:g.pages)||[],h=((S=e.state.data)==null?void 0:S.pageParams)||[];let c={pages:[],pageParams:[]},d=0;const w=async()=>{let f=!1;const y=R=>{Object.defineProperty(R,"signal",{enumerable:!0,get:()=>(e.signal.aborted?f=!0:e.signal.addEventListener("abort",()=>{f=!0}),e.signal)})},Q=Et(e.options,e.fetchOptions),T=async(R,D,U)=>{if(f)return Promise.reject();if(D==null&&R.pages.length)return Promise.resolve(R);const K={client:e.client,queryKey:e.queryKey,pageParam:D,direction:U?"backward":"forward",meta:e.options.meta};y(K);const A=await Q(K),{maxPages:F}=e.options,O=U?Ht:Kt;return{pages:O(R.pages,A,F),pageParams:O(R.pageParams,D,F)}};if(n&&a.length){const R=n==="backward",D=R?Yt:dt,U={pages:a,pageParams:h},K=D(i,U);c=await T(U,K,R)}else{const R=t??a.length;do{const D=d===0?h[0]??i.initialPageParam:dt(i,c);if(d>0&&D==null)break;c=await T(c,D),d++}while(d<R)}return c};e.options.persister?e.fetchFn=()=>{var f,y;return(y=(f=e.options).persister)==null?void 0:y.call(f,w,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s)}:e.fetchFn=w}}}function dt(t,{pages:e,pageParams:s}){const i=e.length-1;return e.length>0?t.getNextPageParam(e[i],e,s[i],s):void 0}function Yt(t,{pages:e,pageParams:s}){var i;return e.length>0?(i=t.getPreviousPageParam)==null?void 0:i.call(t,e[0],e,s[0],s):void 0}var P,Z,ee,Ce,Oe,te,Re,Pe,Pt,gs=(Pt=class{constructor(t={}){l(this,P);l(this,Z);l(this,ee);l(this,Ce);l(this,Oe);l(this,te);l(this,Re);l(this,Pe);u(this,P,t.queryCache||new $t),u(this,Z,t.mutationCache||new Xt),u(this,ee,t.defaultOptions||{}),u(this,Ce,new Map),u(this,Oe,new Map),u(this,te,0)}mount(){ke(this,te)._++,r(this,te)===1&&(u(this,Re,rt.subscribe(async t=>{t&&(await this.resumePausedMutations(),r(this,P).onFocus())})),u(this,Pe,Ke.subscribe(async t=>{t&&(await this.resumePausedMutations(),r(this,P).onOnline())})))}unmount(){var t,e;ke(this,te)._--,r(this,te)===0&&((t=r(this,Re))==null||t.call(this),u(this,Re,void 0),(e=r(this,Pe))==null||e.call(this),u(this,Pe,void 0))}isFetching(t){return r(this,P).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return r(this,Z).findAll({...t,status:"pending"}).length}getQueryData(t){var s;const e=this.defaultQueryOptions({queryKey:t});return(s=r(this,P).get(e.queryHash))==null?void 0:s.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),s=r(this,P).build(this,e),i=s.state.data;return i===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(pe(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(i))}getQueriesData(t){return r(this,P).findAll(t).map(({queryKey:e,state:s})=>{const i=s.data;return[e,i]})}setQueryData(t,e,s){const i=this.defaultQueryOptions({queryKey:t}),n=r(this,P).get(i.queryHash),a=n==null?void 0:n.state.data,h=kt(e,a);if(h!==void 0)return r(this,P).build(this,i).setData(h,{...s,manual:!0})}setQueriesData(t,e,s){return E.batch(()=>r(this,P).findAll(t).map(({queryKey:i})=>[i,this.setQueryData(i,e,s)]))}getQueryState(t){var s;const e=this.defaultQueryOptions({queryKey:t});return(s=r(this,P).get(e.queryHash))==null?void 0:s.state}removeQueries(t){const e=r(this,P);E.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){const s=r(this,P),i={type:"active",...t};return E.batch(()=>(s.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries(i,e)))}cancelQueries(t,e={}){const s={revert:!0,...e},i=E.batch(()=>r(this,P).findAll(t).map(n=>n.cancel(s)));return Promise.all(i).then(k).catch(k)}invalidateQueries(t,e={}){return E.batch(()=>{if(r(this,P).findAll(t).forEach(i=>{i.invalidate()}),(t==null?void 0:t.refetchType)==="none")return Promise.resolve();const s={...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"};return this.refetchQueries(s,e)})}refetchQueries(t,e={}){const s={...e,cancelRefetch:e.cancelRefetch??!0},i=E.batch(()=>r(this,P).findAll(t).filter(n=>!n.isDisabled()).map(n=>{let a=n.fetch(void 0,s);return s.throwOnError||(a=a.catch(k)),n.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(i).then(k)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const s=r(this,P).build(this,e);return s.isStaleByTime(pe(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(k).catch(k)}fetchInfiniteQuery(t){return t.behavior=lt(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(k).catch(k)}ensureInfiniteQueryData(t){return t.behavior=lt(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Ke.isOnline()?r(this,Z).resumePausedMutations():Promise.resolve()}getQueryCache(){return r(this,P)}getMutationCache(){return r(this,Z)}getDefaultOptions(){return r(this,ee)}setDefaultOptions(t){u(this,ee,t)}setQueryDefaults(t,e){r(this,Ce).set(Me(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...r(this,Ce).values()],s={};return e.forEach(i=>{Te(t,i.queryKey)&&Object.assign(s,i.defaultOptions)}),s}setMutationDefaults(t,e){r(this,Oe).set(Me(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...r(this,Oe).values()];let s={};return e.forEach(i=>{Te(t,i.mutationKey)&&(s={...s,...i.defaultOptions})}),s}defaultQueryOptions(t){if(t._defaulted)return t;const e={...r(this,ee).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=st(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===it&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...r(this,ee).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){r(this,P).clear(),r(this,Z).clear()}},P=new WeakMap,Z=new WeakMap,ee=new WeakMap,Ce=new WeakMap,Oe=new WeakMap,te=new WeakMap,Re=new WeakMap,Pe=new WeakMap,Pt),q,m,xe,x,oe,Se,se,V,qe,Fe,Qe,ce,le,ie,Ee,v,De,$e,We,Je,Xe,Ye,Ze,et,xt,St,Zt=(St=class extends Ue{constructor(e,s){super();l(this,v);l(this,q);l(this,m);l(this,xe);l(this,x);l(this,oe);l(this,Se);l(this,se);l(this,V);l(this,qe);l(this,Fe);l(this,Qe);l(this,ce);l(this,le);l(this,ie);l(this,Ee,new Set);this.options=s,u(this,q,e),u(this,V,null),u(this,se,Ve()),this.options.experimental_prefetchInRender||r(this,se).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(s)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(r(this,m).addObserver(this),ft(r(this,m),this.options)?p(this,v,De).call(this):this.updateResult(),p(this,v,Xe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return tt(r(this,m),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return tt(r(this,m),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,p(this,v,Ye).call(this),p(this,v,Ze).call(this),r(this,m).removeObserver(this)}setOptions(e,s){const i=this.options,n=r(this,m);if(this.options=r(this,q).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof G(this.options.enabled,r(this,m))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");p(this,v,et).call(this),r(this,m).setOptions(this.options),i._defaulted&&!Ne(this.options,i)&&r(this,q).getQueryCache().notify({type:"observerOptionsUpdated",query:r(this,m),observer:this});const a=this.hasListeners();a&&yt(r(this,m),n,this.options,i)&&p(this,v,De).call(this),this.updateResult(s),a&&(r(this,m)!==n||G(this.options.enabled,r(this,m))!==G(i.enabled,r(this,m))||pe(this.options.staleTime,r(this,m))!==pe(i.staleTime,r(this,m)))&&p(this,v,$e).call(this);const h=p(this,v,We).call(this);a&&(r(this,m)!==n||G(this.options.enabled,r(this,m))!==G(i.enabled,r(this,m))||h!==r(this,ie))&&p(this,v,Je).call(this,h)}getOptimisticResult(e){const s=r(this,q).getQueryCache().build(r(this,q),e),i=this.createResult(s,e);return ts(this,i)&&(u(this,x,i),u(this,Se,this.options),u(this,oe,r(this,m).state)),i}getCurrentResult(){return r(this,x)}trackResult(e,s){const i={};return Object.keys(e).forEach(n=>{Object.defineProperty(i,n,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(n),s==null||s(n),e[n])})}),i}trackProp(e){r(this,Ee).add(e)}getCurrentQuery(){return r(this,m)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const s=r(this,q).defaultQueryOptions(e),i=r(this,q).getQueryCache().build(r(this,q),s);return i.fetch().then(()=>this.createResult(i,s))}fetch(e){return p(this,v,De).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),r(this,x)))}createResult(e,s){var F;const i=r(this,m),n=this.options,a=r(this,x),h=r(this,oe),c=r(this,Se),w=e!==i?e.state:r(this,xe),{state:b}=e;let o={...b},C=!1,g;if(s._optimisticResults){const O=this.hasListeners(),fe=!O&&ft(e,s),ye=O&&yt(e,i,s,n);(fe||ye)&&(o={...o,...It(b.data,e.options)}),s._optimisticResults==="isRestoring"&&(o.fetchStatus="idle")}let{error:S,errorUpdatedAt:f,status:y}=o;if(s.select&&o.data!==void 0)if(a&&o.data===(h==null?void 0:h.data)&&s.select===r(this,qe))g=r(this,Fe);else try{u(this,qe,s.select),g=s.select(o.data),g=ze(a==null?void 0:a.data,g,s),u(this,Fe,g),u(this,V,null)}catch(O){u(this,V,O)}else g=o.data;if(s.placeholderData!==void 0&&g===void 0&&y==="pending"){let O;if(a!=null&&a.isPlaceholderData&&s.placeholderData===(c==null?void 0:c.placeholderData))O=a.data;else if(O=typeof s.placeholderData=="function"?s.placeholderData((F=r(this,Qe))==null?void 0:F.state.data,r(this,Qe)):s.placeholderData,s.select&&O!==void 0)try{O=s.select(O),u(this,V,null)}catch(fe){u(this,V,fe)}O!==void 0&&(y="success",g=ze(a==null?void 0:a.data,O,s),C=!0)}r(this,V)&&(S=r(this,V),g=r(this,Fe),f=Date.now(),y="error");const Q=o.fetchStatus==="fetching",T=y==="pending",R=y==="error",D=T&&Q,U=g!==void 0,A={status:y,fetchStatus:o.fetchStatus,isPending:T,isSuccess:y==="success",isError:R,isInitialLoading:D,isLoading:D,data:g,dataUpdatedAt:o.dataUpdatedAt,error:S,errorUpdatedAt:f,failureCount:o.fetchFailureCount,failureReason:o.fetchFailureReason,errorUpdateCount:o.errorUpdateCount,isFetched:o.dataUpdateCount>0||o.errorUpdateCount>0,isFetchedAfterMount:o.dataUpdateCount>w.dataUpdateCount||o.errorUpdateCount>w.errorUpdateCount,isFetching:Q,isRefetching:Q&&!T,isLoadingError:R&&!U,isPaused:o.fetchStatus==="paused",isPlaceholderData:C,isRefetchError:R&&U,isStale:nt(e,s),refetch:this.refetch,promise:r(this,se)};if(this.options.experimental_prefetchInRender){const O=je=>{A.status==="error"?je.reject(A.error):A.data!==void 0&&je.resolve(A.data)},fe=()=>{const je=u(this,se,A.promise=Ve());O(je)},ye=r(this,se);switch(ye.status){case"pending":e.queryHash===i.queryHash&&O(ye);break;case"fulfilled":(A.status==="error"||A.data!==ye.value)&&fe();break;case"rejected":(A.status!=="error"||A.error!==ye.reason)&&fe();break}}return A}updateResult(e){const s=r(this,x),i=this.createResult(r(this,m),this.options);if(u(this,oe,r(this,m).state),u(this,Se,this.options),r(this,oe).data!==void 0&&u(this,Qe,r(this,m)),Ne(i,s))return;u(this,x,i);const n={},a=()=>{if(!s)return!0;const{notifyOnChangeProps:h}=this.options,c=typeof h=="function"?h():h;if(c==="all"||!c&&!r(this,Ee).size)return!0;const d=new Set(c??r(this,Ee));return this.options.throwOnError&&d.add("error"),Object.keys(r(this,x)).some(w=>{const b=w;return r(this,x)[b]!==s[b]&&d.has(b)})};(e==null?void 0:e.listeners)!==!1&&a()&&(n.listeners=!0),p(this,v,xt).call(this,{...n,...e})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&p(this,v,Xe).call(this)}},q=new WeakMap,m=new WeakMap,xe=new WeakMap,x=new WeakMap,oe=new WeakMap,Se=new WeakMap,se=new WeakMap,V=new WeakMap,qe=new WeakMap,Fe=new WeakMap,Qe=new WeakMap,ce=new WeakMap,le=new WeakMap,ie=new WeakMap,Ee=new WeakMap,v=new WeakSet,De=function(e){p(this,v,et).call(this);let s=r(this,m).fetch(this.options,e);return e!=null&&e.throwOnError||(s=s.catch(k)),s},$e=function(){p(this,v,Ye).call(this);const e=pe(this.options.staleTime,r(this,m));if(de||r(this,x).isStale||!Ge(e))return;const i=Ft(r(this,x).dataUpdatedAt,e)+1;u(this,ce,setTimeout(()=>{r(this,x).isStale||this.updateResult()},i))},We=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(r(this,m)):this.options.refetchInterval)??!1},Je=function(e){p(this,v,Ze).call(this),u(this,ie,e),!(de||G(this.options.enabled,r(this,m))===!1||!Ge(r(this,ie))||r(this,ie)===0)&&u(this,le,setInterval(()=>{(this.options.refetchIntervalInBackground||rt.isFocused())&&p(this,v,De).call(this)},r(this,ie)))},Xe=function(){p(this,v,$e).call(this),p(this,v,Je).call(this,p(this,v,We).call(this))},Ye=function(){r(this,ce)&&(clearTimeout(r(this,ce)),u(this,ce,void 0))},Ze=function(){r(this,le)&&(clearInterval(r(this,le)),u(this,le,void 0))},et=function(){const e=r(this,q).getQueryCache().build(r(this,q),this.options);if(e===r(this,m))return;const s=r(this,m);u(this,m,e),u(this,xe,e.state),this.hasListeners()&&(s==null||s.removeObserver(this),e.addObserver(this))},xt=function(e){E.batch(()=>{e.listeners&&this.listeners.forEach(s=>{s(r(this,x))}),r(this,q).getQueryCache().notify({query:r(this,m),type:"observerResultsUpdated"})})},St);function es(t,e){return G(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function ft(t,e){return es(t,e)||t.state.data!==void 0&&tt(t,e,e.refetchOnMount)}function tt(t,e,s){if(G(e.enabled,t)!==!1){const i=typeof s=="function"?s(t):s;return i==="always"||i!==!1&&nt(t,e)}return!1}function yt(t,e,s,i){return(t!==e||G(i.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&nt(t,s)}function nt(t,e){return G(e.enabled,t)!==!1&&t.isStaleByTime(pe(e.staleTime,t))}function ts(t,e){return!Ne(t.getCurrentResult(),e)}var qt=L.createContext(void 0),ss=t=>{const e=L.useContext(qt);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},vs=({client:t,children:e})=>(L.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),jt.jsx(qt.Provider,{value:t,children:e})),Ut=L.createContext(!1),is=()=>L.useContext(Ut);Ut.Provider;function rs(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var ns=L.createContext(rs()),as=()=>L.useContext(ns);function us(t,e){return typeof t=="function"?t(...e):!!t}function pt(){}var hs=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},os=t=>{L.useEffect(()=>{t.clearReset()},[t])},cs=({result:t,errorResetBoundary:e,throwOnError:s,query:i,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&i&&(n&&t.data===void 0||us(s,[t.error,i])),ls=t=>{const e=t.staleTime;t.suspense&&(t.staleTime=typeof e=="function"?(...s)=>Math.max(e(...s),1e3):Math.max(e??1e3,1e3),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3)))},ds=(t,e)=>t.isLoading&&t.isFetching&&!e,fs=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,mt=(t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()});function ys(t,e,s){var o,C,g,S,f;const i=ss(),n=is(),a=as(),h=i.defaultQueryOptions(t);(C=(o=i.getDefaultOptions().queries)==null?void 0:o._experimental_beforeQuery)==null||C.call(o,h),h._optimisticResults=n?"isRestoring":"optimistic",ls(h),hs(h,a),os(a);const c=!i.getQueryCache().get(h.queryHash),[d]=L.useState(()=>new e(i,h)),w=d.getOptimisticResult(h),b=!n&&t.subscribed!==!1;if(L.useSyncExternalStore(L.useCallback(y=>{const Q=b?d.subscribe(E.batchCalls(y)):pt;return d.updateResult(),Q},[d,b]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),L.useEffect(()=>{d.setOptions(h,{listeners:!1})},[h,d]),fs(h,w))throw mt(h,d,a);if(cs({result:w,errorResetBoundary:a,throwOnError:h.throwOnError,query:i.getQueryCache().get(h.queryHash),suspense:h.suspense}))throw w.error;if((S=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_afterQuery)==null||S.call(g,h,w),h.experimental_prefetchInRender&&!de&&ds(w,n)){const y=c?mt(h,d,a):(f=i.getQueryCache().get(h.queryHash))==null?void 0:f.promise;y==null||y.catch(pt).finally(()=>{d.updateResult()})}return h.notifyOnChangeProps?w:d.trackResult(w)}function ws(t,e){return ys(t,Zt)}export{gs as Q,ss as a,vs as b,ws as u}; diff --git a/pkg/ui/frontend/dist/assets/radix-core-ByqQ8fsu.js b/pkg/ui/frontend/dist/assets/radix-core-ByqQ8fsu.js new file mode 100644 index 0000000000000..6ce59bacc2ea3 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/radix-core-ByqQ8fsu.js @@ -0,0 +1,49 @@ +import{r as c,c as nn,R as Er,d as Cr}from"./react-core-D_V7s-9r.js";var rn={exports:{}},je={};/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Pr=c,Ar=Symbol.for("react.element"),Rr=Symbol.for("react.fragment"),Sr=Object.prototype.hasOwnProperty,Or=Pr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Tr={key:!0,ref:!0,__self:!0,__source:!0};function on(e,t,n){var r,o={},i=null,s=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(s=t.ref);for(r in t)Sr.call(t,r)&&!Tr.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:Ar,type:e,key:i,ref:s,props:o,_owner:Or.current}}je.Fragment=Rr;je.jsx=on;je.jsxs=on;rn.exports=je;var C=rn.exports;function kt(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function sn(...e){return t=>{let n=!1;const r=e.map(o=>{const i=kt(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():kt(e[o],null)}}}}function K(...e){return c.useCallback(sn(...e),e)}var ft=c.forwardRef((e,t)=>{const{children:n,...r}=e,o=c.Children.toArray(n),i=o.find(Nr);if(i){const s=i.props.children,a=o.map(l=>l===i?c.Children.count(s)>1?c.Children.only(null):c.isValidElement(s)?s.props.children:null:l);return C.jsx(rt,{...r,ref:t,children:c.isValidElement(s)?c.cloneElement(s,void 0,a):null})}return C.jsx(rt,{...r,ref:t,children:n})});ft.displayName="Slot";var rt=c.forwardRef((e,t)=>{const{children:n,...r}=e;if(c.isValidElement(n)){const o=Lr(n);return c.cloneElement(n,{...Mr(r,n.props),ref:t?sn(t,o):o})}return c.Children.count(n)>1?c.Children.only(null):null});rt.displayName="SlotClone";var an=({children:e})=>C.jsx(C.Fragment,{children:e});function Nr(e){return c.isValidElement(e)&&e.type===an}function Mr(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{i(...a),o(...a)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Lr(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function As(e,t){const n=c.createContext(t),r=i=>{const{children:s,...a}=i,l=c.useMemo(()=>a,Object.values(a));return C.jsx(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function o(i){const s=c.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function dt(e,t=[]){let n=[];function r(i,s){const a=c.createContext(s),l=n.length;n=[...n,s];const u=d=>{var y;const{scope:m,children:h,...g}=d,p=((y=m==null?void 0:m[e])==null?void 0:y[l])||a,v=c.useMemo(()=>g,Object.values(g));return C.jsx(p.Provider,{value:v,children:h})};u.displayName=i+"Provider";function f(d,m){var p;const h=((p=m==null?void 0:m[e])==null?void 0:p[l])||a,g=c.useContext(h);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,f]}const o=()=>{const i=n.map(s=>c.createContext(s));return function(a){const l=(a==null?void 0:a[e])||i;return c.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Dr(o,...t)]}function Dr(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((a,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...a,...d}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}function I(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function J(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function cn({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=_r({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,a=J(n),l=c.useCallback(u=>{if(i){const d=typeof u=="function"?u(e):u;d!==e&&a(d)}else o(u)},[i,e,o,a]);return[s,l]}function _r({defaultProp:e,onChange:t}){const n=c.useState(e),[r]=n,o=c.useRef(r),i=J(t);return c.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}var oe=globalThis!=null&&globalThis.document?c.useLayoutEffect:()=>{};function kr(e){const[t,n]=c.useState(void 0);return oe(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,a;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;s=u.inlineSize,a=u.blockSize}else s=e.offsetWidth,a=e.offsetHeight;n({width:s,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}function Fr(e,t){return c.useReducer((n,r)=>t[n][r]??n,e)}var we=e=>{const{present:t,children:n}=e,r=Ir(t),o=typeof n=="function"?n({present:r.isPresent}):c.Children.only(n),i=K(r.ref,jr(o));return typeof n=="function"||r.isPresent?c.cloneElement(o,{ref:i}):null};we.displayName="Presence";function Ir(e){const[t,n]=c.useState(),r=c.useRef({}),o=c.useRef(e),i=c.useRef("none"),s=e?"mounted":"unmounted",[a,l]=Fr(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return c.useEffect(()=>{const u=Ae(r.current);i.current=a==="mounted"?u:"none"},[a]),oe(()=>{const u=r.current,f=o.current;if(f!==e){const m=i.current,h=Ae(u);e?l("MOUNT"):h==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&m!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),oe(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,d=h=>{const p=Ae(r.current).includes(h.animationName);if(h.target===t&&p&&(l("ANIMATION_END"),!o.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},m=h=>{h.target===t&&(i.current=Ae(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:c.useCallback(u=>{u&&(r.current=getComputedStyle(u)),n(u)},[])}}function Ae(e){return(e==null?void 0:e.animationName)||"none"}function jr(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Wr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],B=Wr.reduce((e,t)=>{const n=c.forwardRef((r,o)=>{const{asChild:i,...s}=r,a=i?ft:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),C.jsx(a,{...s,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function $r(e,t){e&&nn.flushSync(()=>e.dispatchEvent(t))}function Br(e,t=globalThis==null?void 0:globalThis.document){const n=J(e);c.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Hr="DismissableLayer",ot="dismissableLayer.update",Vr="dismissableLayer.pointerDownOutside",Ur="dismissableLayer.focusOutside",Ft,ln=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),We=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:s,onDismiss:a,...l}=e,u=c.useContext(ln),[f,d]=c.useState(null),m=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=c.useState({}),g=K(t,P=>d(P)),p=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=p.indexOf(v),w=f?p.indexOf(f):-1,b=u.layersWithOutsidePointerEventsDisabled.size>0,x=w>=y,E=Yr(P=>{const S=P.target,N=[...u.branches].some(O=>O.contains(S));!x||N||(o==null||o(P),s==null||s(P),P.defaultPrevented||a==null||a())},m),A=Xr(P=>{const S=P.target;[...u.branches].some(O=>O.contains(S))||(i==null||i(P),s==null||s(P),P.defaultPrevented||a==null||a())},m);return Br(P=>{w===u.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&a&&(P.preventDefault(),a()))},m),c.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Ft=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),It(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Ft)}},[f,m,n,u]),c.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),It())},[f,u]),c.useEffect(()=>{const P=()=>h({});return document.addEventListener(ot,P),()=>document.removeEventListener(ot,P)},[]),C.jsx(B.div,{...l,ref:g,style:{pointerEvents:b?x?"auto":"none":void 0,...e.style},onFocusCapture:I(e.onFocusCapture,A.onFocusCapture),onBlurCapture:I(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:I(e.onPointerDownCapture,E.onPointerDownCapture)})});We.displayName=Hr;var zr="DismissableLayerBranch",un=c.forwardRef((e,t)=>{const n=c.useContext(ln),r=c.useRef(null),o=K(t,r);return c.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),C.jsx(B.div,{...e,ref:o})});un.displayName=zr;function Yr(e,t=globalThis==null?void 0:globalThis.document){const n=J(e),r=c.useRef(!1),o=c.useRef(()=>{});return c.useEffect(()=>{const i=a=>{if(a.target&&!r.current){let l=function(){fn(Vr,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Xr(e,t=globalThis==null?void 0:globalThis.document){const n=J(e),r=c.useRef(!1);return c.useEffect(()=>{const o=i=>{i.target&&!r.current&&fn(Ur,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function It(){const e=new CustomEvent(ot);document.dispatchEvent(e)}function fn(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?$r(o,i):o.dispatchEvent(i)}var Rs=We,Ss=un,Ke=0;function Kr(){c.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??jt()),document.body.insertAdjacentElement("beforeend",e[1]??jt()),Ke++,()=>{Ke===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ke--}},[])}function jt(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ge="focusScope.autoFocusOnMount",qe="focusScope.autoFocusOnUnmount",Wt={bubbles:!1,cancelable:!0},Gr="FocusScope",dn=c.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[a,l]=c.useState(null),u=J(o),f=J(i),d=c.useRef(null),m=K(t,p=>l(p)),h=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(r){let p=function(b){if(h.paused||!a)return;const x=b.target;a.contains(x)?d.current=x:Q(d.current,{select:!0})},v=function(b){if(h.paused||!a)return;const x=b.relatedTarget;x!==null&&(a.contains(x)||Q(d.current,{select:!0}))},y=function(b){if(document.activeElement===document.body)for(const E of b)E.removedNodes.length>0&&Q(a)};document.addEventListener("focusin",p),document.addEventListener("focusout",v);const w=new MutationObserver(y);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",v),w.disconnect()}}},[r,a,h.paused]),c.useEffect(()=>{if(a){Bt.add(h);const p=document.activeElement;if(!a.contains(p)){const y=new CustomEvent(Ge,Wt);a.addEventListener(Ge,u),a.dispatchEvent(y),y.defaultPrevented||(qr(to(pn(a)),{select:!0}),document.activeElement===p&&Q(a))}return()=>{a.removeEventListener(Ge,u),setTimeout(()=>{const y=new CustomEvent(qe,Wt);a.addEventListener(qe,f),a.dispatchEvent(y),y.defaultPrevented||Q(p??document.body,{select:!0}),a.removeEventListener(qe,f),Bt.remove(h)},0)}}},[a,u,f,h]);const g=c.useCallback(p=>{if(!n&&!r||h.paused)return;const v=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,y=document.activeElement;if(v&&y){const w=p.currentTarget,[b,x]=Zr(w);b&&x?!p.shiftKey&&y===x?(p.preventDefault(),n&&Q(b,{select:!0})):p.shiftKey&&y===b&&(p.preventDefault(),n&&Q(x,{select:!0})):y===w&&p.preventDefault()}},[n,r,h.paused]);return C.jsx(B.div,{tabIndex:-1,...s,ref:m,onKeyDown:g})});dn.displayName=Gr;function qr(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Q(r,{select:t}),document.activeElement!==n)return}function Zr(e){const t=pn(e),n=$t(t,e),r=$t(t.reverse(),e);return[n,r]}function pn(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function $t(e,t){for(const n of e)if(!Qr(n,{upTo:t}))return n}function Qr(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Jr(e){return e instanceof HTMLInputElement&&"select"in e}function Q(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Jr(e)&&t&&e.select()}}var Bt=eo();function eo(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ht(e,t),e.unshift(t)},remove(t){var n;e=Ht(e,t),(n=e[0])==null||n.resume()}}}function Ht(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function to(e){return e.filter(t=>t.tagName!=="A")}var no=Er.useId||(()=>{}),ro=0;function hn(e){const[t,n]=c.useState(no());return oe(()=>{n(r=>r??String(ro++))},[e]),t?`radix-${t}`:""}const oo=["top","right","bottom","left"],ee=Math.min,j=Math.max,_e=Math.round,Re=Math.floor,Y=e=>({x:e,y:e}),io={left:"right",right:"left",bottom:"top",top:"bottom"},so={start:"end",end:"start"};function it(e,t,n){return j(e,ee(t,n))}function q(e,t){return typeof e=="function"?e(t):e}function Z(e){return e.split("-")[0]}function he(e){return e.split("-")[1]}function pt(e){return e==="x"?"y":"x"}function ht(e){return e==="y"?"height":"width"}function te(e){return["top","bottom"].includes(Z(e))?"y":"x"}function mt(e){return pt(te(e))}function ao(e,t,n){n===void 0&&(n=!1);const r=he(e),o=mt(e),i=ht(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=ke(s)),[s,ke(s)]}function co(e){const t=ke(e);return[st(e),t,st(t)]}function st(e){return e.replace(/start|end/g,t=>so[t])}function lo(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function uo(e,t,n,r){const o=he(e);let i=lo(Z(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(st)))),i}function ke(e){return e.replace(/left|right|bottom|top/g,t=>io[t])}function fo(e){return{top:0,right:0,bottom:0,left:0,...e}}function mn(e){return typeof e!="number"?fo(e):{top:e,right:e,bottom:e,left:e}}function Fe(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Vt(e,t,n){let{reference:r,floating:o}=e;const i=te(t),s=mt(t),a=ht(s),l=Z(t),u=i==="y",f=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,m=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:f,y:r.y-o.height};break;case"bottom":h={x:f,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:d};break;case"left":h={x:r.x-o.width,y:d};break;default:h={x:r.x,y:r.y}}switch(he(t)){case"start":h[s]-=m*(n&&u?-1:1);break;case"end":h[s]+=m*(n&&u?-1:1);break}return h}const po=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,a=i.filter(Boolean),l=await(s.isRTL==null?void 0:s.isRTL(t));let u=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:f,y:d}=Vt(u,r,l),m=r,h={},g=0;for(let p=0;p<a.length;p++){const{name:v,fn:y}=a[p],{x:w,y:b,data:x,reset:E}=await y({x:f,y:d,initialPlacement:r,placement:m,strategy:o,middlewareData:h,rects:u,platform:s,elements:{reference:e,floating:t}});f=w??f,d=b??d,h={...h,[v]:{...h[v],...x}},E&&g<=50&&(g++,typeof E=="object"&&(E.placement&&(m=E.placement),E.rects&&(u=E.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:o}):E.rects),{x:f,y:d}=Vt(u,m,l)),p=-1)}return{x:f,y:d,placement:m,strategy:o,middlewareData:h}};async function ge(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:s,elements:a,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:f="viewport",elementContext:d="floating",altBoundary:m=!1,padding:h=0}=q(t,e),g=mn(h),v=a[m?d==="floating"?"reference":"floating":d],y=Fe(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(v)))==null||n?v:v.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(a.floating)),boundary:u,rootBoundary:f,strategy:l})),w=d==="floating"?{x:r,y:o,width:s.floating.width,height:s.floating.height}:s.reference,b=await(i.getOffsetParent==null?void 0:i.getOffsetParent(a.floating)),x=await(i.isElement==null?void 0:i.isElement(b))?await(i.getScale==null?void 0:i.getScale(b))||{x:1,y:1}:{x:1,y:1},E=Fe(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:b,strategy:l}):w);return{top:(y.top-E.top+g.top)/x.y,bottom:(E.bottom-y.bottom+g.bottom)/x.y,left:(y.left-E.left+g.left)/x.x,right:(E.right-y.right+g.right)/x.x}}const ho=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:a,middlewareData:l}=t,{element:u,padding:f=0}=q(e,t)||{};if(u==null)return{};const d=mn(f),m={x:n,y:r},h=mt(o),g=ht(h),p=await s.getDimensions(u),v=h==="y",y=v?"top":"left",w=v?"bottom":"right",b=v?"clientHeight":"clientWidth",x=i.reference[g]+i.reference[h]-m[h]-i.floating[g],E=m[h]-i.reference[h],A=await(s.getOffsetParent==null?void 0:s.getOffsetParent(u));let P=A?A[b]:0;(!P||!await(s.isElement==null?void 0:s.isElement(A)))&&(P=a.floating[b]||i.floating[g]);const S=x/2-E/2,N=P/2-p[g]/2-1,O=ee(d[y],N),k=ee(d[w],N),F=O,M=P-p[g]-k,T=P/2-p[g]/2+S,$=it(F,T,M),L=!l.arrow&&he(o)!=null&&T!==$&&i.reference[g]/2-(T<F?O:k)-p[g]/2<0,D=L?T<F?T-F:T-M:0;return{[h]:m[h]+D,data:{[h]:$,centerOffset:T-$-D,...L&&{alignmentOffset:D}},reset:L}}}),mo=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:s,initialPlacement:a,platform:l,elements:u}=t,{mainAxis:f=!0,crossAxis:d=!0,fallbackPlacements:m,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:p=!0,...v}=q(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const y=Z(o),w=te(a),b=Z(a)===a,x=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=m||(b||!p?[ke(a)]:co(a)),A=g!=="none";!m&&A&&E.push(...uo(a,p,g,x));const P=[a,...E],S=await ge(t,v),N=[];let O=((r=i.flip)==null?void 0:r.overflows)||[];if(f&&N.push(S[y]),d){const T=ao(o,s,x);N.push(S[T[0]],S[T[1]])}if(O=[...O,{placement:o,overflows:N}],!N.every(T=>T<=0)){var k,F;const T=(((k=i.flip)==null?void 0:k.index)||0)+1,$=P[T];if($)return{data:{index:T,overflows:O},reset:{placement:$}};let L=(F=O.filter(D=>D.overflows[0]<=0).sort((D,R)=>D.overflows[1]-R.overflows[1])[0])==null?void 0:F.placement;if(!L)switch(h){case"bestFit":{var M;const D=(M=O.filter(R=>{if(A){const _=te(R.placement);return _===w||_==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(_=>_>0).reduce((_,U)=>_+U,0)]).sort((R,_)=>R[1]-_[1])[0])==null?void 0:M[0];D&&(L=D);break}case"initialPlacement":L=a;break}if(o!==L)return{reset:{placement:L}}}return{}}}};function Ut(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function zt(e){return oo.some(t=>e[t]>=0)}const vo=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=q(e,t);switch(r){case"referenceHidden":{const i=await ge(t,{...o,elementContext:"reference"}),s=Ut(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:zt(s)}}}case"escaped":{const i=await ge(t,{...o,altBoundary:!0}),s=Ut(i,n.floating);return{data:{escapedOffsets:s,escaped:zt(s)}}}default:return{}}}}};async function go(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=Z(n),a=he(n),l=te(n)==="y",u=["left","top"].includes(s)?-1:1,f=i&&l?-1:1,d=q(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*f,y:m*u}:{x:m*u,y:h*f}}const yo=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:s,middlewareData:a}=t,l=await go(t,e);return s===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:s}}}}},wo=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:a={fn:v=>{let{x:y,y:w}=v;return{x:y,y:w}}},...l}=q(e,t),u={x:n,y:r},f=await ge(t,l),d=te(Z(o)),m=pt(d);let h=u[m],g=u[d];if(i){const v=m==="y"?"top":"left",y=m==="y"?"bottom":"right",w=h+f[v],b=h-f[y];h=it(w,h,b)}if(s){const v=d==="y"?"top":"left",y=d==="y"?"bottom":"right",w=g+f[v],b=g-f[y];g=it(w,g,b)}const p=a.fn({...t,[m]:h,[d]:g});return{...p,data:{x:p.x-n,y:p.y-r,enabled:{[m]:i,[d]:s}}}}}},xo=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=q(e,t),f={x:n,y:r},d=te(o),m=pt(d);let h=f[m],g=f[d];const p=q(a,t),v=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:0,crossAxis:0,...p};if(l){const b=m==="y"?"height":"width",x=i.reference[m]-i.floating[b]+v.mainAxis,E=i.reference[m]+i.reference[b]-v.mainAxis;h<x?h=x:h>E&&(h=E)}if(u){var y,w;const b=m==="y"?"width":"height",x=["top","left"].includes(Z(o)),E=i.reference[d]-i.floating[b]+(x&&((y=s.offset)==null?void 0:y[d])||0)+(x?0:v.crossAxis),A=i.reference[d]+i.reference[b]+(x?0:((w=s.offset)==null?void 0:w[d])||0)-(x?v.crossAxis:0);g<E?g=E:g>A&&(g=A)}return{[m]:h,[d]:g}}}},bo=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:s,elements:a}=t,{apply:l=()=>{},...u}=q(e,t),f=await ge(t,u),d=Z(o),m=he(o),h=te(o)==="y",{width:g,height:p}=i.floating;let v,y;d==="top"||d==="bottom"?(v=d,y=m===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(y=d,v=m==="end"?"top":"bottom");const w=p-f.top-f.bottom,b=g-f.left-f.right,x=ee(p-f[v],w),E=ee(g-f[y],b),A=!t.middlewareData.shift;let P=x,S=E;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(S=b),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(P=w),A&&!m){const O=j(f.left,0),k=j(f.right,0),F=j(f.top,0),M=j(f.bottom,0);h?S=g-2*(O!==0||k!==0?O+k:j(f.left,f.right)):P=p-2*(F!==0||M!==0?F+M:j(f.top,f.bottom))}await l({...t,availableWidth:S,availableHeight:P});const N=await s.getDimensions(a.floating);return g!==N.width||p!==N.height?{reset:{rects:!0}}:{}}}};function $e(){return typeof window<"u"}function me(e){return vn(e)?(e.nodeName||"").toLowerCase():"#document"}function W(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function G(e){var t;return(t=(vn(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function vn(e){return $e()?e instanceof Node||e instanceof W(e).Node:!1}function H(e){return $e()?e instanceof Element||e instanceof W(e).Element:!1}function X(e){return $e()?e instanceof HTMLElement||e instanceof W(e).HTMLElement:!1}function Yt(e){return!$e()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof W(e).ShadowRoot}function xe(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=V(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function Eo(e){return["table","td","th"].includes(me(e))}function Be(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function vt(e){const t=gt(),n=H(e)?V(e):e;return["transform","translate","scale","rotate","perspective"].some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function Co(e){let t=ne(e);for(;X(t)&&!fe(t);){if(vt(t))return t;if(Be(t))return null;t=ne(t)}return null}function gt(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function fe(e){return["html","body","#document"].includes(me(e))}function V(e){return W(e).getComputedStyle(e)}function He(e){return H(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ne(e){if(me(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Yt(e)&&e.host||G(e);return Yt(t)?t.host:t}function gn(e){const t=ne(e);return fe(t)?e.ownerDocument?e.ownerDocument.body:e.body:X(t)&&xe(t)?t:gn(t)}function ye(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=gn(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=W(o);if(i){const a=at(s);return t.concat(s,s.visualViewport||[],xe(o)?o:[],a&&n?ye(a):[])}return t.concat(o,ye(o,[],n))}function at(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function yn(e){const t=V(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=X(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,a=_e(n)!==i||_e(r)!==s;return a&&(n=i,r=s),{width:n,height:r,$:a}}function yt(e){return H(e)?e:e.contextElement}function le(e){const t=yt(e);if(!X(t))return Y(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=yn(t);let s=(i?_e(n.width):n.width)/r,a=(i?_e(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}const Po=Y(0);function wn(e){const t=W(e);return!gt()||!t.visualViewport?Po:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ao(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==W(e)?!1:t}function ie(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=yt(e);let s=Y(1);t&&(r?H(r)&&(s=le(r)):s=le(e));const a=Ao(i,n,r)?wn(i):Y(0);let l=(o.left+a.x)/s.x,u=(o.top+a.y)/s.y,f=o.width/s.x,d=o.height/s.y;if(i){const m=W(i),h=r&&H(r)?W(r):r;let g=m,p=at(g);for(;p&&r&&h!==g;){const v=le(p),y=p.getBoundingClientRect(),w=V(p),b=y.left+(p.clientLeft+parseFloat(w.paddingLeft))*v.x,x=y.top+(p.clientTop+parseFloat(w.paddingTop))*v.y;l*=v.x,u*=v.y,f*=v.x,d*=v.y,l+=b,u+=x,g=W(p),p=at(g)}}return Fe({width:f,height:d,x:l,y:u})}function wt(e,t){const n=He(e).scrollLeft;return t?t.left+n:ie(G(e)).left+n}function xn(e,t,n){n===void 0&&(n=!1);const r=e.getBoundingClientRect(),o=r.left+t.scrollLeft-(n?0:wt(e,r)),i=r.top+t.scrollTop;return{x:o,y:i}}function Ro(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",s=G(r),a=t?Be(t.floating):!1;if(r===s||a&&i)return n;let l={scrollLeft:0,scrollTop:0},u=Y(1);const f=Y(0),d=X(r);if((d||!d&&!i)&&((me(r)!=="body"||xe(s))&&(l=He(r)),X(r))){const h=ie(r);u=le(r),f.x=h.x+r.clientLeft,f.y=h.y+r.clientTop}const m=s&&!d&&!i?xn(s,l,!0):Y(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+f.x+m.x,y:n.y*u.y-l.scrollTop*u.y+f.y+m.y}}function So(e){return Array.from(e.getClientRects())}function Oo(e){const t=G(e),n=He(e),r=e.ownerDocument.body,o=j(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=j(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+wt(e);const a=-n.scrollTop;return V(r).direction==="rtl"&&(s+=j(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:a}}function To(e,t){const n=W(e),r=G(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,a=0,l=0;if(o){i=o.width,s=o.height;const u=gt();(!u||u&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}return{width:i,height:s,x:a,y:l}}function No(e,t){const n=ie(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=X(e)?le(e):Y(1),s=e.clientWidth*i.x,a=e.clientHeight*i.y,l=o*i.x,u=r*i.y;return{width:s,height:a,x:l,y:u}}function Xt(e,t,n){let r;if(t==="viewport")r=To(e,n);else if(t==="document")r=Oo(G(e));else if(H(t))r=No(t,n);else{const o=wn(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Fe(r)}function bn(e,t){const n=ne(e);return n===t||!H(n)||fe(n)?!1:V(n).position==="fixed"||bn(n,t)}function Mo(e,t){const n=t.get(e);if(n)return n;let r=ye(e,[],!1).filter(a=>H(a)&&me(a)!=="body"),o=null;const i=V(e).position==="fixed";let s=i?ne(e):e;for(;H(s)&&!fe(s);){const a=V(s),l=vt(s);!l&&a.position==="fixed"&&(o=null),(i?!l&&!o:!l&&a.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||xe(s)&&!l&&bn(e,s))?r=r.filter(f=>f!==s):o=a,s=ne(s)}return t.set(e,r),r}function Lo(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?Be(t)?[]:Mo(t,this._c):[].concat(n),r],a=s[0],l=s.reduce((u,f)=>{const d=Xt(t,f,o);return u.top=j(d.top,u.top),u.right=ee(d.right,u.right),u.bottom=ee(d.bottom,u.bottom),u.left=j(d.left,u.left),u},Xt(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Do(e){const{width:t,height:n}=yn(e);return{width:t,height:n}}function _o(e,t,n){const r=X(t),o=G(t),i=n==="fixed",s=ie(e,!0,i,t);let a={scrollLeft:0,scrollTop:0};const l=Y(0);if(r||!r&&!i)if((me(t)!=="body"||xe(o))&&(a=He(t)),r){const m=ie(t,!0,i,t);l.x=m.x+t.clientLeft,l.y=m.y+t.clientTop}else o&&(l.x=wt(o));const u=o&&!r&&!i?xn(o,a):Y(0),f=s.left+a.scrollLeft-l.x-u.x,d=s.top+a.scrollTop-l.y-u.y;return{x:f,y:d,width:s.width,height:s.height}}function Ze(e){return V(e).position==="static"}function Kt(e,t){if(!X(e)||V(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return G(e)===n&&(n=n.ownerDocument.body),n}function En(e,t){const n=W(e);if(Be(e))return n;if(!X(e)){let o=ne(e);for(;o&&!fe(o);){if(H(o)&&!Ze(o))return o;o=ne(o)}return n}let r=Kt(e,t);for(;r&&Eo(r)&&Ze(r);)r=Kt(r,t);return r&&fe(r)&&Ze(r)&&!vt(r)?n:r||Co(e)||n}const ko=async function(e){const t=this.getOffsetParent||En,n=this.getDimensions,r=await n(e.floating);return{reference:_o(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Fo(e){return V(e).direction==="rtl"}const Io={convertOffsetParentRelativeRectToViewportRelativeRect:Ro,getDocumentElement:G,getClippingRect:Lo,getOffsetParent:En,getElementRects:ko,getClientRects:So,getDimensions:Do,getScale:le,isElement:H,isRTL:Fo};function Cn(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function jo(e,t){let n=null,r;const o=G(e);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:f,top:d,width:m,height:h}=u;if(a||t(),!m||!h)return;const g=Re(d),p=Re(o.clientWidth-(f+m)),v=Re(o.clientHeight-(d+h)),y=Re(f),b={rootMargin:-g+"px "+-p+"px "+-v+"px "+-y+"px",threshold:j(0,ee(1,l))||1};let x=!0;function E(A){const P=A[0].intersectionRatio;if(P!==l){if(!x)return s();P?s(!1,P):r=setTimeout(()=>{s(!1,1e-7)},1e3)}P===1&&!Cn(u,e.getBoundingClientRect())&&s(),x=!1}try{n=new IntersectionObserver(E,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(E,b)}n.observe(e)}return s(!0),i}function Wo(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=yt(e),f=o||i?[...u?ye(u):[],...ye(t)]:[];f.forEach(y=>{o&&y.addEventListener("scroll",n,{passive:!0}),i&&y.addEventListener("resize",n)});const d=u&&a?jo(u,n):null;let m=-1,h=null;s&&(h=new ResizeObserver(y=>{let[w]=y;w&&w.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,p=l?ie(e):null;l&&v();function v(){const y=ie(e);p&&!Cn(p,y)&&n(),p=y,g=requestAnimationFrame(v)}return n(),()=>{var y;f.forEach(w=>{o&&w.removeEventListener("scroll",n),i&&w.removeEventListener("resize",n)}),d==null||d(),(y=h)==null||y.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const $o=yo,Bo=wo,Ho=mo,Vo=bo,Uo=vo,Gt=ho,zo=xo,Yo=(e,t,n)=>{const r=new Map,o={platform:Io,...n},i={...o.platform,_c:r};return po(e,t,{...o,platform:i})};var Me=typeof document<"u"?c.useLayoutEffect:c.useEffect;function Ie(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ie(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ie(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Pn(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function qt(e,t){const n=Pn(e);return Math.round(t*n)/n}function Qe(e){const t=c.useRef(e);return Me(()=>{t.current=e}),t}function Xo(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[f,d]=c.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=c.useState(r);Ie(m,r)||h(r);const[g,p]=c.useState(null),[v,y]=c.useState(null),w=c.useCallback(R=>{R!==A.current&&(A.current=R,p(R))},[]),b=c.useCallback(R=>{R!==P.current&&(P.current=R,y(R))},[]),x=i||g,E=s||v,A=c.useRef(null),P=c.useRef(null),S=c.useRef(f),N=l!=null,O=Qe(l),k=Qe(o),F=Qe(u),M=c.useCallback(()=>{if(!A.current||!P.current)return;const R={placement:t,strategy:n,middleware:m};k.current&&(R.platform=k.current),Yo(A.current,P.current,R).then(_=>{const U={..._,isPositioned:F.current!==!1};T.current&&!Ie(S.current,U)&&(S.current=U,nn.flushSync(()=>{d(U)}))})},[m,t,n,k,F]);Me(()=>{u===!1&&S.current.isPositioned&&(S.current.isPositioned=!1,d(R=>({...R,isPositioned:!1})))},[u]);const T=c.useRef(!1);Me(()=>(T.current=!0,()=>{T.current=!1}),[]),Me(()=>{if(x&&(A.current=x),E&&(P.current=E),x&&E){if(O.current)return O.current(x,E,M);M()}},[x,E,M,O,N]);const $=c.useMemo(()=>({reference:A,floating:P,setReference:w,setFloating:b}),[w,b]),L=c.useMemo(()=>({reference:x,floating:E}),[x,E]),D=c.useMemo(()=>{const R={position:n,left:0,top:0};if(!L.floating)return R;const _=qt(L.floating,f.x),U=qt(L.floating,f.y);return a?{...R,transform:"translate("+_+"px, "+U+"px)",...Pn(L.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:_,top:U}},[n,a,L.floating,f.x,f.y]);return c.useMemo(()=>({...f,update:M,refs:$,elements:L,floatingStyles:D}),[f,M,$,L,D])}const Ko=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Gt({element:r.current,padding:o}).fn(n):{}:r?Gt({element:r,padding:o}).fn(n):{}}}},Go=(e,t)=>({...$o(e),options:[e,t]}),qo=(e,t)=>({...Bo(e),options:[e,t]}),Zo=(e,t)=>({...zo(e),options:[e,t]}),Qo=(e,t)=>({...Ho(e),options:[e,t]}),Jo=(e,t)=>({...Vo(e),options:[e,t]}),ei=(e,t)=>({...Uo(e),options:[e,t]}),ti=(e,t)=>({...Ko(e),options:[e,t]});var ni="Arrow",An=c.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return C.jsx(B.svg,{...i,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:C.jsx("polygon",{points:"0,0 30,0 15,10"})})});An.displayName=ni;var ri=An,xt="Popper",[Rn,Ve]=dt(xt),[oi,Sn]=Rn(xt),On=e=>{const{__scopePopper:t,children:n}=e,[r,o]=c.useState(null);return C.jsx(oi,{scope:t,anchor:r,onAnchorChange:o,children:n})};On.displayName=xt;var Tn="PopperAnchor",Nn=c.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Sn(Tn,n),s=c.useRef(null),a=K(t,s);return c.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:C.jsx(B.div,{...o,ref:a})});Nn.displayName=Tn;var bt="PopperContent",[ii,si]=Rn(bt),Mn=c.forwardRef((e,t)=>{var Ot,Tt,Nt,Mt,Lt,Dt;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:f=0,sticky:d="partial",hideWhenDetached:m=!1,updatePositionStrategy:h="optimized",onPlaced:g,...p}=e,v=Sn(bt,n),[y,w]=c.useState(null),b=K(t,ve=>w(ve)),[x,E]=c.useState(null),A=kr(x),P=(A==null?void 0:A.width)??0,S=(A==null?void 0:A.height)??0,N=r+(i!=="center"?"-"+i:""),O=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},k=Array.isArray(u)?u:[u],F=k.length>0,M={padding:O,boundary:k.filter(ci),altBoundary:F},{refs:T,floatingStyles:$,placement:L,isPositioned:D,middlewareData:R}=Xo({strategy:"fixed",placement:N,whileElementsMounted:(...ve)=>Wo(...ve,{animationFrame:h==="always"}),elements:{reference:v.anchor},middleware:[Go({mainAxis:o+S,alignmentAxis:s}),l&&qo({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?Zo():void 0,...M}),l&&Qo({...M}),Jo({...M,apply:({elements:ve,rects:_t,availableWidth:yr,availableHeight:wr})=>{const{width:xr,height:br}=_t.reference,Pe=ve.floating.style;Pe.setProperty("--radix-popper-available-width",`${yr}px`),Pe.setProperty("--radix-popper-available-height",`${wr}px`),Pe.setProperty("--radix-popper-anchor-width",`${xr}px`),Pe.setProperty("--radix-popper-anchor-height",`${br}px`)}}),x&&ti({element:x,padding:a}),li({arrowWidth:P,arrowHeight:S}),m&&ei({strategy:"referenceHidden",...M})]}),[_,U]=_n(L),Ce=J(g);oe(()=>{D&&(Ce==null||Ce())},[D,Ce]);const pr=(Ot=R.arrow)==null?void 0:Ot.x,hr=(Tt=R.arrow)==null?void 0:Tt.y,mr=((Nt=R.arrow)==null?void 0:Nt.centerOffset)!==0,[vr,gr]=c.useState();return oe(()=>{y&&gr(window.getComputedStyle(y).zIndex)},[y]),C.jsx("div",{ref:T.setFloating,"data-radix-popper-content-wrapper":"",style:{...$,transform:D?$.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:vr,"--radix-popper-transform-origin":[(Mt=R.transformOrigin)==null?void 0:Mt.x,(Lt=R.transformOrigin)==null?void 0:Lt.y].join(" "),...((Dt=R.hide)==null?void 0:Dt.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:C.jsx(ii,{scope:n,placedSide:_,onArrowChange:E,arrowX:pr,arrowY:hr,shouldHideArrow:mr,children:C.jsx(B.div,{"data-side":_,"data-align":U,...p,ref:b,style:{...p.style,animation:D?void 0:"none"}})})})});Mn.displayName=bt;var Ln="PopperArrow",ai={top:"bottom",right:"left",bottom:"top",left:"right"},Dn=c.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=si(Ln,r),s=ai[i.placedSide];return C.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:C.jsx(ri,{...o,ref:n,style:{...o.style,display:"block"}})})});Dn.displayName=Ln;function ci(e){return e!==null}var li=e=>({name:"transformOrigin",options:e,fn(t){var v,y,w;const{placement:n,rects:r,middlewareData:o}=t,s=((v=o.arrow)==null?void 0:v.centerOffset)!==0,a=s?0:e.arrowWidth,l=s?0:e.arrowHeight,[u,f]=_n(n),d={start:"0%",center:"50%",end:"100%"}[f],m=(((y=o.arrow)==null?void 0:y.x)??0)+a/2,h=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let g="",p="";return u==="bottom"?(g=s?d:`${m}px`,p=`${-l}px`):u==="top"?(g=s?d:`${m}px`,p=`${r.floating.height+l}px`):u==="right"?(g=`${-l}px`,p=s?d:`${h}px`):u==="left"&&(g=`${r.floating.width+l}px`,p=s?d:`${h}px`),{data:{x:g,y:p}}}});function _n(e){const[t,n="center"]=e.split("-");return[t,n]}var kn=On,Et=Nn,Fn=Mn,In=Dn,ui="Portal",Ct=c.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,i]=c.useState(!1);oe(()=>i(!0),[]);const s=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return s?Cr.createPortal(C.jsx(B.div,{...r,ref:t}),s):null});Ct.displayName=ui;var fi=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},se=new WeakMap,Se=new WeakMap,Oe={},Je=0,jn=function(e){return e&&(e.host||jn(e.parentNode))},di=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=jn(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},pi=function(e,t,n,r){var o=di(t,Array.isArray(e)?e:[e]);Oe[n]||(Oe[n]=new WeakMap);var i=Oe[n],s=[],a=new Set,l=new Set(o),u=function(d){!d||a.has(d)||(a.add(d),u(d.parentNode))};o.forEach(u);var f=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(m){if(a.has(m))f(m);else try{var h=m.getAttribute(r),g=h!==null&&h!=="false",p=(se.get(m)||0)+1,v=(i.get(m)||0)+1;se.set(m,p),i.set(m,v),s.push(m),p===1&&g&&Se.set(m,!0),v===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",m,y)}})};return f(t),a.clear(),Je++,function(){s.forEach(function(d){var m=se.get(d)-1,h=i.get(d)-1;se.set(d,m),i.set(d,h),m||(Se.has(d)||d.removeAttribute(r),Se.delete(d)),h||d.removeAttribute(n)}),Je--,Je||(se=new WeakMap,se=new WeakMap,Se=new WeakMap,Oe={})}},hi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=fi(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),pi(r,o,n,"aria-hidden")):function(){return null}},z=function(){return z=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},z.apply(this,arguments)};function Wn(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function mi(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var Le="right-scroll-bar-position",De="width-before-scroll-bar",vi="with-scroll-bars-hidden",gi="--removed-body-scroll-bar-size";function et(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function yi(e,t){var n=c.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var wi=typeof window<"u"?c.useLayoutEffect:c.useEffect,Zt=new WeakMap;function xi(e,t){var n=yi(null,function(r){return e.forEach(function(o){return et(o,r)})});return wi(function(){var r=Zt.get(n);if(r){var o=new Set(r),i=new Set(e),s=n.current;o.forEach(function(a){i.has(a)||et(a,null)}),i.forEach(function(a){o.has(a)||et(a,s)})}Zt.set(n,e)},[e]),n}function bi(e){return e}function Ei(e,t){t===void 0&&(t=bi);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var s=t(i,r);return n.push(s),function(){n=n.filter(function(a){return a!==s})}},assignSyncMedium:function(i){for(r=!0;n.length;){var s=n;n=[],s.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var s=[];if(n.length){var a=n;n=[],a.forEach(i),s=n}var l=function(){var f=s;s=[],f.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(f){s.push(f),u()},filter:function(f){return s=s.filter(f),n}}}};return o}function Ci(e){e===void 0&&(e={});var t=Ei(null);return t.options=z({async:!0,ssr:!1},e),t}var $n=function(e){var t=e.sideCar,n=Wn(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return c.createElement(r,z({},n))};$n.isSideCarExport=!0;function Pi(e,t){return e.useMedium(t),$n}var Bn=Ci(),tt=function(){},Ue=c.forwardRef(function(e,t){var n=c.useRef(null),r=c.useState({onScrollCapture:tt,onWheelCapture:tt,onTouchMoveCapture:tt}),o=r[0],i=r[1],s=e.forwardProps,a=e.children,l=e.className,u=e.removeScrollBar,f=e.enabled,d=e.shards,m=e.sideCar,h=e.noIsolation,g=e.inert,p=e.allowPinchZoom,v=e.as,y=v===void 0?"div":v,w=e.gapMode,b=Wn(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),x=m,E=xi([n,t]),A=z(z({},b),o);return c.createElement(c.Fragment,null,f&&c.createElement(x,{sideCar:Bn,removeScrollBar:u,shards:d,noIsolation:h,inert:g,setCallbacks:i,allowPinchZoom:!!p,lockRef:n,gapMode:w}),s?c.cloneElement(c.Children.only(a),z(z({},A),{ref:E})):c.createElement(y,z({},A,{className:l,ref:E}),a))});Ue.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ue.classNames={fullWidth:De,zeroRight:Le};var Ai=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Ri(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ai();return t&&e.setAttribute("nonce",t),e}function Si(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Oi(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Ti=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Ri())&&(Si(t,n),Oi(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ni=function(){var e=Ti();return function(t,n){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Hn=function(){var e=Ni(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Mi={left:0,top:0,right:0,gap:0},nt=function(e){return parseInt(e||"",10)||0},Li=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[nt(n),nt(r),nt(o)]},Di=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Mi;var t=Li(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},_i=Hn(),ue="data-scroll-locked",ki=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,a=e.gap;return n===void 0&&(n="margin"),` + .`.concat(vi,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(a,"px ").concat(r,`; + } + body[`).concat(ue,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(o,`px; + padding-top: `).concat(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(a,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Le,` { + right: `).concat(a,"px ").concat(r,`; + } + + .`).concat(De,` { + margin-right: `).concat(a,"px ").concat(r,`; + } + + .`).concat(Le," .").concat(Le,` { + right: 0 `).concat(r,`; + } + + .`).concat(De," .").concat(De,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(ue,`] { + `).concat(gi,": ").concat(a,`px; + } +`)},Qt=function(){var e=parseInt(document.body.getAttribute(ue)||"0",10);return isFinite(e)?e:0},Fi=function(){c.useEffect(function(){return document.body.setAttribute(ue,(Qt()+1).toString()),function(){var e=Qt()-1;e<=0?document.body.removeAttribute(ue):document.body.setAttribute(ue,e.toString())}},[])},Ii=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Fi();var i=c.useMemo(function(){return Di(o)},[o]);return c.createElement(_i,{styles:ki(i,!t,o,n?"":"!important")})},ct=!1;if(typeof window<"u")try{var Te=Object.defineProperty({},"passive",{get:function(){return ct=!0,!0}});window.addEventListener("test",Te,Te),window.removeEventListener("test",Te,Te)}catch{ct=!1}var ae=ct?{passive:!1}:!1,ji=function(e){return e.tagName==="TEXTAREA"},Vn=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!ji(e)&&n[t]==="visible")},Wi=function(e){return Vn(e,"overflowY")},$i=function(e){return Vn(e,"overflowX")},Jt=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=Un(e,r);if(o){var i=zn(e,r),s=i[1],a=i[2];if(s>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Bi=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Hi=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},Un=function(e,t){return e==="v"?Wi(t):$i(t)},zn=function(e,t){return e==="v"?Bi(t):Hi(t)},Vi=function(e,t){return e==="h"&&t==="rtl"?-1:1},Ui=function(e,t,n,r,o){var i=Vi(e,window.getComputedStyle(t).direction),s=i*r,a=n.target,l=t.contains(a),u=!1,f=s>0,d=0,m=0;do{var h=zn(e,a),g=h[0],p=h[1],v=h[2],y=p-v-i*g;(g||y)&&Un(e,a)&&(d+=y,m+=g),a instanceof ShadowRoot?a=a.host:a=a.parentNode}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(f&&Math.abs(d)<1||!f&&Math.abs(m)<1)&&(u=!0),u},Ne=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},en=function(e){return[e.deltaX,e.deltaY]},tn=function(e){return e&&"current"in e?e.current:e},zi=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Yi=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},Xi=0,ce=[];function Ki(e){var t=c.useRef([]),n=c.useRef([0,0]),r=c.useRef(),o=c.useState(Xi++)[0],i=c.useState(Hn)[0],s=c.useRef(e);c.useEffect(function(){s.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var p=mi([e.lockRef.current],(e.shards||[]).map(tn),!0).filter(Boolean);return p.forEach(function(v){return v.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),p.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=c.useCallback(function(p,v){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!s.current.allowPinchZoom;var y=Ne(p),w=n.current,b="deltaX"in p?p.deltaX:w[0]-y[0],x="deltaY"in p?p.deltaY:w[1]-y[1],E,A=p.target,P=Math.abs(b)>Math.abs(x)?"h":"v";if("touches"in p&&P==="h"&&A.type==="range")return!1;var S=Jt(P,A);if(!S)return!0;if(S?E=P:(E=P==="v"?"h":"v",S=Jt(P,A)),!S)return!1;if(!r.current&&"changedTouches"in p&&(b||x)&&(r.current=E),!E)return!0;var N=r.current||E;return Ui(N,v,p,N==="h"?b:x)},[]),l=c.useCallback(function(p){var v=p;if(!(!ce.length||ce[ce.length-1]!==i)){var y="deltaY"in v?en(v):Ne(v),w=t.current.filter(function(E){return E.name===v.type&&(E.target===v.target||v.target===E.shadowParent)&&zi(E.delta,y)})[0];if(w&&w.should){v.cancelable&&v.preventDefault();return}if(!w){var b=(s.current.shards||[]).map(tn).filter(Boolean).filter(function(E){return E.contains(v.target)}),x=b.length>0?a(v,b[0]):!s.current.noIsolation;x&&v.cancelable&&v.preventDefault()}}},[]),u=c.useCallback(function(p,v,y,w){var b={name:p,delta:v,target:y,should:w,shadowParent:Gi(y)};t.current.push(b),setTimeout(function(){t.current=t.current.filter(function(x){return x!==b})},1)},[]),f=c.useCallback(function(p){n.current=Ne(p),r.current=void 0},[]),d=c.useCallback(function(p){u(p.type,en(p),p.target,a(p,e.lockRef.current))},[]),m=c.useCallback(function(p){u(p.type,Ne(p),p.target,a(p,e.lockRef.current))},[]);c.useEffect(function(){return ce.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:m}),document.addEventListener("wheel",l,ae),document.addEventListener("touchmove",l,ae),document.addEventListener("touchstart",f,ae),function(){ce=ce.filter(function(p){return p!==i}),document.removeEventListener("wheel",l,ae),document.removeEventListener("touchmove",l,ae),document.removeEventListener("touchstart",f,ae)}},[]);var h=e.removeScrollBar,g=e.inert;return c.createElement(c.Fragment,null,g?c.createElement(i,{styles:Yi(o)}):null,h?c.createElement(Ii,{gapMode:e.gapMode}):null)}function Gi(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const qi=Pi(Bn,Ki);var Yn=c.forwardRef(function(e,t){return c.createElement(Ue,z({},e,{ref:t,sideCar:qi}))});Yn.classNames=Ue.classNames;var Pt="Popover",[Xn,Os]=dt(Pt,[Ve]),be=Ve(),[Zi,re]=Xn(Pt),Kn=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,a=be(t),l=c.useRef(null),[u,f]=c.useState(!1),[d=!1,m]=cn({prop:r,defaultProp:o,onChange:i});return C.jsx(kn,{...a,children:C.jsx(Zi,{scope:t,contentId:hn(),triggerRef:l,open:d,onOpenChange:m,onOpenToggle:c.useCallback(()=>m(h=>!h),[m]),hasCustomAnchor:u,onCustomAnchorAdd:c.useCallback(()=>f(!0),[]),onCustomAnchorRemove:c.useCallback(()=>f(!1),[]),modal:s,children:n})})};Kn.displayName=Pt;var Gn="PopoverAnchor",Qi=c.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=re(Gn,n),i=be(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=o;return c.useEffect(()=>(s(),()=>a()),[s,a]),C.jsx(Et,{...i,...r,ref:t})});Qi.displayName=Gn;var qn="PopoverTrigger",Zn=c.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=re(qn,n),i=be(n),s=K(t,o.triggerRef),a=C.jsx(B.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":nr(o.open),...r,ref:s,onClick:I(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:C.jsx(Et,{asChild:!0,...i,children:a})});Zn.displayName=qn;var At="PopoverPortal",[Ji,es]=Xn(At,{forceMount:void 0}),Qn=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=re(At,t);return C.jsx(Ji,{scope:t,forceMount:n,children:C.jsx(we,{present:n||i.open,children:C.jsx(Ct,{asChild:!0,container:o,children:r})})})};Qn.displayName=At;var de="PopoverContent",Jn=c.forwardRef((e,t)=>{const n=es(de,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=re(de,e.__scopePopover);return C.jsx(we,{present:r||i.open,children:i.modal?C.jsx(ts,{...o,ref:t}):C.jsx(ns,{...o,ref:t})})});Jn.displayName=de;var ts=c.forwardRef((e,t)=>{const n=re(de,e.__scopePopover),r=c.useRef(null),o=K(t,r),i=c.useRef(!1);return c.useEffect(()=>{const s=r.current;if(s)return hi(s)},[]),C.jsx(Yn,{as:ft,allowPinchZoom:!0,children:C.jsx(er,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:I(e.onCloseAutoFocus,s=>{var a;s.preventDefault(),i.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:I(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:I(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),ns=c.forwardRef((e,t)=>{const n=re(de,e.__scopePopover),r=c.useRef(!1),o=c.useRef(!1);return C.jsx(er,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s,a;(s=e.onCloseAutoFocus)==null||s.call(e,i),i.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const s=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(s))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),er=c.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,...d}=e,m=re(de,n),h=be(n);return Kr(),C.jsx(dn,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:C.jsx(We,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:f,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>m.onOpenChange(!1),children:C.jsx(Fn,{"data-state":nr(m.open),role:"dialog",id:m.contentId,...h,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),tr="PopoverClose",rs=c.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=re(tr,n);return C.jsx(B.button,{type:"button",...r,ref:t,onClick:I(e.onClick,()=>o.onOpenChange(!1))})});rs.displayName=tr;var os="PopoverArrow",is=c.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=be(n);return C.jsx(In,{...o,...r,ref:t})});is.displayName=os;function nr(e){return e?"open":"closed"}var Ts=Kn,Ns=Zn,Ms=Qn,Ls=Jn,ss="VisuallyHidden",rr=c.forwardRef((e,t)=>C.jsx(B.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));rr.displayName=ss;var as=rr,[ze,Ds]=dt("Tooltip",[Ve]),Ye=Ve(),or="TooltipProvider",cs=700,lt="tooltip.open",[ls,Rt]=ze(or),ir=e=>{const{__scopeTooltip:t,delayDuration:n=cs,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,a]=c.useState(!0),l=c.useRef(!1),u=c.useRef(0);return c.useEffect(()=>{const f=u.current;return()=>window.clearTimeout(f)},[]),C.jsx(ls,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:c.useCallback(()=>{window.clearTimeout(u.current),a(!1)},[]),onClose:c.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>a(!0),r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:c.useCallback(f=>{l.current=f},[]),disableHoverableContent:o,children:i})};ir.displayName=or;var Xe="Tooltip",[us,Ee]=ze(Xe),sr=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:a}=e,l=Rt(Xe,e.__scopeTooltip),u=Ye(t),[f,d]=c.useState(null),m=hn(),h=c.useRef(0),g=s??l.disableHoverableContent,p=a??l.delayDuration,v=c.useRef(!1),[y=!1,w]=cn({prop:r,defaultProp:o,onChange:P=>{P?(l.onOpen(),document.dispatchEvent(new CustomEvent(lt))):l.onClose(),i==null||i(P)}}),b=c.useMemo(()=>y?v.current?"delayed-open":"instant-open":"closed",[y]),x=c.useCallback(()=>{window.clearTimeout(h.current),h.current=0,v.current=!1,w(!0)},[w]),E=c.useCallback(()=>{window.clearTimeout(h.current),h.current=0,w(!1)},[w]),A=c.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{v.current=!0,w(!0),h.current=0},p)},[p,w]);return c.useEffect(()=>()=>{h.current&&(window.clearTimeout(h.current),h.current=0)},[]),C.jsx(kn,{...u,children:C.jsx(us,{scope:t,contentId:m,open:y,stateAttribute:b,trigger:f,onTriggerChange:d,onTriggerEnter:c.useCallback(()=>{l.isOpenDelayed?A():x()},[l.isOpenDelayed,A,x]),onTriggerLeave:c.useCallback(()=>{g?E():(window.clearTimeout(h.current),h.current=0)},[E,g]),onOpen:x,onClose:E,disableHoverableContent:g,children:n})})};sr.displayName=Xe;var ut="TooltipTrigger",ar=c.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ee(ut,n),i=Rt(ut,n),s=Ye(n),a=c.useRef(null),l=K(t,a,o.onTriggerChange),u=c.useRef(!1),f=c.useRef(!1),d=c.useCallback(()=>u.current=!1,[]);return c.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),C.jsx(Et,{asChild:!0,...s,children:C.jsx(B.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:I(e.onPointerMove,m=>{m.pointerType!=="touch"&&!f.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),f.current=!0)}),onPointerLeave:I(e.onPointerLeave,()=>{o.onTriggerLeave(),f.current=!1}),onPointerDown:I(e.onPointerDown,()=>{u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:I(e.onFocus,()=>{u.current||o.onOpen()}),onBlur:I(e.onBlur,o.onClose),onClick:I(e.onClick,o.onClose)})})});ar.displayName=ut;var St="TooltipPortal",[fs,ds]=ze(St,{forceMount:void 0}),cr=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Ee(St,t);return C.jsx(fs,{scope:t,forceMount:n,children:C.jsx(we,{present:n||i.open,children:C.jsx(Ct,{asChild:!0,container:o,children:r})})})};cr.displayName=St;var pe="TooltipContent",lr=c.forwardRef((e,t)=>{const n=ds(pe,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Ee(pe,e.__scopeTooltip);return C.jsx(we,{present:r||s.open,children:s.disableHoverableContent?C.jsx(ur,{side:o,...i,ref:t}):C.jsx(ps,{side:o,...i,ref:t})})}),ps=c.forwardRef((e,t)=>{const n=Ee(pe,e.__scopeTooltip),r=Rt(pe,e.__scopeTooltip),o=c.useRef(null),i=K(t,o),[s,a]=c.useState(null),{trigger:l,onClose:u}=n,f=o.current,{onPointerInTransitChange:d}=r,m=c.useCallback(()=>{a(null),d(!1)},[d]),h=c.useCallback((g,p)=>{const v=g.currentTarget,y={x:g.clientX,y:g.clientY},w=gs(y,v.getBoundingClientRect()),b=ys(y,w),x=ws(p.getBoundingClientRect()),E=bs([...b,...x]);a(E),d(!0)},[d]);return c.useEffect(()=>()=>m(),[m]),c.useEffect(()=>{if(l&&f){const g=v=>h(v,f),p=v=>h(v,l);return l.addEventListener("pointerleave",g),f.addEventListener("pointerleave",p),()=>{l.removeEventListener("pointerleave",g),f.removeEventListener("pointerleave",p)}}},[l,f,h,m]),c.useEffect(()=>{if(s){const g=p=>{const v=p.target,y={x:p.clientX,y:p.clientY},w=(l==null?void 0:l.contains(v))||(f==null?void 0:f.contains(v)),b=!xs(y,s);w?m():b&&(m(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,f,s,u,m]),C.jsx(ur,{...e,ref:i})}),[hs,ms]=ze(Xe,{isInside:!1}),ur=c.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...a}=e,l=Ee(pe,n),u=Ye(n),{onClose:f}=l;return c.useEffect(()=>(document.addEventListener(lt,f),()=>document.removeEventListener(lt,f)),[f]),c.useEffect(()=>{if(l.trigger){const d=m=>{const h=m.target;h!=null&&h.contains(l.trigger)&&f()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,f]),C.jsx(We,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:f,children:C.jsxs(Fn,{"data-state":l.stateAttribute,...u,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[C.jsx(an,{children:r}),C.jsx(hs,{scope:n,isInside:!0,children:C.jsx(as,{id:l.contentId,role:"tooltip",children:o||r})})]})})});lr.displayName=pe;var fr="TooltipArrow",vs=c.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ye(n);return ms(fr,n).isInside?null:C.jsx(In,{...o,...r,ref:t})});vs.displayName=fr;function gs(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function ys(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function ws(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function xs(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const a=t[i].x,l=t[i].y,u=t[s].x,f=t[s].y;l>r!=f>r&&n<(u-a)*(r-l)/(f-l)+a&&(o=!o)}return o}function bs(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Es(t)}function Es(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const o=e[r];for(;t.length>=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var _s=ir,ks=sr,Fs=ar,Is=cr,js=lr,Cs="Label",dr=c.forwardRef((e,t)=>C.jsx(B.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dr.displayName=Cs;var Ws=dr;export{Et as A,Ms as B,Fn as C,We as D,Ls as E,dn as F,Ts as G,Is as H,js as I,_s as J,ks as K,Fs as L,Ws as M,Ss as N,Rs as O,B as P,Yn as R,ft as S,Ns as T,rr as V,cn as a,J as b,dt as c,I as d,hn as e,Ve as f,we as g,hi as h,Kr as i,C as j,In as k,sn as l,$r as m,Ct as n,kn as o,oe as p,kr as q,As as r,V as s,Xo as t,K as u,H as v,Wo as w,Qo as x,Go as y,ti as z}; diff --git a/pkg/ui/frontend/dist/assets/radix-inputs-D4_OLmm6.js b/pkg/ui/frontend/dist/assets/radix-inputs-D4_OLmm6.js new file mode 100644 index 0000000000000..39b4651f1a911 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/radix-inputs-D4_OLmm6.js @@ -0,0 +1 @@ +import{r as a,c as Le,b as V}from"./react-core-D_V7s-9r.js";import{c as fe,u as A,a as ee,j as d,P as _,d as E,g as kt,q as Ve,f as Be,A as Nt,p as q,h as Mt,i as jt,R as At,S as Ot,F as Dt,D as Lt,C as Vt,e as Ee,k as Bt,V as Ht,b as Gt,n as Ft,o as Wt}from"./radix-core-ByqQ8fsu.js";import{c as Kt,a as Oe,u as He,b as Ge,R as Ut,I as $t}from"./radix-navigation-DYoR-lWZ.js";function _e(t){const s=a.useRef({value:t,previous:t});return a.useMemo(()=>(s.current.value!==t&&(s.current.previous=s.current.value,s.current.value=t),s.current.previous),[t])}var ke="Checkbox",[zt,_o]=fe(ke),[qt,Xt]=zt(ke),Fe=a.forwardRef((t,s)=>{const{__scopeCheckbox:e,name:c,checked:r,defaultChecked:i,required:n,disabled:o,value:l="on",onCheckedChange:u,form:h,...v}=t,[S,y]=a.useState(null),w=A(s,b=>y(b)),p=a.useRef(!1),x=S?h||!!S.closest("form"):!0,[C=!1,f]=ee({prop:r,defaultProp:i,onChange:u}),m=a.useRef(C);return a.useEffect(()=>{const b=S==null?void 0:S.form;if(b){const k=()=>f(m.current);return b.addEventListener("reset",k),()=>b.removeEventListener("reset",k)}},[S,f]),d.jsxs(qt,{scope:e,state:C,disabled:o,children:[d.jsx(_.button,{type:"button",role:"checkbox","aria-checked":z(C)?"mixed":C,"aria-required":n,"data-state":Ue(C),"data-disabled":o?"":void 0,disabled:o,value:l,...v,ref:w,onKeyDown:E(t.onKeyDown,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:E(t.onClick,b=>{f(k=>z(k)?!0:!k),x&&(p.current=b.isPropagationStopped(),p.current||b.stopPropagation())})}),x&&d.jsx(Yt,{control:S,bubbles:!p.current,name:c,value:l,checked:C,required:n,disabled:o,form:h,style:{transform:"translateX(-100%)"},defaultChecked:z(i)?!1:i})]})});Fe.displayName=ke;var We="CheckboxIndicator",Ke=a.forwardRef((t,s)=>{const{__scopeCheckbox:e,forceMount:c,...r}=t,i=Xt(We,e);return d.jsx(kt,{present:c||z(i.state)||i.state===!0,children:d.jsx(_.span,{"data-state":Ue(i.state),"data-disabled":i.disabled?"":void 0,...r,ref:s,style:{pointerEvents:"none",...t.style}})})});Ke.displayName=We;var Yt=t=>{const{control:s,checked:e,bubbles:c=!0,defaultChecked:r,...i}=t,n=a.useRef(null),o=_e(e),l=Ve(s);a.useEffect(()=>{const h=n.current,v=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(v,"checked").set;if(o!==e&&y){const w=new Event("click",{bubbles:c});h.indeterminate=z(e),y.call(h,z(e)?!1:e),h.dispatchEvent(w)}},[o,e,c]);const u=a.useRef(z(e)?!1:e);return d.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r??u.current,...i,tabIndex:-1,ref:n,style:{...t.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function z(t){return t==="indeterminate"}function Ue(t){return z(t)?"indeterminate":t?"checked":"unchecked"}var ko=Fe,No=Ke,Zt=[" ","Enter","ArrowUp","ArrowDown"],Jt=[" ","Enter"],le="Select",[he,me,Qt]=Kt(le),[ne,Mo]=fe(le,[Qt,Be]),ge=Be(),[eo,X]=ne(le),[to,oo]=ne(le),$e=t=>{const{__scopeSelect:s,children:e,open:c,defaultOpen:r,onOpenChange:i,value:n,defaultValue:o,onValueChange:l,dir:u,name:h,autoComplete:v,disabled:S,required:y,form:w}=t,p=ge(s),[x,C]=a.useState(null),[f,m]=a.useState(null),[b,k]=a.useState(!1),se=He(u),[N=!1,D]=ee({prop:c,defaultProp:r,onChange:i}),[K,Z]=ee({prop:n,defaultProp:o,onChange:l}),B=a.useRef(null),H=x?w||!!x.closest("form"):!0,[U,G]=a.useState(new Set),F=Array.from(U).map(M=>M.props.value).join(";");return d.jsx(Wt,{...p,children:d.jsxs(eo,{required:y,scope:s,trigger:x,onTriggerChange:C,valueNode:f,onValueNodeChange:m,valueNodeHasChildren:b,onValueNodeHasChildrenChange:k,contentId:Ee(),value:K,onValueChange:Z,open:N,onOpenChange:D,dir:se,triggerPointerDownPosRef:B,disabled:S,children:[d.jsx(he.Provider,{scope:s,children:d.jsx(to,{scope:t.__scopeSelect,onNativeOptionAdd:a.useCallback(M=>{G(L=>new Set(L).add(M))},[]),onNativeOptionRemove:a.useCallback(M=>{G(L=>{const W=new Set(L);return W.delete(M),W})},[]),children:e})}),H?d.jsxs(vt,{"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:v,value:K,onChange:M=>Z(M.target.value),disabled:S,form:w,children:[K===void 0?d.jsx("option",{value:""}):null,Array.from(U)]},F):null]})})};$e.displayName=le;var ze="SelectTrigger",qe=a.forwardRef((t,s)=>{const{__scopeSelect:e,disabled:c=!1,...r}=t,i=ge(e),n=X(ze,e),o=n.disabled||c,l=A(s,n.onTriggerChange),u=me(e),h=a.useRef("touch"),[v,S,y]=xt(p=>{const x=u().filter(m=>!m.disabled),C=x.find(m=>m.value===n.value),f=St(x,p,C);f!==void 0&&n.onValueChange(f.value)}),w=p=>{o||(n.onOpenChange(!0),y()),p&&(n.triggerPointerDownPosRef.current={x:Math.round(p.pageX),y:Math.round(p.pageY)})};return d.jsx(Nt,{asChild:!0,...i,children:d.jsx(_.button,{type:"button",role:"combobox","aria-controls":n.contentId,"aria-expanded":n.open,"aria-required":n.required,"aria-autocomplete":"none",dir:n.dir,"data-state":n.open?"open":"closed",disabled:o,"data-disabled":o?"":void 0,"data-placeholder":gt(n.value)?"":void 0,...r,ref:l,onClick:E(r.onClick,p=>{p.currentTarget.focus(),h.current!=="mouse"&&w(p)}),onPointerDown:E(r.onPointerDown,p=>{h.current=p.pointerType;const x=p.target;x.hasPointerCapture(p.pointerId)&&x.releasePointerCapture(p.pointerId),p.button===0&&p.ctrlKey===!1&&p.pointerType==="mouse"&&(w(p),p.preventDefault())}),onKeyDown:E(r.onKeyDown,p=>{const x=v.current!=="";!(p.ctrlKey||p.altKey||p.metaKey)&&p.key.length===1&&S(p.key),!(x&&p.key===" ")&&Zt.includes(p.key)&&(w(),p.preventDefault())})})})});qe.displayName=ze;var Xe="SelectValue",Ye=a.forwardRef((t,s)=>{const{__scopeSelect:e,className:c,style:r,children:i,placeholder:n="",...o}=t,l=X(Xe,e),{onValueNodeHasChildrenChange:u}=l,h=i!==void 0,v=A(s,l.onValueNodeChange);return q(()=>{u(h)},[u,h]),d.jsx(_.span,{...o,ref:v,style:{pointerEvents:"none"},children:gt(l.value)?d.jsx(d.Fragment,{children:n}):i})});Ye.displayName=Xe;var no="SelectIcon",Ze=a.forwardRef((t,s)=>{const{__scopeSelect:e,children:c,...r}=t;return d.jsx(_.span,{"aria-hidden":!0,...r,ref:s,children:c||"▼"})});Ze.displayName=no;var ro="SelectPortal",Je=t=>d.jsx(Ft,{asChild:!0,...t});Je.displayName=ro;var te="SelectContent",Qe=a.forwardRef((t,s)=>{const e=X(te,t.__scopeSelect),[c,r]=a.useState();if(q(()=>{r(new DocumentFragment)},[]),!e.open){const i=c;return i?Le.createPortal(d.jsx(et,{scope:t.__scopeSelect,children:d.jsx(he.Slot,{scope:t.__scopeSelect,children:d.jsx("div",{children:t.children})})}),i):null}return d.jsx(tt,{...t,ref:s})});Qe.displayName=te;var O=10,[et,Y]=ne(te),so="SelectContentImpl",tt=a.forwardRef((t,s)=>{const{__scopeSelect:e,position:c="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:i,onPointerDownOutside:n,side:o,sideOffset:l,align:u,alignOffset:h,arrowPadding:v,collisionBoundary:S,collisionPadding:y,sticky:w,hideWhenDetached:p,avoidCollisions:x,...C}=t,f=X(te,e),[m,b]=a.useState(null),[k,se]=a.useState(null),N=A(s,g=>b(g)),[D,K]=a.useState(null),[Z,B]=a.useState(null),H=me(e),[U,G]=a.useState(!1),F=a.useRef(!1);a.useEffect(()=>{if(m)return Mt(m)},[m]),jt();const M=a.useCallback(g=>{const[R,...j]=H().map(T=>T.ref.current),[I]=j.slice(-1),P=document.activeElement;for(const T of g)if(T===P||(T==null||T.scrollIntoView({block:"nearest"}),T===R&&k&&(k.scrollTop=0),T===I&&k&&(k.scrollTop=k.scrollHeight),T==null||T.focus(),document.activeElement!==P))return},[H,k]),L=a.useCallback(()=>M([D,m]),[M,D,m]);a.useEffect(()=>{U&&L()},[U,L]);const{onOpenChange:W,triggerPointerDownPosRef:$}=f;a.useEffect(()=>{if(m){let g={x:0,y:0};const R=I=>{var P,T;g={x:Math.abs(Math.round(I.pageX)-(((P=$.current)==null?void 0:P.x)??0)),y:Math.abs(Math.round(I.pageY)-(((T=$.current)==null?void 0:T.y)??0))}},j=I=>{g.x<=10&&g.y<=10?I.preventDefault():m.contains(I.target)||W(!1),document.removeEventListener("pointermove",R),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",R),document.addEventListener("pointerup",j,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",j,{capture:!0})}}},[m,W,$]),a.useEffect(()=>{const g=()=>W(!1);return window.addEventListener("blur",g),window.addEventListener("resize",g),()=>{window.removeEventListener("blur",g),window.removeEventListener("resize",g)}},[W]);const[ve,ie]=xt(g=>{const R=H().filter(P=>!P.disabled),j=R.find(P=>P.ref.current===document.activeElement),I=St(R,g,j);I&&setTimeout(()=>I.ref.current.focus())}),xe=a.useCallback((g,R,j)=>{const I=!F.current&&!j;(f.value!==void 0&&f.value===R||I)&&(K(g),I&&(F.current=!0))},[f.value]),Se=a.useCallback(()=>m==null?void 0:m.focus(),[m]),oe=a.useCallback((g,R,j)=>{const I=!F.current&&!j;(f.value!==void 0&&f.value===R||I)&&B(g)},[f.value]),de=c==="popper"?be:ot,ae=de===be?{side:o,sideOffset:l,align:u,alignOffset:h,arrowPadding:v,collisionBoundary:S,collisionPadding:y,sticky:w,hideWhenDetached:p,avoidCollisions:x}:{};return d.jsx(et,{scope:e,content:m,viewport:k,onViewportChange:se,itemRefCallback:xe,selectedItem:D,onItemLeave:Se,itemTextRefCallback:oe,focusSelectedItem:L,selectedItemText:Z,position:c,isPositioned:U,searchRef:ve,children:d.jsx(At,{as:Ot,allowPinchZoom:!0,children:d.jsx(Dt,{asChild:!0,trapped:f.open,onMountAutoFocus:g=>{g.preventDefault()},onUnmountAutoFocus:E(r,g=>{var R;(R=f.trigger)==null||R.focus({preventScroll:!0}),g.preventDefault()}),children:d.jsx(Lt,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:n,onFocusOutside:g=>g.preventDefault(),onDismiss:()=>f.onOpenChange(!1),children:d.jsx(de,{role:"listbox",id:f.contentId,"data-state":f.open?"open":"closed",dir:f.dir,onContextMenu:g=>g.preventDefault(),...C,...ae,onPlaced:()=>G(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...C.style},onKeyDown:E(C.onKeyDown,g=>{const R=g.ctrlKey||g.altKey||g.metaKey;if(g.key==="Tab"&&g.preventDefault(),!R&&g.key.length===1&&ie(g.key),["ArrowUp","ArrowDown","Home","End"].includes(g.key)){let I=H().filter(P=>!P.disabled).map(P=>P.ref.current);if(["ArrowUp","End"].includes(g.key)&&(I=I.slice().reverse()),["ArrowUp","ArrowDown"].includes(g.key)){const P=g.target,T=I.indexOf(P);I=I.slice(T+1)}setTimeout(()=>M(I)),g.preventDefault()}})})})})})})});tt.displayName=so;var ao="SelectItemAlignedPosition",ot=a.forwardRef((t,s)=>{const{__scopeSelect:e,onPlaced:c,...r}=t,i=X(te,e),n=Y(te,e),[o,l]=a.useState(null),[u,h]=a.useState(null),v=A(s,N=>h(N)),S=me(e),y=a.useRef(!1),w=a.useRef(!0),{viewport:p,selectedItem:x,selectedItemText:C,focusSelectedItem:f}=n,m=a.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&u&&p&&x&&C){const N=i.trigger.getBoundingClientRect(),D=u.getBoundingClientRect(),K=i.valueNode.getBoundingClientRect(),Z=C.getBoundingClientRect();if(i.dir!=="rtl"){const P=Z.left-D.left,T=K.left-P,J=N.left-T,Q=N.width+J,Ce=Math.max(Q,D.width),we=window.innerWidth-O,ye=Oe(T,[O,Math.max(O,we-Ce)]);o.style.minWidth=Q+"px",o.style.left=ye+"px"}else{const P=D.right-Z.right,T=window.innerWidth-K.right-P,J=window.innerWidth-N.right-T,Q=N.width+J,Ce=Math.max(Q,D.width),we=window.innerWidth-O,ye=Oe(T,[O,Math.max(O,we-Ce)]);o.style.minWidth=Q+"px",o.style.right=ye+"px"}const B=S(),H=window.innerHeight-O*2,U=p.scrollHeight,G=window.getComputedStyle(u),F=parseInt(G.borderTopWidth,10),M=parseInt(G.paddingTop,10),L=parseInt(G.borderBottomWidth,10),W=parseInt(G.paddingBottom,10),$=F+M+U+W+L,ve=Math.min(x.offsetHeight*5,$),ie=window.getComputedStyle(p),xe=parseInt(ie.paddingTop,10),Se=parseInt(ie.paddingBottom,10),oe=N.top+N.height/2-O,de=H-oe,ae=x.offsetHeight/2,g=x.offsetTop+ae,R=F+M+g,j=$-R;if(R<=oe){const P=B.length>0&&x===B[B.length-1].ref.current;o.style.bottom="0px";const T=u.clientHeight-p.offsetTop-p.offsetHeight,J=Math.max(de,ae+(P?Se:0)+T+L),Q=R+J;o.style.height=Q+"px"}else{const P=B.length>0&&x===B[0].ref.current;o.style.top="0px";const J=Math.max(oe,F+p.offsetTop+(P?xe:0)+ae)+j;o.style.height=J+"px",p.scrollTop=R-oe+p.offsetTop}o.style.margin=`${O}px 0`,o.style.minHeight=ve+"px",o.style.maxHeight=H+"px",c==null||c(),requestAnimationFrame(()=>y.current=!0)}},[S,i.trigger,i.valueNode,o,u,p,x,C,i.dir,c]);q(()=>m(),[m]);const[b,k]=a.useState();q(()=>{u&&k(window.getComputedStyle(u).zIndex)},[u]);const se=a.useCallback(N=>{N&&w.current===!0&&(m(),f==null||f(),w.current=!1)},[m,f]);return d.jsx(lo,{scope:e,contentWrapper:o,shouldExpandOnScrollRef:y,onScrollButtonChange:se,children:d.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:b},children:d.jsx(_.div,{...r,ref:v,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});ot.displayName=ao;var co="SelectPopperPosition",be=a.forwardRef((t,s)=>{const{__scopeSelect:e,align:c="start",collisionPadding:r=O,...i}=t,n=ge(e);return d.jsx(Vt,{...n,...i,ref:s,align:c,collisionPadding:r,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});be.displayName=co;var[lo,Ne]=ne(te,{}),Pe="SelectViewport",nt=a.forwardRef((t,s)=>{const{__scopeSelect:e,nonce:c,...r}=t,i=Y(Pe,e),n=Ne(Pe,e),o=A(s,i.onViewportChange),l=a.useRef(0);return d.jsxs(d.Fragment,{children:[d.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:c}),d.jsx(he.Slot,{scope:e,children:d.jsx(_.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:E(r.onScroll,u=>{const h=u.currentTarget,{contentWrapper:v,shouldExpandOnScrollRef:S}=n;if(S!=null&&S.current&&v){const y=Math.abs(l.current-h.scrollTop);if(y>0){const w=window.innerHeight-O*2,p=parseFloat(v.style.minHeight),x=parseFloat(v.style.height),C=Math.max(p,x);if(C<w){const f=C+y,m=Math.min(w,f),b=f-m;v.style.height=m+"px",v.style.bottom==="0px"&&(h.scrollTop=b>0?b:0,v.style.justifyContent="flex-end")}}}l.current=h.scrollTop})})})]})});nt.displayName=Pe;var rt="SelectGroup",[io,uo]=ne(rt),po=a.forwardRef((t,s)=>{const{__scopeSelect:e,...c}=t,r=Ee();return d.jsx(io,{scope:e,id:r,children:d.jsx(_.div,{role:"group","aria-labelledby":r,...c,ref:s})})});po.displayName=rt;var st="SelectLabel",at=a.forwardRef((t,s)=>{const{__scopeSelect:e,...c}=t,r=uo(st,e);return d.jsx(_.div,{id:r.id,...c,ref:s})});at.displayName=st;var ue="SelectItem",[fo,ct]=ne(ue),lt=a.forwardRef((t,s)=>{const{__scopeSelect:e,value:c,disabled:r=!1,textValue:i,...n}=t,o=X(ue,e),l=Y(ue,e),u=o.value===c,[h,v]=a.useState(i??""),[S,y]=a.useState(!1),w=A(s,f=>{var m;return(m=l.itemRefCallback)==null?void 0:m.call(l,f,c,r)}),p=Ee(),x=a.useRef("touch"),C=()=>{r||(o.onValueChange(c),o.onOpenChange(!1))};if(c==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.jsx(fo,{scope:e,value:c,disabled:r,textId:p,isSelected:u,onItemTextChange:a.useCallback(f=>{v(m=>m||((f==null?void 0:f.textContent)??"").trim())},[]),children:d.jsx(he.ItemSlot,{scope:e,value:c,disabled:r,textValue:h,children:d.jsx(_.div,{role:"option","aria-labelledby":p,"data-highlighted":S?"":void 0,"aria-selected":u&&S,"data-state":u?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...n,ref:w,onFocus:E(n.onFocus,()=>y(!0)),onBlur:E(n.onBlur,()=>y(!1)),onClick:E(n.onClick,()=>{x.current!=="mouse"&&C()}),onPointerUp:E(n.onPointerUp,()=>{x.current==="mouse"&&C()}),onPointerDown:E(n.onPointerDown,f=>{x.current=f.pointerType}),onPointerMove:E(n.onPointerMove,f=>{var m;x.current=f.pointerType,r?(m=l.onItemLeave)==null||m.call(l):x.current==="mouse"&&f.currentTarget.focus({preventScroll:!0})}),onPointerLeave:E(n.onPointerLeave,f=>{var m;f.currentTarget===document.activeElement&&((m=l.onItemLeave)==null||m.call(l))}),onKeyDown:E(n.onKeyDown,f=>{var b;((b=l.searchRef)==null?void 0:b.current)!==""&&f.key===" "||(Jt.includes(f.key)&&C(),f.key===" "&&f.preventDefault())})})})})});lt.displayName=ue;var ce="SelectItemText",it=a.forwardRef((t,s)=>{const{__scopeSelect:e,className:c,style:r,...i}=t,n=X(ce,e),o=Y(ce,e),l=ct(ce,e),u=oo(ce,e),[h,v]=a.useState(null),S=A(s,C=>v(C),l.onItemTextChange,C=>{var f;return(f=o.itemTextRefCallback)==null?void 0:f.call(o,C,l.value,l.disabled)}),y=h==null?void 0:h.textContent,w=a.useMemo(()=>d.jsx("option",{value:l.value,disabled:l.disabled,children:y},l.value),[l.disabled,l.value,y]),{onNativeOptionAdd:p,onNativeOptionRemove:x}=u;return q(()=>(p(w),()=>x(w)),[p,x,w]),d.jsxs(d.Fragment,{children:[d.jsx(_.span,{id:l.textId,...i,ref:S}),l.isSelected&&n.valueNode&&!n.valueNodeHasChildren?Le.createPortal(i.children,n.valueNode):null]})});it.displayName=ce;var dt="SelectItemIndicator",ut=a.forwardRef((t,s)=>{const{__scopeSelect:e,...c}=t;return ct(dt,e).isSelected?d.jsx(_.span,{"aria-hidden":!0,...c,ref:s}):null});ut.displayName=dt;var Te="SelectScrollUpButton",pt=a.forwardRef((t,s)=>{const e=Y(Te,t.__scopeSelect),c=Ne(Te,t.__scopeSelect),[r,i]=a.useState(!1),n=A(s,c.onScrollButtonChange);return q(()=>{if(e.viewport&&e.isPositioned){let o=function(){const u=l.scrollTop>0;i(u)};const l=e.viewport;return o(),l.addEventListener("scroll",o),()=>l.removeEventListener("scroll",o)}},[e.viewport,e.isPositioned]),r?d.jsx(ht,{...t,ref:n,onAutoScroll:()=>{const{viewport:o,selectedItem:l}=e;o&&l&&(o.scrollTop=o.scrollTop-l.offsetHeight)}}):null});pt.displayName=Te;var Ie="SelectScrollDownButton",ft=a.forwardRef((t,s)=>{const e=Y(Ie,t.__scopeSelect),c=Ne(Ie,t.__scopeSelect),[r,i]=a.useState(!1),n=A(s,c.onScrollButtonChange);return q(()=>{if(e.viewport&&e.isPositioned){let o=function(){const u=l.scrollHeight-l.clientHeight,h=Math.ceil(l.scrollTop)<u;i(h)};const l=e.viewport;return o(),l.addEventListener("scroll",o),()=>l.removeEventListener("scroll",o)}},[e.viewport,e.isPositioned]),r?d.jsx(ht,{...t,ref:n,onAutoScroll:()=>{const{viewport:o,selectedItem:l}=e;o&&l&&(o.scrollTop=o.scrollTop+l.offsetHeight)}}):null});ft.displayName=Ie;var ht=a.forwardRef((t,s)=>{const{__scopeSelect:e,onAutoScroll:c,...r}=t,i=Y("SelectScrollButton",e),n=a.useRef(null),o=me(e),l=a.useCallback(()=>{n.current!==null&&(window.clearInterval(n.current),n.current=null)},[]);return a.useEffect(()=>()=>l(),[l]),q(()=>{var h;const u=o().find(v=>v.ref.current===document.activeElement);(h=u==null?void 0:u.ref.current)==null||h.scrollIntoView({block:"nearest"})},[o]),d.jsx(_.div,{"aria-hidden":!0,...r,ref:s,style:{flexShrink:0,...r.style},onPointerDown:E(r.onPointerDown,()=>{n.current===null&&(n.current=window.setInterval(c,50))}),onPointerMove:E(r.onPointerMove,()=>{var u;(u=i.onItemLeave)==null||u.call(i),n.current===null&&(n.current=window.setInterval(c,50))}),onPointerLeave:E(r.onPointerLeave,()=>{l()})})}),ho="SelectSeparator",mt=a.forwardRef((t,s)=>{const{__scopeSelect:e,...c}=t;return d.jsx(_.div,{"aria-hidden":!0,...c,ref:s})});mt.displayName=ho;var Re="SelectArrow",mo=a.forwardRef((t,s)=>{const{__scopeSelect:e,...c}=t,r=ge(e),i=X(Re,e),n=Y(Re,e);return i.open&&n.position==="popper"?d.jsx(Bt,{...r,...c,ref:s}):null});mo.displayName=Re;function gt(t){return t===""||t===void 0}var vt=a.forwardRef((t,s)=>{const{value:e,...c}=t,r=a.useRef(null),i=A(s,r),n=_e(e);return a.useEffect(()=>{const o=r.current,l=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(l,"value").set;if(n!==e&&h){const v=new Event("change",{bubbles:!0});h.call(o,e),o.dispatchEvent(v)}},[n,e]),d.jsx(Ht,{asChild:!0,children:d.jsx("select",{...c,ref:i,defaultValue:e})})});vt.displayName="BubbleSelect";function xt(t){const s=Gt(t),e=a.useRef(""),c=a.useRef(0),r=a.useCallback(n=>{const o=e.current+n;s(o),function l(u){e.current=u,window.clearTimeout(c.current),u!==""&&(c.current=window.setTimeout(()=>l(""),1e3))}(o)},[s]),i=a.useCallback(()=>{e.current="",window.clearTimeout(c.current)},[]);return a.useEffect(()=>()=>window.clearTimeout(c.current),[]),[e,r,i]}function St(t,s,e){const r=s.length>1&&Array.from(s).every(u=>u===s[0])?s[0]:s,i=e?t.indexOf(e):-1;let n=go(t,Math.max(i,0));r.length===1&&(n=n.filter(u=>u!==e));const l=n.find(u=>u.textValue.toLowerCase().startsWith(r.toLowerCase()));return l!==e?l:void 0}function go(t,s){return t.map((e,c)=>t[(s+c)%t.length])}var jo=$e,Ao=qe,Oo=Ye,Do=Ze,Lo=Je,Vo=Qe,Bo=nt,Ho=at,Go=lt,Fo=it,Wo=ut,Ko=pt,Uo=ft,$o=mt,Me="Switch",[vo,zo]=fe(Me),[xo,So]=vo(Me),Ct=a.forwardRef((t,s)=>{const{__scopeSwitch:e,name:c,checked:r,defaultChecked:i,required:n,disabled:o,value:l="on",onCheckedChange:u,form:h,...v}=t,[S,y]=a.useState(null),w=A(s,m=>y(m)),p=a.useRef(!1),x=S?h||!!S.closest("form"):!0,[C=!1,f]=ee({prop:r,defaultProp:i,onChange:u});return d.jsxs(xo,{scope:e,checked:C,disabled:o,children:[d.jsx(_.button,{type:"button",role:"switch","aria-checked":C,"aria-required":n,"data-state":bt(C),"data-disabled":o?"":void 0,disabled:o,value:l,...v,ref:w,onClick:E(t.onClick,m=>{f(b=>!b),x&&(p.current=m.isPropagationStopped(),p.current||m.stopPropagation())})}),x&&d.jsx(Co,{control:S,bubbles:!p.current,name:c,value:l,checked:C,required:n,disabled:o,form:h,style:{transform:"translateX(-100%)"}})]})});Ct.displayName=Me;var wt="SwitchThumb",yt=a.forwardRef((t,s)=>{const{__scopeSwitch:e,...c}=t,r=So(wt,e);return d.jsx(_.span,{"data-state":bt(r.checked),"data-disabled":r.disabled?"":void 0,...c,ref:s})});yt.displayName=wt;var Co=t=>{const{control:s,checked:e,bubbles:c=!0,...r}=t,i=a.useRef(null),n=_e(e),o=Ve(s);return a.useEffect(()=>{const l=i.current,u=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(u,"checked").set;if(n!==e&&v){const S=new Event("click",{bubbles:c});v.call(l,e),l.dispatchEvent(S)}},[n,e,c]),d.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:e,...r,tabIndex:-1,ref:i,style:{...t.style,...o,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function bt(t){return t?"checked":"unchecked"}var qo=Ct,Xo=yt,wo="Toggle",je=a.forwardRef((t,s)=>{const{pressed:e,defaultPressed:c=!1,onPressedChange:r,...i}=t,[n=!1,o]=ee({prop:e,onChange:r,defaultProp:c});return d.jsx(_.button,{type:"button","aria-pressed":n,"data-state":n?"on":"off","data-disabled":t.disabled?"":void 0,...i,ref:s,onClick:E(t.onClick,()=>{t.disabled||o(!n)})})});je.displayName=wo;var Yo=je,re="ToggleGroup",[Pt,Zo]=fe(re,[Ge]),Tt=Ge(),Ae=V.forwardRef((t,s)=>{const{type:e,...c}=t;if(e==="single"){const r=c;return d.jsx(yo,{...r,ref:s})}if(e==="multiple"){const r=c;return d.jsx(bo,{...r,ref:s})}throw new Error(`Missing prop \`type\` expected on \`${re}\``)});Ae.displayName=re;var[It,Rt]=Pt(re),yo=V.forwardRef((t,s)=>{const{value:e,defaultValue:c,onValueChange:r=()=>{},...i}=t,[n,o]=ee({prop:e,defaultProp:c,onChange:r});return d.jsx(It,{scope:t.__scopeToggleGroup,type:"single",value:n?[n]:[],onItemActivate:o,onItemDeactivate:V.useCallback(()=>o(""),[o]),children:d.jsx(Et,{...i,ref:s})})}),bo=V.forwardRef((t,s)=>{const{value:e,defaultValue:c,onValueChange:r=()=>{},...i}=t,[n=[],o]=ee({prop:e,defaultProp:c,onChange:r}),l=V.useCallback(h=>o((v=[])=>[...v,h]),[o]),u=V.useCallback(h=>o((v=[])=>v.filter(S=>S!==h)),[o]);return d.jsx(It,{scope:t.__scopeToggleGroup,type:"multiple",value:n,onItemActivate:l,onItemDeactivate:u,children:d.jsx(Et,{...i,ref:s})})});Ae.displayName=re;var[Po,To]=Pt(re),Et=V.forwardRef((t,s)=>{const{__scopeToggleGroup:e,disabled:c=!1,rovingFocus:r=!0,orientation:i,dir:n,loop:o=!0,...l}=t,u=Tt(e),h=He(n),v={role:"group",dir:h,...l};return d.jsx(Po,{scope:e,rovingFocus:r,disabled:c,children:r?d.jsx(Ut,{asChild:!0,...u,orientation:i,dir:h,loop:o,children:d.jsx(_.div,{...v,ref:s})}):d.jsx(_.div,{...v,ref:s})})}),pe="ToggleGroupItem",_t=V.forwardRef((t,s)=>{const e=Rt(pe,t.__scopeToggleGroup),c=To(pe,t.__scopeToggleGroup),r=Tt(t.__scopeToggleGroup),i=e.value.includes(t.value),n=c.disabled||t.disabled,o={...t,pressed:i,disabled:n},l=V.useRef(null);return c.rovingFocus?d.jsx($t,{asChild:!0,...r,focusable:!n,active:i,ref:l,children:d.jsx(De,{...o,ref:s})}):d.jsx(De,{...o,ref:s})});_t.displayName=pe;var De=V.forwardRef((t,s)=>{const{__scopeToggleGroup:e,value:c,...r}=t,i=Rt(pe,e),n={role:"radio","aria-checked":t.pressed,"aria-pressed":void 0},o=i.type==="single"?n:void 0;return d.jsx(je,{...o,...r,ref:s,onPressedChange:l=>{l?i.onItemActivate(c):i.onItemDeactivate(c)}})}),Jo=Ae,Qo=_t;export{Vo as C,No as I,Ho as L,Lo as P,ko as R,Ko as S,Ao as T,Bo as V,Do as a,Uo as b,Go as c,Wo as d,Fo as e,$o as f,jo as g,Oo as h,qo as i,Xo as j,Yo as k,Jo as l,Qo as m}; diff --git a/pkg/ui/frontend/dist/assets/radix-layout-BqTpm3s4.js b/pkg/ui/frontend/dist/assets/radix-layout-BqTpm3s4.js new file mode 100644 index 0000000000000..a9e1f24a60ada --- /dev/null +++ b/pkg/ui/frontend/dist/assets/radix-layout-BqTpm3s4.js @@ -0,0 +1,5 @@ +import{r as s}from"./react-core-D_V7s-9r.js";import{c as I,u as _,j as i,P as R,d as g,g as N,R as Re,S as xe,h as me,i as De,F as Pe,D as q,r as be,a as j,e as O,n as Ee,f as z,A as _e,C as Ne,k as Oe,o as ye,p as Te}from"./radix-core-ByqQ8fsu.js";var M="Dialog",[Y,ot]=I(M),[we,v]=Y(M),Z=e=>{const{__scopeDialog:o,children:r,open:a,defaultOpen:t,onOpenChange:n,modal:c=!0}=e,l=s.useRef(null),u=s.useRef(null),[f=!1,p]=j({prop:a,defaultProp:t,onChange:n});return i.jsx(we,{scope:o,triggerRef:l,contentRef:u,contentId:O(),titleId:O(),descriptionId:O(),open:f,onOpenChange:p,onOpenToggle:s.useCallback(()=>p(x=>!x),[p]),modal:c,children:r})};Z.displayName=M;var J="DialogTrigger",Se=s.forwardRef((e,o)=>{const{__scopeDialog:r,...a}=e,t=v(J,r),n=_(o,t.triggerRef);return i.jsx(R.button,{type:"button","aria-haspopup":"dialog","aria-expanded":t.open,"aria-controls":t.contentId,"data-state":L(t.open),...a,ref:n,onClick:g(e.onClick,t.onOpenToggle)})});Se.displayName=J;var F="DialogPortal",[Ae,Q]=Y(F,{forceMount:void 0}),X=e=>{const{__scopeDialog:o,forceMount:r,children:a,container:t}=e,n=v(F,o);return i.jsx(Ae,{scope:o,forceMount:r,children:s.Children.map(a,c=>i.jsx(N,{present:r||n.open,children:i.jsx(Ee,{asChild:!0,container:t,children:c})}))})};X.displayName=F;var y="DialogOverlay",ee=s.forwardRef((e,o)=>{const r=Q(y,e.__scopeDialog),{forceMount:a=r.forceMount,...t}=e,n=v(y,e.__scopeDialog);return n.modal?i.jsx(N,{present:a||n.open,children:i.jsx(Ie,{...t,ref:o})}):null});ee.displayName=y;var Ie=s.forwardRef((e,o)=>{const{__scopeDialog:r,...a}=e,t=v(y,r);return i.jsx(Re,{as:xe,allowPinchZoom:!0,shards:[t.contentRef],children:i.jsx(R.div,{"data-state":L(t.open),...a,ref:o,style:{pointerEvents:"auto",...a.style}})})}),b="DialogContent",te=s.forwardRef((e,o)=>{const r=Q(b,e.__scopeDialog),{forceMount:a=r.forceMount,...t}=e,n=v(b,e.__scopeDialog);return i.jsx(N,{present:a||n.open,children:n.modal?i.jsx(je,{...t,ref:o}):i.jsx(Me,{...t,ref:o})})});te.displayName=b;var je=s.forwardRef((e,o)=>{const r=v(b,e.__scopeDialog),a=s.useRef(null),t=_(o,r.contentRef,a);return s.useEffect(()=>{const n=a.current;if(n)return me(n)},[]),i.jsx(oe,{...e,ref:t,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:g(e.onCloseAutoFocus,n=>{var c;n.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:g(e.onPointerDownOutside,n=>{const c=n.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&n.preventDefault()}),onFocusOutside:g(e.onFocusOutside,n=>n.preventDefault())})}),Me=s.forwardRef((e,o)=>{const r=v(b,e.__scopeDialog),a=s.useRef(!1),t=s.useRef(!1);return i.jsx(oe,{...e,ref:o,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:n=>{var c,l;(c=e.onCloseAutoFocus)==null||c.call(e,n),n.defaultPrevented||(a.current||(l=r.triggerRef.current)==null||l.focus(),n.preventDefault()),a.current=!1,t.current=!1},onInteractOutside:n=>{var u,f;(u=e.onInteractOutside)==null||u.call(e,n),n.defaultPrevented||(a.current=!0,n.detail.originalEvent.type==="pointerdown"&&(t.current=!0));const c=n.target;((f=r.triggerRef.current)==null?void 0:f.contains(c))&&n.preventDefault(),n.detail.originalEvent.type==="focusin"&&t.current&&n.preventDefault()}})}),oe=s.forwardRef((e,o)=>{const{__scopeDialog:r,trapFocus:a,onOpenAutoFocus:t,onCloseAutoFocus:n,...c}=e,l=v(b,r),u=s.useRef(null),f=_(o,u);return De(),i.jsxs(i.Fragment,{children:[i.jsx(Pe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:t,onUnmountAutoFocus:n,children:i.jsx(q,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":L(l.open),...c,ref:f,onDismiss:()=>l.onOpenChange(!1)})}),i.jsxs(i.Fragment,{children:[i.jsx(Fe,{titleId:l.titleId}),i.jsx(Le,{contentRef:u,descriptionId:l.descriptionId})]})]})}),H="DialogTitle",ne=s.forwardRef((e,o)=>{const{__scopeDialog:r,...a}=e,t=v(H,r);return i.jsx(R.h2,{id:t.titleId,...a,ref:o})});ne.displayName=H;var re="DialogDescription",ae=s.forwardRef((e,o)=>{const{__scopeDialog:r,...a}=e,t=v(re,r);return i.jsx(R.p,{id:t.descriptionId,...a,ref:o})});ae.displayName=re;var se="DialogClose",ie=s.forwardRef((e,o)=>{const{__scopeDialog:r,...a}=e,t=v(se,r);return i.jsx(R.button,{type:"button",...a,ref:o,onClick:g(e.onClick,()=>t.onOpenChange(!1))})});ie.displayName=se;function L(e){return e?"open":"closed"}var ce="DialogTitleWarning",[nt,le]=be(ce,{contentName:b,titleName:H,docsSlug:"dialog"}),Fe=({titleId:e})=>{const o=le(ce),r=`\`${o.contentName}\` requires a \`${o.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${o.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${o.docsSlug}`;return s.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},He="DialogDescriptionWarning",Le=({contentRef:e,descriptionId:o})=>{const a=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${le(He).contentName}}.`;return s.useEffect(()=>{var n;const t=(n=e.current)==null?void 0:n.getAttribute("aria-describedby");o&&t&&(document.getElementById(o)||console.warn(a))},[a,e,o]),null},rt=Z,at=X,st=ee,it=te,ct=ne,lt=ae,dt=ie,A,k="HoverCard",[de,ut]=I(k,[z]),S=z(),[ke,$]=de(k),ue=e=>{const{__scopeHoverCard:o,children:r,open:a,defaultOpen:t,onOpenChange:n,openDelay:c=700,closeDelay:l=300}=e,u=S(o),f=s.useRef(0),p=s.useRef(0),x=s.useRef(!1),C=s.useRef(!1),[D=!1,d]=j({prop:a,defaultProp:t,onChange:n}),m=s.useCallback(()=>{clearTimeout(p.current),f.current=window.setTimeout(()=>d(!0),c)},[c,d]),P=s.useCallback(()=>{clearTimeout(f.current),!x.current&&!C.current&&(p.current=window.setTimeout(()=>d(!1),l))},[l,d]),E=s.useCallback(()=>d(!1),[d]);return s.useEffect(()=>()=>{clearTimeout(f.current),clearTimeout(p.current)},[]),i.jsx(ke,{scope:o,open:D,onOpenChange:d,onOpen:m,onClose:P,onDismiss:E,hasSelectionRef:x,isPointerDownOnContentRef:C,children:i.jsx(ye,{...u,children:r})})};ue.displayName=k;var fe="HoverCardTrigger",pe=s.forwardRef((e,o)=>{const{__scopeHoverCard:r,...a}=e,t=$(fe,r),n=S(r);return i.jsx(_e,{asChild:!0,...n,children:i.jsx(R.a,{"data-state":t.open?"open":"closed",...a,ref:o,onPointerEnter:g(e.onPointerEnter,w(t.onOpen)),onPointerLeave:g(e.onPointerLeave,w(t.onClose)),onFocus:g(e.onFocus,t.onOpen),onBlur:g(e.onBlur,t.onClose),onTouchStart:g(e.onTouchStart,c=>c.preventDefault())})})});pe.displayName=fe;var $e="HoverCardPortal",[ft,We]=de($e,{forceMount:void 0}),T="HoverCardContent",ge=s.forwardRef((e,o)=>{const r=We(T,e.__scopeHoverCard),{forceMount:a=r.forceMount,...t}=e,n=$(T,e.__scopeHoverCard);return i.jsx(N,{present:a||n.open,children:i.jsx(Ge,{"data-state":n.open?"open":"closed",...t,onPointerEnter:g(e.onPointerEnter,w(n.onOpen)),onPointerLeave:g(e.onPointerLeave,w(n.onClose)),ref:o})})});ge.displayName=T;var Ge=s.forwardRef((e,o)=>{const{__scopeHoverCard:r,onEscapeKeyDown:a,onPointerDownOutside:t,onFocusOutside:n,onInteractOutside:c,...l}=e,u=$(T,r),f=S(r),p=s.useRef(null),x=_(o,p),[C,D]=s.useState(!1);return s.useEffect(()=>{if(C){const d=document.body;return A=d.style.userSelect||d.style.webkitUserSelect,d.style.userSelect="none",d.style.webkitUserSelect="none",()=>{d.style.userSelect=A,d.style.webkitUserSelect=A}}},[C]),s.useEffect(()=>{if(p.current){const d=()=>{D(!1),u.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var P;((P=document.getSelection())==null?void 0:P.toString())!==""&&(u.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",d),()=>{document.removeEventListener("pointerup",d),u.hasSelectionRef.current=!1,u.isPointerDownOnContentRef.current=!1}}},[u.isPointerDownOnContentRef,u.hasSelectionRef]),s.useEffect(()=>{p.current&&Ve(p.current).forEach(m=>m.setAttribute("tabindex","-1"))}),i.jsx(q,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:c,onEscapeKeyDown:a,onPointerDownOutside:t,onFocusOutside:g(n,d=>{d.preventDefault()}),onDismiss:u.onDismiss,children:i.jsx(Ne,{...f,...l,onPointerDown:g(l.onPointerDown,d=>{d.currentTarget.contains(d.target)&&D(!0),u.hasSelectionRef.current=!1,u.isPointerDownOnContentRef.current=!0}),ref:x,style:{...l.style,userSelect:C?"text":void 0,WebkitUserSelect:C?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),Be="HoverCardArrow",Ue=s.forwardRef((e,o)=>{const{__scopeHoverCard:r,...a}=e,t=S(r);return i.jsx(Oe,{...t,...a,ref:o})});Ue.displayName=Be;function w(e){return o=>o.pointerType==="touch"?void 0:e()}function Ve(e){const o=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:a=>a.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;r.nextNode();)o.push(r.currentNode);return o}var pt=ue,gt=pe,vt=ge,W="Collapsible",[Ke,Ct]=I(W),[qe,G]=Ke(W),ve=s.forwardRef((e,o)=>{const{__scopeCollapsible:r,open:a,defaultOpen:t,disabled:n,onOpenChange:c,...l}=e,[u=!1,f]=j({prop:a,defaultProp:t,onChange:c});return i.jsx(qe,{scope:r,disabled:n,contentId:O(),open:u,onOpenToggle:s.useCallback(()=>f(p=>!p),[f]),children:i.jsx(R.div,{"data-state":U(u),"data-disabled":n?"":void 0,...l,ref:o})})});ve.displayName=W;var Ce="CollapsibleTrigger",ze=s.forwardRef((e,o)=>{const{__scopeCollapsible:r,...a}=e,t=G(Ce,r);return i.jsx(R.button,{type:"button","aria-controls":t.contentId,"aria-expanded":t.open||!1,"data-state":U(t.open),"data-disabled":t.disabled?"":void 0,disabled:t.disabled,...a,ref:o,onClick:g(e.onClick,t.onOpenToggle)})});ze.displayName=Ce;var B="CollapsibleContent",Ye=s.forwardRef((e,o)=>{const{forceMount:r,...a}=e,t=G(B,e.__scopeCollapsible);return i.jsx(N,{present:r||t.open,children:({present:n})=>i.jsx(Ze,{...a,ref:o,present:n})})});Ye.displayName=B;var Ze=s.forwardRef((e,o)=>{const{__scopeCollapsible:r,present:a,children:t,...n}=e,c=G(B,r),[l,u]=s.useState(a),f=s.useRef(null),p=_(o,f),x=s.useRef(0),C=x.current,D=s.useRef(0),d=D.current,m=c.open||l,P=s.useRef(m),E=s.useRef(void 0);return s.useEffect(()=>{const h=requestAnimationFrame(()=>P.current=!1);return()=>cancelAnimationFrame(h)},[]),Te(()=>{const h=f.current;if(h){E.current=E.current||{transitionDuration:h.style.transitionDuration,animationName:h.style.animationName},h.style.transitionDuration="0s",h.style.animationName="none";const V=h.getBoundingClientRect();x.current=V.height,D.current=V.width,P.current||(h.style.transitionDuration=E.current.transitionDuration,h.style.animationName=E.current.animationName),u(a)}},[c.open,a]),i.jsx(R.div,{"data-state":U(c.open),"data-disabled":c.disabled?"":void 0,id:c.contentId,hidden:!m,...n,ref:p,style:{"--radix-collapsible-content-height":C?`${C}px`:void 0,"--radix-collapsible-content-width":d?`${d}px`:void 0,...e.style},children:m&&t})});function U(e){return e?"open":"closed"}var ht=ve,Je="Separator",K="horizontal",Qe=["horizontal","vertical"],he=s.forwardRef((e,o)=>{const{decorative:r,orientation:a=K,...t}=e,n=Xe(a)?a:K,l=r?{role:"none"}:{"aria-orientation":n==="vertical"?n:void 0,role:"separator"};return i.jsx(R.div,{"data-orientation":n,...l,...t,ref:o})});he.displayName=Je;function Xe(e){return Qe.includes(e)}var Rt=he;export{it as C,lt as D,st as O,at as P,rt as R,ct as T,dt as a,vt as b,pt as c,gt as d,ht as e,ze as f,Ye as g,Rt as h}; diff --git a/pkg/ui/frontend/dist/assets/radix-navigation-DYoR-lWZ.js b/pkg/ui/frontend/dist/assets/radix-navigation-DYoR-lWZ.js new file mode 100644 index 0000000000000..32ba7a49c0999 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/radix-navigation-DYoR-lWZ.js @@ -0,0 +1 @@ +import{b as W,r as s}from"./react-core-D_V7s-9r.js";import{c as J,u as y,j as i,S as Re,a as Ee,b as G,P as E,d as w,e as ce,f as We,A as co,g as $,h as io,i as lo,F as uo,D as fo,C as po,k as mo,l as He,R as ho,m as vo,n as wo,o as bo,p as go}from"./radix-core-ByqQ8fsu.js";function Ye(e){const o=e+"CollectionProvider",[t,n]=J(o),[r,a]=t(o,{collectionRef:{current:null},itemMap:new Map}),c=v=>{const{scope:h,children:S}=v,R=W.useRef(null),g=W.useRef(new Map).current;return i.jsx(r,{scope:h,itemMap:g,collectionRef:R,children:S})};c.displayName=o;const u=e+"CollectionSlot",f=W.forwardRef((v,h)=>{const{scope:S,children:R}=v,g=a(u,S),C=y(h,g.collectionRef);return i.jsx(Re,{ref:C,children:R})});f.displayName=u;const m=e+"CollectionItemSlot",d="data-radix-collection-item",l=W.forwardRef((v,h)=>{const{scope:S,children:R,...g}=v,C=W.useRef(null),P=y(h,C),I=a(m,S);return W.useEffect(()=>(I.itemMap.set(C,{ref:C,...g}),()=>void I.itemMap.delete(C))),i.jsx(Re,{[d]:"",ref:P,children:R})});l.displayName=m;function p(v){const h=a(e+"CollectionConsumer",v);return W.useCallback(()=>{const R=h.collectionRef.current;if(!R)return[];const g=Array.from(R.querySelectorAll(`[${d}]`));return Array.from(h.itemMap.values()).sort((I,A)=>g.indexOf(I.ref.current)-g.indexOf(A.ref.current))},[h.collectionRef,h.itemMap])}return[{Provider:c,Slot:f,ItemSlot:l},p,n]}var So=s.createContext(void 0);function fe(e){const o=s.useContext(So);return e||o||"ltr"}var xe="rovingFocusGroup.onEntryFocus",Co={bubbles:!1,cancelable:!0},pe="RovingFocusGroup",[Me,ze,xo]=Ye(pe),[Ro,me]=J(pe,[xo]),[Mo,_o]=Ro(pe),Xe=s.forwardRef((e,o)=>i.jsx(Me.Provider,{scope:e.__scopeRovingFocusGroup,children:i.jsx(Me.Slot,{scope:e.__scopeRovingFocusGroup,children:i.jsx(Eo,{...e,ref:o})})}));Xe.displayName=pe;var Eo=s.forwardRef((e,o)=>{const{__scopeRovingFocusGroup:t,orientation:n,loop:r=!1,dir:a,currentTabStopId:c,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:f,onEntryFocus:m,preventScrollOnEntryFocus:d=!1,...l}=e,p=s.useRef(null),v=y(o,p),h=fe(a),[S=null,R]=Ee({prop:c,defaultProp:u,onChange:f}),[g,C]=s.useState(!1),P=G(m),I=ze(t),A=s.useRef(!1),[F,D]=s.useState(0);return s.useEffect(()=>{const M=p.current;if(M)return M.addEventListener(xe,P),()=>M.removeEventListener(xe,P)},[P]),i.jsx(Mo,{scope:t,orientation:n,dir:h,loop:r,currentTabStopId:S,onItemFocus:s.useCallback(M=>R(M),[R]),onItemShiftTab:s.useCallback(()=>C(!0),[]),onFocusableItemAdd:s.useCallback(()=>D(M=>M+1),[]),onFocusableItemRemove:s.useCallback(()=>D(M=>M-1),[]),children:i.jsx(E.div,{tabIndex:g||F===0?-1:0,"data-orientation":n,...l,ref:v,style:{outline:"none",...e.style},onMouseDown:w(e.onMouseDown,()=>{A.current=!0}),onFocus:w(e.onFocus,M=>{const x=!A.current;if(M.target===M.currentTarget&&x&&!g){const _=new CustomEvent(xe,Co);if(M.currentTarget.dispatchEvent(_),!_.defaultPrevented){const N=I().filter(U=>U.focusable),z=N.find(U=>U.active),ae=N.find(U=>U.id===S),ge=[z,ae,...N].filter(Boolean).map(U=>U.ref.current);Je(ge,d)}}A.current=!1}),onBlur:w(e.onBlur,()=>C(!1))})})}),qe="RovingFocusGroupItem",Ze=s.forwardRef((e,o)=>{const{__scopeRovingFocusGroup:t,focusable:n=!0,active:r=!1,tabStopId:a,...c}=e,u=ce(),f=a||u,m=_o(qe,t),d=m.currentTabStopId===f,l=ze(t),{onFocusableItemAdd:p,onFocusableItemRemove:v}=m;return s.useEffect(()=>{if(n)return p(),()=>v()},[n,p,v]),i.jsx(Me.ItemSlot,{scope:t,id:f,focusable:n,active:r,children:i.jsx(E.span,{tabIndex:d?0:-1,"data-orientation":m.orientation,...c,ref:o,onMouseDown:w(e.onMouseDown,h=>{n?m.onItemFocus(f):h.preventDefault()}),onFocus:w(e.onFocus,()=>m.onItemFocus(f)),onKeyDown:w(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){m.onItemShiftTab();return}if(h.target!==h.currentTarget)return;const S=Io(h,m.orientation,m.dir);if(S!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let g=l().filter(C=>C.focusable).map(C=>C.ref.current);if(S==="last")g.reverse();else if(S==="prev"||S==="next"){S==="prev"&&g.reverse();const C=g.indexOf(h.currentTarget);g=m.loop?yo(g,C+1):g.slice(C+1)}setTimeout(()=>Je(g))}})})})});Ze.displayName=qe;var Po={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function To(e,o){return o!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Io(e,o,t){const n=To(e.key,t);if(!(o==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(o==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return Po[n]}function Je(e,o=!1){const t=document.activeElement;for(const n of e)if(n===t||(n.focus({preventScroll:o}),document.activeElement!==t))return}function yo(e,o){return e.map((t,n)=>e[(o+n)%e.length])}var Qe=Xe,et=Ze,_e=["Enter"," "],Ao=["ArrowDown","PageUp","Home"],tt=["ArrowUp","PageDown","End"],Do=[...Ao,...tt],No={ltr:[..._e,"ArrowRight"],rtl:[..._e,"ArrowLeft"]},Oo={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ne="Menu",[te,jo,Lo]=Ye(ne),[H,ot]=J(ne,[Lo,We,me]),he=We(),nt=me(),[Fo,Y]=H(ne),[ko,re]=H(ne),rt=e=>{const{__scopeMenu:o,open:t=!1,children:n,dir:r,onOpenChange:a,modal:c=!0}=e,u=he(o),[f,m]=s.useState(null),d=s.useRef(!1),l=G(a),p=fe(r);return s.useEffect(()=>{const v=()=>{d.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>d.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),i.jsx(bo,{...u,children:i.jsx(Fo,{scope:o,open:t,onOpenChange:l,content:f,onContentChange:m,children:i.jsx(ko,{scope:o,onClose:s.useCallback(()=>l(!1),[l]),isUsingKeyboardRef:d,dir:p,modal:c,children:n})})})};rt.displayName=ne;var Go="MenuAnchor",Pe=s.forwardRef((e,o)=>{const{__scopeMenu:t,...n}=e,r=he(t);return i.jsx(co,{...r,...n,ref:o})});Pe.displayName=Go;var Te="MenuPortal",[Ko,at]=H(Te,{forceMount:void 0}),st=e=>{const{__scopeMenu:o,forceMount:t,children:n,container:r}=e,a=Y(Te,o);return i.jsx(Ko,{scope:o,forceMount:t,children:i.jsx($,{present:t||a.open,children:i.jsx(wo,{asChild:!0,container:r,children:n})})})};st.displayName=Te;var j="MenuContent",[Uo,Ie]=H(j),ct=s.forwardRef((e,o)=>{const t=at(j,e.__scopeMenu),{forceMount:n=t.forceMount,...r}=e,a=Y(j,e.__scopeMenu),c=re(j,e.__scopeMenu);return i.jsx(te.Provider,{scope:e.__scopeMenu,children:i.jsx($,{present:n||a.open,children:i.jsx(te.Slot,{scope:e.__scopeMenu,children:c.modal?i.jsx(Vo,{...r,ref:o}):i.jsx($o,{...r,ref:o})})})})}),Vo=s.forwardRef((e,o)=>{const t=Y(j,e.__scopeMenu),n=s.useRef(null),r=y(o,n);return s.useEffect(()=>{const a=n.current;if(a)return io(a)},[]),i.jsx(ye,{...e,ref:r,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:w(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),$o=s.forwardRef((e,o)=>{const t=Y(j,e.__scopeMenu);return i.jsx(ye,{...e,ref:o,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),ye=s.forwardRef((e,o)=>{const{__scopeMenu:t,loop:n=!1,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEntryFocus:f,onEscapeKeyDown:m,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:p,onDismiss:v,disableOutsideScroll:h,...S}=e,R=Y(j,t),g=re(j,t),C=he(t),P=nt(t),I=jo(t),[A,F]=s.useState(null),D=s.useRef(null),M=y(o,D,R.onContentChange),x=s.useRef(0),_=s.useRef(""),N=s.useRef(0),z=s.useRef(null),ae=s.useRef("right"),se=s.useRef(0),ge=h?ho:s.Fragment,U=h?{as:Re,allowPinchZoom:!0}:void 0,so=b=>{var q,Ue;const O=_.current+b,k=I().filter(V=>!V.disabled),B=document.activeElement,Se=(q=k.find(V=>V.ref.current===B))==null?void 0:q.textValue,Ce=k.map(V=>V.textValue),Ke=tn(Ce,O,Se),Q=(Ue=k.find(V=>V.textValue===Ke))==null?void 0:Ue.ref.current;(function V(Ve){_.current=Ve,window.clearTimeout(x.current),Ve!==""&&(x.current=window.setTimeout(()=>V(""),1e3))})(O),Q&&setTimeout(()=>Q.focus())};s.useEffect(()=>()=>window.clearTimeout(x.current),[]),lo();const X=s.useCallback(b=>{var k,B;return ae.current===((k=z.current)==null?void 0:k.side)&&nn(b,(B=z.current)==null?void 0:B.area)},[]);return i.jsx(Uo,{scope:t,searchRef:_,onItemEnter:s.useCallback(b=>{X(b)&&b.preventDefault()},[X]),onItemLeave:s.useCallback(b=>{var O;X(b)||((O=D.current)==null||O.focus(),F(null))},[X]),onTriggerLeave:s.useCallback(b=>{X(b)&&b.preventDefault()},[X]),pointerGraceTimerRef:N,onPointerGraceIntentChange:s.useCallback(b=>{z.current=b},[]),children:i.jsx(ge,{...U,children:i.jsx(uo,{asChild:!0,trapped:r,onMountAutoFocus:w(a,b=>{var O;b.preventDefault(),(O=D.current)==null||O.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:i.jsx(fo,{asChild:!0,disableOutsidePointerEvents:u,onEscapeKeyDown:m,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:p,onDismiss:v,children:i.jsx(Qe,{asChild:!0,...P,dir:g.dir,orientation:"vertical",loop:n,currentTabStopId:A,onCurrentTabStopIdChange:F,onEntryFocus:w(f,b=>{g.isUsingKeyboardRef.current||b.preventDefault()}),preventScrollOnEntryFocus:!0,children:i.jsx(po,{role:"menu","aria-orientation":"vertical","data-state":Rt(R.open),"data-radix-menu-content":"",dir:g.dir,...C,...S,ref:M,style:{outline:"none",...S.style},onKeyDown:w(S.onKeyDown,b=>{const k=b.target.closest("[data-radix-menu-content]")===b.currentTarget,B=b.ctrlKey||b.altKey||b.metaKey,Se=b.key.length===1;k&&(b.key==="Tab"&&b.preventDefault(),!B&&Se&&so(b.key));const Ce=D.current;if(b.target!==Ce||!Do.includes(b.key))return;b.preventDefault();const Q=I().filter(q=>!q.disabled).map(q=>q.ref.current);tt.includes(b.key)&&Q.reverse(),Qo(Q)}),onBlur:w(e.onBlur,b=>{b.currentTarget.contains(b.target)||(window.clearTimeout(x.current),_.current="")}),onPointerMove:w(e.onPointerMove,oe(b=>{const O=b.target,k=se.current!==b.clientX;if(b.currentTarget.contains(O)&&k){const B=b.clientX>se.current?"right":"left";ae.current=B,se.current=b.clientX}}))})})})})})})});ct.displayName=j;var Bo="MenuGroup",Ae=s.forwardRef((e,o)=>{const{__scopeMenu:t,...n}=e;return i.jsx(E.div,{role:"group",...n,ref:o})});Ae.displayName=Bo;var Wo="MenuLabel",it=s.forwardRef((e,o)=>{const{__scopeMenu:t,...n}=e;return i.jsx(E.div,{...n,ref:o})});it.displayName=Wo;var ie="MenuItem",$e="menu.itemSelect",ve=s.forwardRef((e,o)=>{const{disabled:t=!1,onSelect:n,...r}=e,a=s.useRef(null),c=re(ie,e.__scopeMenu),u=Ie(ie,e.__scopeMenu),f=y(o,a),m=s.useRef(!1),d=()=>{const l=a.current;if(!t&&l){const p=new CustomEvent($e,{bubbles:!0,cancelable:!0});l.addEventListener($e,v=>n==null?void 0:n(v),{once:!0}),vo(l,p),p.defaultPrevented?m.current=!1:c.onClose()}};return i.jsx(lt,{...r,ref:f,disabled:t,onClick:w(e.onClick,d),onPointerDown:l=>{var p;(p=e.onPointerDown)==null||p.call(e,l),m.current=!0},onPointerUp:w(e.onPointerUp,l=>{var p;m.current||(p=l.currentTarget)==null||p.click()}),onKeyDown:w(e.onKeyDown,l=>{const p=u.searchRef.current!=="";t||p&&l.key===" "||_e.includes(l.key)&&(l.currentTarget.click(),l.preventDefault())})})});ve.displayName=ie;var lt=s.forwardRef((e,o)=>{const{__scopeMenu:t,disabled:n=!1,textValue:r,...a}=e,c=Ie(ie,t),u=nt(t),f=s.useRef(null),m=y(o,f),[d,l]=s.useState(!1),[p,v]=s.useState("");return s.useEffect(()=>{const h=f.current;h&&v((h.textContent??"").trim())},[a.children]),i.jsx(te.ItemSlot,{scope:t,disabled:n,textValue:r??p,children:i.jsx(et,{asChild:!0,...u,focusable:!n,children:i.jsx(E.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...a,ref:m,onPointerMove:w(e.onPointerMove,oe(h=>{n?c.onItemLeave(h):(c.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:w(e.onPointerLeave,oe(h=>c.onItemLeave(h))),onFocus:w(e.onFocus,()=>l(!0)),onBlur:w(e.onBlur,()=>l(!1))})})})}),Ho="MenuCheckboxItem",ut=s.forwardRef((e,o)=>{const{checked:t=!1,onCheckedChange:n,...r}=e;return i.jsx(ht,{scope:e.__scopeMenu,checked:t,children:i.jsx(ve,{role:"menuitemcheckbox","aria-checked":le(t)?"mixed":t,...r,ref:o,"data-state":Ne(t),onSelect:w(r.onSelect,()=>n==null?void 0:n(le(t)?!0:!t),{checkForDefaultPrevented:!1})})})});ut.displayName=Ho;var dt="MenuRadioGroup",[Yo,zo]=H(dt,{value:void 0,onValueChange:()=>{}}),ft=s.forwardRef((e,o)=>{const{value:t,onValueChange:n,...r}=e,a=G(n);return i.jsx(Yo,{scope:e.__scopeMenu,value:t,onValueChange:a,children:i.jsx(Ae,{...r,ref:o})})});ft.displayName=dt;var pt="MenuRadioItem",mt=s.forwardRef((e,o)=>{const{value:t,...n}=e,r=zo(pt,e.__scopeMenu),a=t===r.value;return i.jsx(ht,{scope:e.__scopeMenu,checked:a,children:i.jsx(ve,{role:"menuitemradio","aria-checked":a,...n,ref:o,"data-state":Ne(a),onSelect:w(n.onSelect,()=>{var c;return(c=r.onValueChange)==null?void 0:c.call(r,t)},{checkForDefaultPrevented:!1})})})});mt.displayName=pt;var De="MenuItemIndicator",[ht,Xo]=H(De,{checked:!1}),vt=s.forwardRef((e,o)=>{const{__scopeMenu:t,forceMount:n,...r}=e,a=Xo(De,t);return i.jsx($,{present:n||le(a.checked)||a.checked===!0,children:i.jsx(E.span,{...r,ref:o,"data-state":Ne(a.checked)})})});vt.displayName=De;var qo="MenuSeparator",wt=s.forwardRef((e,o)=>{const{__scopeMenu:t,...n}=e;return i.jsx(E.div,{role:"separator","aria-orientation":"horizontal",...n,ref:o})});wt.displayName=qo;var Zo="MenuArrow",bt=s.forwardRef((e,o)=>{const{__scopeMenu:t,...n}=e,r=he(t);return i.jsx(mo,{...r,...n,ref:o})});bt.displayName=Zo;var Jo="MenuSub",[tr,gt]=H(Jo),ee="MenuSubTrigger",St=s.forwardRef((e,o)=>{const t=Y(ee,e.__scopeMenu),n=re(ee,e.__scopeMenu),r=gt(ee,e.__scopeMenu),a=Ie(ee,e.__scopeMenu),c=s.useRef(null),{pointerGraceTimerRef:u,onPointerGraceIntentChange:f}=a,m={__scopeMenu:e.__scopeMenu},d=s.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return s.useEffect(()=>d,[d]),s.useEffect(()=>{const l=u.current;return()=>{window.clearTimeout(l),f(null)}},[u,f]),i.jsx(Pe,{asChild:!0,...m,children:i.jsx(lt,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":r.contentId,"data-state":Rt(t.open),...e,ref:He(o,r.onTriggerChange),onClick:l=>{var p;(p=e.onClick)==null||p.call(e,l),!(e.disabled||l.defaultPrevented)&&(l.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:w(e.onPointerMove,oe(l=>{a.onItemEnter(l),!l.defaultPrevented&&!e.disabled&&!t.open&&!c.current&&(a.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{t.onOpenChange(!0),d()},100))})),onPointerLeave:w(e.onPointerLeave,oe(l=>{var v,h;d();const p=(v=t.content)==null?void 0:v.getBoundingClientRect();if(p){const S=(h=t.content)==null?void 0:h.dataset.side,R=S==="right",g=R?-5:5,C=p[R?"left":"right"],P=p[R?"right":"left"];a.onPointerGraceIntentChange({area:[{x:l.clientX+g,y:l.clientY},{x:C,y:p.top},{x:P,y:p.top},{x:P,y:p.bottom},{x:C,y:p.bottom}],side:S}),window.clearTimeout(u.current),u.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(l),l.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:w(e.onKeyDown,l=>{var v;const p=a.searchRef.current!=="";e.disabled||p&&l.key===" "||No[n.dir].includes(l.key)&&(t.onOpenChange(!0),(v=t.content)==null||v.focus(),l.preventDefault())})})})});St.displayName=ee;var Ct="MenuSubContent",xt=s.forwardRef((e,o)=>{const t=at(j,e.__scopeMenu),{forceMount:n=t.forceMount,...r}=e,a=Y(j,e.__scopeMenu),c=re(j,e.__scopeMenu),u=gt(Ct,e.__scopeMenu),f=s.useRef(null),m=y(o,f);return i.jsx(te.Provider,{scope:e.__scopeMenu,children:i.jsx($,{present:n||a.open,children:i.jsx(te.Slot,{scope:e.__scopeMenu,children:i.jsx(ye,{id:u.contentId,"aria-labelledby":u.triggerId,...r,ref:m,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var l;c.isUsingKeyboardRef.current&&((l=f.current)==null||l.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:w(e.onFocusOutside,d=>{d.target!==u.trigger&&a.onOpenChange(!1)}),onEscapeKeyDown:w(e.onEscapeKeyDown,d=>{c.onClose(),d.preventDefault()}),onKeyDown:w(e.onKeyDown,d=>{var v;const l=d.currentTarget.contains(d.target),p=Oo[c.dir].includes(d.key);l&&p&&(a.onOpenChange(!1),(v=u.trigger)==null||v.focus(),d.preventDefault())})})})})})});xt.displayName=Ct;function Rt(e){return e?"open":"closed"}function le(e){return e==="indeterminate"}function Ne(e){return le(e)?"indeterminate":e?"checked":"unchecked"}function Qo(e){const o=document.activeElement;for(const t of e)if(t===o||(t.focus(),document.activeElement!==o))return}function en(e,o){return e.map((t,n)=>e[(o+n)%e.length])}function tn(e,o,t){const r=o.length>1&&Array.from(o).every(m=>m===o[0])?o[0]:o,a=t?e.indexOf(t):-1;let c=en(e,Math.max(a,0));r.length===1&&(c=c.filter(m=>m!==t));const f=c.find(m=>m.toLowerCase().startsWith(r.toLowerCase()));return f!==t?f:void 0}function on(e,o){const{x:t,y:n}=e;let r=!1;for(let a=0,c=o.length-1;a<o.length;c=a++){const u=o[a].x,f=o[a].y,m=o[c].x,d=o[c].y;f>n!=d>n&&t<(m-u)*(n-f)/(d-f)+u&&(r=!r)}return r}function nn(e,o){if(!o)return!1;const t={x:e.clientX,y:e.clientY};return on(t,o)}function oe(e){return o=>o.pointerType==="mouse"?e(o):void 0}var rn=rt,an=Pe,sn=st,cn=ct,ln=Ae,un=it,dn=ve,fn=ut,pn=ft,mn=mt,hn=vt,vn=wt,wn=bt,bn=St,gn=xt,Oe="DropdownMenu",[Sn,or]=J(Oe,[ot]),T=ot(),[Cn,Mt]=Sn(Oe),_t=e=>{const{__scopeDropdownMenu:o,children:t,dir:n,open:r,defaultOpen:a,onOpenChange:c,modal:u=!0}=e,f=T(o),m=s.useRef(null),[d=!1,l]=Ee({prop:r,defaultProp:a,onChange:c});return i.jsx(Cn,{scope:o,triggerId:ce(),triggerRef:m,contentId:ce(),open:d,onOpenChange:l,onOpenToggle:s.useCallback(()=>l(p=>!p),[l]),modal:u,children:i.jsx(rn,{...f,open:d,onOpenChange:l,dir:n,modal:u,children:t})})};_t.displayName=Oe;var Et="DropdownMenuTrigger",Pt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,disabled:n=!1,...r}=e,a=Mt(Et,t),c=T(t);return i.jsx(an,{asChild:!0,...c,children:i.jsx(E.button,{type:"button",id:a.triggerId,"aria-haspopup":"menu","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...r,ref:He(o,a.triggerRef),onPointerDown:w(e.onPointerDown,u=>{!n&&u.button===0&&u.ctrlKey===!1&&(a.onOpenToggle(),a.open||u.preventDefault())}),onKeyDown:w(e.onKeyDown,u=>{n||(["Enter"," "].includes(u.key)&&a.onOpenToggle(),u.key==="ArrowDown"&&a.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(u.key)&&u.preventDefault())})})})});Pt.displayName=Et;var xn="DropdownMenuPortal",Tt=e=>{const{__scopeDropdownMenu:o,...t}=e,n=T(o);return i.jsx(sn,{...n,...t})};Tt.displayName=xn;var It="DropdownMenuContent",yt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=Mt(It,t),a=T(t),c=s.useRef(!1);return i.jsx(cn,{id:r.contentId,"aria-labelledby":r.triggerId,...a,...n,ref:o,onCloseAutoFocus:w(e.onCloseAutoFocus,u=>{var f;c.current||(f=r.triggerRef.current)==null||f.focus(),c.current=!1,u.preventDefault()}),onInteractOutside:w(e.onInteractOutside,u=>{const f=u.detail.originalEvent,m=f.button===0&&f.ctrlKey===!0,d=f.button===2||m;(!r.modal||d)&&(c.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});yt.displayName=It;var Rn="DropdownMenuGroup",Mn=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(ln,{...r,...n,ref:o})});Mn.displayName=Rn;var _n="DropdownMenuLabel",At=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(un,{...r,...n,ref:o})});At.displayName=_n;var En="DropdownMenuItem",Dt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(dn,{...r,...n,ref:o})});Dt.displayName=En;var Pn="DropdownMenuCheckboxItem",Nt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(fn,{...r,...n,ref:o})});Nt.displayName=Pn;var Tn="DropdownMenuRadioGroup",In=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(pn,{...r,...n,ref:o})});In.displayName=Tn;var yn="DropdownMenuRadioItem",Ot=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(mn,{...r,...n,ref:o})});Ot.displayName=yn;var An="DropdownMenuItemIndicator",jt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(hn,{...r,...n,ref:o})});jt.displayName=An;var Dn="DropdownMenuSeparator",Lt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(vn,{...r,...n,ref:o})});Lt.displayName=Dn;var Nn="DropdownMenuArrow",On=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(wn,{...r,...n,ref:o})});On.displayName=Nn;var jn="DropdownMenuSubTrigger",Ft=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(bn,{...r,...n,ref:o})});Ft.displayName=jn;var Ln="DropdownMenuSubContent",kt=s.forwardRef((e,o)=>{const{__scopeDropdownMenu:t,...n}=e,r=T(t);return i.jsx(gn,{...r,...n,ref:o,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});kt.displayName=Ln;var nr=_t,rr=Pt,ar=Tt,sr=yt,cr=At,ir=Dt,lr=Nt,ur=Ot,dr=jt,fr=Lt,pr=Ft,mr=kt;function Fn(e,[o,t]){return Math.min(t,Math.max(o,e))}function kn(e,o){return s.useReducer((t,n)=>o[t][n]??t,e)}var je="ScrollArea",[Gt,hr]=J(je),[Gn,L]=Gt(je),Kt=s.forwardRef((e,o)=>{const{__scopeScrollArea:t,type:n="hover",dir:r,scrollHideDelay:a=600,...c}=e,[u,f]=s.useState(null),[m,d]=s.useState(null),[l,p]=s.useState(null),[v,h]=s.useState(null),[S,R]=s.useState(null),[g,C]=s.useState(0),[P,I]=s.useState(0),[A,F]=s.useState(!1),[D,M]=s.useState(!1),x=y(o,N=>f(N)),_=fe(r);return i.jsx(Gn,{scope:t,type:n,dir:_,scrollHideDelay:a,scrollArea:u,viewport:m,onViewportChange:d,content:l,onContentChange:p,scrollbarX:v,onScrollbarXChange:h,scrollbarXEnabled:A,onScrollbarXEnabledChange:F,scrollbarY:S,onScrollbarYChange:R,scrollbarYEnabled:D,onScrollbarYEnabledChange:M,onCornerWidthChange:C,onCornerHeightChange:I,children:i.jsx(E.div,{dir:_,...c,ref:x,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":P+"px",...e.style}})})});Kt.displayName=je;var Ut="ScrollAreaViewport",Vt=s.forwardRef((e,o)=>{const{__scopeScrollArea:t,children:n,nonce:r,...a}=e,c=L(Ut,t),u=s.useRef(null),f=y(o,u,c.onViewportChange);return i.jsxs(i.Fragment,{children:[i.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),i.jsx(E.div,{"data-radix-scroll-area-viewport":"",...a,ref:f,style:{overflowX:c.scrollbarXEnabled?"scroll":"hidden",overflowY:c.scrollbarYEnabled?"scroll":"hidden",...e.style},children:i.jsx("div",{ref:c.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});Vt.displayName=Ut;var K="ScrollAreaScrollbar",Kn=s.forwardRef((e,o)=>{const{forceMount:t,...n}=e,r=L(K,e.__scopeScrollArea),{onScrollbarXEnabledChange:a,onScrollbarYEnabledChange:c}=r,u=e.orientation==="horizontal";return s.useEffect(()=>(u?a(!0):c(!0),()=>{u?a(!1):c(!1)}),[u,a,c]),r.type==="hover"?i.jsx(Un,{...n,ref:o,forceMount:t}):r.type==="scroll"?i.jsx(Vn,{...n,ref:o,forceMount:t}):r.type==="auto"?i.jsx($t,{...n,ref:o,forceMount:t}):r.type==="always"?i.jsx(Le,{...n,ref:o}):null});Kn.displayName=K;var Un=s.forwardRef((e,o)=>{const{forceMount:t,...n}=e,r=L(K,e.__scopeScrollArea),[a,c]=s.useState(!1);return s.useEffect(()=>{const u=r.scrollArea;let f=0;if(u){const m=()=>{window.clearTimeout(f),c(!0)},d=()=>{f=window.setTimeout(()=>c(!1),r.scrollHideDelay)};return u.addEventListener("pointerenter",m),u.addEventListener("pointerleave",d),()=>{window.clearTimeout(f),u.removeEventListener("pointerenter",m),u.removeEventListener("pointerleave",d)}}},[r.scrollArea,r.scrollHideDelay]),i.jsx($,{present:t||a,children:i.jsx($t,{"data-state":a?"visible":"hidden",...n,ref:o})})}),Vn=s.forwardRef((e,o)=>{const{forceMount:t,...n}=e,r=L(K,e.__scopeScrollArea),a=e.orientation==="horizontal",c=be(()=>f("SCROLL_END"),100),[u,f]=kn("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return s.useEffect(()=>{if(u==="idle"){const m=window.setTimeout(()=>f("HIDE"),r.scrollHideDelay);return()=>window.clearTimeout(m)}},[u,r.scrollHideDelay,f]),s.useEffect(()=>{const m=r.viewport,d=a?"scrollLeft":"scrollTop";if(m){let l=m[d];const p=()=>{const v=m[d];l!==v&&(f("SCROLL"),c()),l=v};return m.addEventListener("scroll",p),()=>m.removeEventListener("scroll",p)}},[r.viewport,a,f,c]),i.jsx($,{present:t||u!=="hidden",children:i.jsx(Le,{"data-state":u==="hidden"?"hidden":"visible",...n,ref:o,onPointerEnter:w(e.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:w(e.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),$t=s.forwardRef((e,o)=>{const t=L(K,e.__scopeScrollArea),{forceMount:n,...r}=e,[a,c]=s.useState(!1),u=e.orientation==="horizontal",f=be(()=>{if(t.viewport){const m=t.viewport.offsetWidth<t.viewport.scrollWidth,d=t.viewport.offsetHeight<t.viewport.scrollHeight;c(u?m:d)}},10);return Z(t.viewport,f),Z(t.content,f),i.jsx($,{present:n||a,children:i.jsx(Le,{"data-state":a?"visible":"hidden",...r,ref:o})})}),Le=s.forwardRef((e,o)=>{const{orientation:t="vertical",...n}=e,r=L(K,e.__scopeScrollArea),a=s.useRef(null),c=s.useRef(0),[u,f]=s.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),m=Yt(u.viewport,u.content),d={...n,sizes:u,onSizesChange:f,hasThumb:m>0&&m<1,onThumbChange:p=>a.current=p,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:p=>c.current=p};function l(p,v){return Xn(p,c.current,u,v)}return t==="horizontal"?i.jsx($n,{...d,ref:o,onThumbPositionChange:()=>{if(r.viewport&&a.current){const p=r.viewport.scrollLeft,v=Be(p,u,r.dir);a.current.style.transform=`translate3d(${v}px, 0, 0)`}},onWheelScroll:p=>{r.viewport&&(r.viewport.scrollLeft=p)},onDragScroll:p=>{r.viewport&&(r.viewport.scrollLeft=l(p,r.dir))}}):t==="vertical"?i.jsx(Bn,{...d,ref:o,onThumbPositionChange:()=>{if(r.viewport&&a.current){const p=r.viewport.scrollTop,v=Be(p,u);a.current.style.transform=`translate3d(0, ${v}px, 0)`}},onWheelScroll:p=>{r.viewport&&(r.viewport.scrollTop=p)},onDragScroll:p=>{r.viewport&&(r.viewport.scrollTop=l(p))}}):null}),$n=s.forwardRef((e,o)=>{const{sizes:t,onSizesChange:n,...r}=e,a=L(K,e.__scopeScrollArea),[c,u]=s.useState(),f=s.useRef(null),m=y(o,f,a.onScrollbarXChange);return s.useEffect(()=>{f.current&&u(getComputedStyle(f.current))},[f]),i.jsx(Wt,{"data-orientation":"horizontal",...r,ref:m,sizes:t,style:{bottom:0,left:a.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:a.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":we(t)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,l)=>{if(a.viewport){const p=a.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Xt(p,l)&&d.preventDefault()}},onResize:()=>{f.current&&a.viewport&&c&&n({content:a.viewport.scrollWidth,viewport:a.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:de(c.paddingLeft),paddingEnd:de(c.paddingRight)}})}})}),Bn=s.forwardRef((e,o)=>{const{sizes:t,onSizesChange:n,...r}=e,a=L(K,e.__scopeScrollArea),[c,u]=s.useState(),f=s.useRef(null),m=y(o,f,a.onScrollbarYChange);return s.useEffect(()=>{f.current&&u(getComputedStyle(f.current))},[f]),i.jsx(Wt,{"data-orientation":"vertical",...r,ref:m,sizes:t,style:{top:0,right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":we(t)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,l)=>{if(a.viewport){const p=a.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Xt(p,l)&&d.preventDefault()}},onResize:()=>{f.current&&a.viewport&&c&&n({content:a.viewport.scrollHeight,viewport:a.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:de(c.paddingTop),paddingEnd:de(c.paddingBottom)}})}})}),[Wn,Bt]=Gt(K),Wt=s.forwardRef((e,o)=>{const{__scopeScrollArea:t,sizes:n,hasThumb:r,onThumbChange:a,onThumbPointerUp:c,onThumbPointerDown:u,onThumbPositionChange:f,onDragScroll:m,onWheelScroll:d,onResize:l,...p}=e,v=L(K,t),[h,S]=s.useState(null),R=y(o,x=>S(x)),g=s.useRef(null),C=s.useRef(""),P=v.viewport,I=n.content-n.viewport,A=G(d),F=G(f),D=be(l,10);function M(x){if(g.current){const _=x.clientX-g.current.left,N=x.clientY-g.current.top;m({x:_,y:N})}}return s.useEffect(()=>{const x=_=>{const N=_.target;(h==null?void 0:h.contains(N))&&A(_,I)};return document.addEventListener("wheel",x,{passive:!1}),()=>document.removeEventListener("wheel",x,{passive:!1})},[P,h,I,A]),s.useEffect(F,[n,F]),Z(h,D),Z(v.content,D),i.jsx(Wn,{scope:t,scrollbar:h,hasThumb:r,onThumbChange:G(a),onThumbPointerUp:G(c),onThumbPositionChange:F,onThumbPointerDown:G(u),children:i.jsx(E.div,{...p,ref:R,style:{position:"absolute",...p.style},onPointerDown:w(e.onPointerDown,x=>{x.button===0&&(x.target.setPointerCapture(x.pointerId),g.current=h.getBoundingClientRect(),C.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",v.viewport&&(v.viewport.style.scrollBehavior="auto"),M(x))}),onPointerMove:w(e.onPointerMove,M),onPointerUp:w(e.onPointerUp,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),document.body.style.webkitUserSelect=C.current,v.viewport&&(v.viewport.style.scrollBehavior=""),g.current=null})})})}),ue="ScrollAreaThumb",Hn=s.forwardRef((e,o)=>{const{forceMount:t,...n}=e,r=Bt(ue,e.__scopeScrollArea);return i.jsx($,{present:t||r.hasThumb,children:i.jsx(Yn,{ref:o,...n})})}),Yn=s.forwardRef((e,o)=>{const{__scopeScrollArea:t,style:n,...r}=e,a=L(ue,t),c=Bt(ue,t),{onThumbPositionChange:u}=c,f=y(o,l=>c.onThumbChange(l)),m=s.useRef(void 0),d=be(()=>{m.current&&(m.current(),m.current=void 0)},100);return s.useEffect(()=>{const l=a.viewport;if(l){const p=()=>{if(d(),!m.current){const v=qn(l,u);m.current=v,u()}};return u(),l.addEventListener("scroll",p),()=>l.removeEventListener("scroll",p)}},[a.viewport,d,u]),i.jsx(E.div,{"data-state":c.hasThumb?"visible":"hidden",...r,ref:f,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:w(e.onPointerDownCapture,l=>{const v=l.target.getBoundingClientRect(),h=l.clientX-v.left,S=l.clientY-v.top;c.onThumbPointerDown({x:h,y:S})}),onPointerUp:w(e.onPointerUp,c.onThumbPointerUp)})});Hn.displayName=ue;var Fe="ScrollAreaCorner",Ht=s.forwardRef((e,o)=>{const t=L(Fe,e.__scopeScrollArea),n=!!(t.scrollbarX&&t.scrollbarY);return t.type!=="scroll"&&n?i.jsx(zn,{...e,ref:o}):null});Ht.displayName=Fe;var zn=s.forwardRef((e,o)=>{const{__scopeScrollArea:t,...n}=e,r=L(Fe,t),[a,c]=s.useState(0),[u,f]=s.useState(0),m=!!(a&&u);return Z(r.scrollbarX,()=>{var l;const d=((l=r.scrollbarX)==null?void 0:l.offsetHeight)||0;r.onCornerHeightChange(d),f(d)}),Z(r.scrollbarY,()=>{var l;const d=((l=r.scrollbarY)==null?void 0:l.offsetWidth)||0;r.onCornerWidthChange(d),c(d)}),m?i.jsx(E.div,{...n,ref:o,style:{width:a,height:u,position:"absolute",right:r.dir==="ltr"?0:void 0,left:r.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function de(e){return e?parseInt(e,10):0}function Yt(e,o){const t=e/o;return isNaN(t)?0:t}function we(e){const o=Yt(e.viewport,e.content),t=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,n=(e.scrollbar.size-t)*o;return Math.max(n,18)}function Xn(e,o,t,n="ltr"){const r=we(t),a=r/2,c=o||a,u=r-c,f=t.scrollbar.paddingStart+c,m=t.scrollbar.size-t.scrollbar.paddingEnd-u,d=t.content-t.viewport,l=n==="ltr"?[0,d]:[d*-1,0];return zt([f,m],l)(e)}function Be(e,o,t="ltr"){const n=we(o),r=o.scrollbar.paddingStart+o.scrollbar.paddingEnd,a=o.scrollbar.size-r,c=o.content-o.viewport,u=a-n,f=t==="ltr"?[0,c]:[c*-1,0],m=Fn(e,f);return zt([0,c],[0,u])(m)}function zt(e,o){return t=>{if(e[0]===e[1]||o[0]===o[1])return o[0];const n=(o[1]-o[0])/(e[1]-e[0]);return o[0]+n*(t-e[0])}}function Xt(e,o){return e>0&&e<o}var qn=(e,o=()=>{})=>{let t={left:e.scrollLeft,top:e.scrollTop},n=0;return function r(){const a={left:e.scrollLeft,top:e.scrollTop},c=t.left!==a.left,u=t.top!==a.top;(c||u)&&o(),t=a,n=window.requestAnimationFrame(r)}(),()=>window.cancelAnimationFrame(n)};function be(e,o){const t=G(e),n=s.useRef(0);return s.useEffect(()=>()=>window.clearTimeout(n.current),[]),s.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(t,o)},[t,o])}function Z(e,o){const t=G(o);go(()=>{let n=0;if(e){const r=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(t)});return r.observe(e),()=>{window.cancelAnimationFrame(n),r.unobserve(e)}}},[e,t])}var vr=Kt,wr=Vt,br=Ht,ke="Tabs",[Zn,gr]=J(ke,[me]),qt=me(),[Jn,Ge]=Zn(ke),Zt=s.forwardRef((e,o)=>{const{__scopeTabs:t,value:n,onValueChange:r,defaultValue:a,orientation:c="horizontal",dir:u,activationMode:f="automatic",...m}=e,d=fe(u),[l,p]=Ee({prop:n,onChange:r,defaultProp:a});return i.jsx(Jn,{scope:t,baseId:ce(),value:l,onValueChange:p,orientation:c,dir:d,activationMode:f,children:i.jsx(E.div,{dir:d,"data-orientation":c,...m,ref:o})})});Zt.displayName=ke;var Jt="TabsList",Qt=s.forwardRef((e,o)=>{const{__scopeTabs:t,loop:n=!0,...r}=e,a=Ge(Jt,t),c=qt(t);return i.jsx(Qe,{asChild:!0,...c,orientation:a.orientation,dir:a.dir,loop:n,children:i.jsx(E.div,{role:"tablist","aria-orientation":a.orientation,...r,ref:o})})});Qt.displayName=Jt;var eo="TabsTrigger",to=s.forwardRef((e,o)=>{const{__scopeTabs:t,value:n,disabled:r=!1,...a}=e,c=Ge(eo,t),u=qt(t),f=ro(c.baseId,n),m=ao(c.baseId,n),d=n===c.value;return i.jsx(et,{asChild:!0,...u,focusable:!r,active:d,children:i.jsx(E.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":m,"data-state":d?"active":"inactive","data-disabled":r?"":void 0,disabled:r,id:f,...a,ref:o,onMouseDown:w(e.onMouseDown,l=>{!r&&l.button===0&&l.ctrlKey===!1?c.onValueChange(n):l.preventDefault()}),onKeyDown:w(e.onKeyDown,l=>{[" ","Enter"].includes(l.key)&&c.onValueChange(n)}),onFocus:w(e.onFocus,()=>{const l=c.activationMode!=="manual";!d&&!r&&l&&c.onValueChange(n)})})})});to.displayName=eo;var oo="TabsContent",no=s.forwardRef((e,o)=>{const{__scopeTabs:t,value:n,forceMount:r,children:a,...c}=e,u=Ge(oo,t),f=ro(u.baseId,n),m=ao(u.baseId,n),d=n===u.value,l=s.useRef(d);return s.useEffect(()=>{const p=requestAnimationFrame(()=>l.current=!1);return()=>cancelAnimationFrame(p)},[]),i.jsx($,{present:r||d,children:({present:p})=>i.jsx(E.div,{"data-state":d?"active":"inactive","data-orientation":u.orientation,role:"tabpanel","aria-labelledby":f,hidden:!p,id:m,tabIndex:0,...c,ref:o,style:{...e.style,animationDuration:l.current?"0s":void 0},children:p&&a})})});no.displayName=oo;function ro(e,o){return`${e}-trigger-${o}`}function ao(e,o){return`${e}-content-${o}`}var Sr=Zt,Cr=Qt,xr=to,Rr=no;export{sr as C,et as I,cr as L,ar as P,Qe as R,pr as S,rr as T,wr as V,Fn as a,me as b,Ye as c,mr as d,ir as e,lr as f,dr as g,ur as h,fr as i,nr as j,vr as k,br as l,Kn as m,Hn as n,Cr as o,xr as p,Rr as q,Sr as r,fe as u}; diff --git a/pkg/ui/frontend/dist/assets/react-core-D_V7s-9r.js b/pkg/ui/frontend/dist/assets/react-core-D_V7s-9r.js new file mode 100644 index 0000000000000..e46154114c04c --- /dev/null +++ b/pkg/ui/frontend/dist/assets/react-core-D_V7s-9r.js @@ -0,0 +1,32 @@ +function $o(e,n){for(var t=0;t<n.length;t++){const r=n[t];if(typeof r!="string"&&!Array.isArray(r)){for(const l in r)if(l!=="default"&&!(l in e)){const u=Object.getOwnPropertyDescriptor(r,l);u&&Object.defineProperty(e,l,u.get?u:{enumerable:!0,get:()=>r[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var kd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Vo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ao={exports:{}},T={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Kt=Symbol.for("react.element"),ba=Symbol.for("react.portal"),ef=Symbol.for("react.fragment"),nf=Symbol.for("react.strict_mode"),tf=Symbol.for("react.profiler"),rf=Symbol.for("react.provider"),lf=Symbol.for("react.context"),uf=Symbol.for("react.forward_ref"),of=Symbol.for("react.suspense"),sf=Symbol.for("react.memo"),af=Symbol.for("react.lazy"),Li=Symbol.iterator;function ff(e){return e===null||typeof e!="object"?null:(e=Li&&e[Li]||e["@@iterator"],typeof e=="function"?e:null)}var Bo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ho=Object.assign,Wo={};function rt(e,n,t){this.props=e,this.context=n,this.refs=Wo,this.updater=t||Bo}rt.prototype.isReactComponent={};rt.prototype.setState=function(e,n){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,n,"setState")};rt.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Qo(){}Qo.prototype=rt.prototype;function Du(e,n,t){this.props=e,this.context=n,this.refs=Wo,this.updater=t||Bo}var Iu=Du.prototype=new Qo;Iu.constructor=Du;Ho(Iu,rt.prototype);Iu.isPureReactComponent=!0;var Ri=Array.isArray,Ko=Object.prototype.hasOwnProperty,Fu={current:null},Yo={key:!0,ref:!0,__self:!0,__source:!0};function Xo(e,n,t){var r,l={},u=null,i=null;if(n!=null)for(r in n.ref!==void 0&&(i=n.ref),n.key!==void 0&&(u=""+n.key),n)Ko.call(n,r)&&!Yo.hasOwnProperty(r)&&(l[r]=n[r]);var o=arguments.length-2;if(o===1)l.children=t;else if(1<o){for(var s=Array(o),f=0;f<o;f++)s[f]=arguments[f+2];l.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)l[r]===void 0&&(l[r]=o[r]);return{$$typeof:Kt,type:e,key:u,ref:i,props:l,_owner:Fu.current}}function cf(e,n){return{$$typeof:Kt,type:e.type,key:n,ref:e.ref,props:e.props,_owner:e._owner}}function ju(e){return typeof e=="object"&&e!==null&&e.$$typeof===Kt}function df(e){var n={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(t){return n[t]})}var Mi=/\/+/g;function vl(e,n){return typeof e=="object"&&e!==null&&e.key!=null?df(""+e.key):n.toString(36)}function vr(e,n,t,r,l){var u=typeof e;(u==="undefined"||u==="boolean")&&(e=null);var i=!1;if(e===null)i=!0;else switch(u){case"string":case"number":i=!0;break;case"object":switch(e.$$typeof){case Kt:case ba:i=!0}}if(i)return i=e,l=l(i),e=r===""?"."+vl(i,0):r,Ri(l)?(t="",e!=null&&(t=e.replace(Mi,"$&/")+"/"),vr(l,n,t,"",function(f){return f})):l!=null&&(ju(l)&&(l=cf(l,t+(!l.key||i&&i.key===l.key?"":(""+l.key).replace(Mi,"$&/")+"/")+e)),n.push(l)),1;if(i=0,r=r===""?".":r+":",Ri(e))for(var o=0;o<e.length;o++){u=e[o];var s=r+vl(u,o);i+=vr(u,n,t,s,l)}else if(s=ff(e),typeof s=="function")for(e=s.call(e),o=0;!(u=e.next()).done;)u=u.value,s=r+vl(u,o++),i+=vr(u,n,t,s,l);else if(u==="object")throw n=String(e),Error("Objects are not valid as a React child (found: "+(n==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.");return i}function bt(e,n,t){if(e==null)return e;var r=[],l=0;return vr(e,r,"","",function(u){return n.call(t,u,l++)}),r}function pf(e){if(e._status===-1){var n=e._result;n=n(),n.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var ie={current:null},yr={transition:null},mf={ReactCurrentDispatcher:ie,ReactCurrentBatchConfig:yr,ReactCurrentOwner:Fu};function Go(){throw Error("act(...) is not supported in production builds of React.")}T.Children={map:bt,forEach:function(e,n,t){bt(e,function(){n.apply(this,arguments)},t)},count:function(e){var n=0;return bt(e,function(){n++}),n},toArray:function(e){return bt(e,function(n){return n})||[]},only:function(e){if(!ju(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};T.Component=rt;T.Fragment=ef;T.Profiler=tf;T.PureComponent=Du;T.StrictMode=nf;T.Suspense=of;T.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=mf;T.act=Go;T.cloneElement=function(e,n,t){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Ho({},e.props),l=e.key,u=e.ref,i=e._owner;if(n!=null){if(n.ref!==void 0&&(u=n.ref,i=Fu.current),n.key!==void 0&&(l=""+n.key),e.type&&e.type.defaultProps)var o=e.type.defaultProps;for(s in n)Ko.call(n,s)&&!Yo.hasOwnProperty(s)&&(r[s]=n[s]===void 0&&o!==void 0?o[s]:n[s])}var s=arguments.length-2;if(s===1)r.children=t;else if(1<s){o=Array(s);for(var f=0;f<s;f++)o[f]=arguments[f+2];r.children=o}return{$$typeof:Kt,type:e.type,key:l,ref:u,props:r,_owner:i}};T.createContext=function(e){return e={$$typeof:lf,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:rf,_context:e},e.Consumer=e};T.createElement=Xo;T.createFactory=function(e){var n=Xo.bind(null,e);return n.type=e,n};T.createRef=function(){return{current:null}};T.forwardRef=function(e){return{$$typeof:uf,render:e}};T.isValidElement=ju;T.lazy=function(e){return{$$typeof:af,_payload:{_status:-1,_result:e},_init:pf}};T.memo=function(e,n){return{$$typeof:sf,type:e,compare:n===void 0?null:n}};T.startTransition=function(e){var n=yr.transition;yr.transition={};try{e()}finally{yr.transition=n}};T.unstable_act=Go;T.useCallback=function(e,n){return ie.current.useCallback(e,n)};T.useContext=function(e){return ie.current.useContext(e)};T.useDebugValue=function(){};T.useDeferredValue=function(e){return ie.current.useDeferredValue(e)};T.useEffect=function(e,n){return ie.current.useEffect(e,n)};T.useId=function(){return ie.current.useId()};T.useImperativeHandle=function(e,n,t){return ie.current.useImperativeHandle(e,n,t)};T.useInsertionEffect=function(e,n){return ie.current.useInsertionEffect(e,n)};T.useLayoutEffect=function(e,n){return ie.current.useLayoutEffect(e,n)};T.useMemo=function(e,n){return ie.current.useMemo(e,n)};T.useReducer=function(e,n,t){return ie.current.useReducer(e,n,t)};T.useRef=function(e){return ie.current.useRef(e)};T.useState=function(e){return ie.current.useState(e)};T.useSyncExternalStore=function(e,n,t){return ie.current.useSyncExternalStore(e,n,t)};T.useTransition=function(){return ie.current.useTransition()};T.version="18.3.1";Ao.exports=T;var Uu=Ao.exports;const hf=Vo(Uu),Sd=$o({__proto__:null,default:hf},[Uu]);var Zo={exports:{}},ye={},Jo={exports:{}},qo={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(e){function n(C,N){var z=C.length;C.push(N);e:for(;0<z;){var H=z-1>>>1,X=C[H];if(0<l(X,N))C[H]=N,C[z]=X,z=H;else break e}}function t(C){return C.length===0?null:C[0]}function r(C){if(C.length===0)return null;var N=C[0],z=C.pop();if(z!==N){C[0]=z;e:for(var H=0,X=C.length,Jt=X>>>1;H<Jt;){var hn=2*(H+1)-1,hl=C[hn],vn=hn+1,qt=C[vn];if(0>l(hl,z))vn<X&&0>l(qt,hl)?(C[H]=qt,C[vn]=z,H=vn):(C[H]=hl,C[hn]=z,H=hn);else if(vn<X&&0>l(qt,z))C[H]=qt,C[vn]=z,H=vn;else break e}}return N}function l(C,N){var z=C.sortIndex-N.sortIndex;return z!==0?z:C.id-N.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;e.unstable_now=function(){return u.now()}}else{var i=Date,o=i.now();e.unstable_now=function(){return i.now()-o}}var s=[],f=[],h=1,m=null,p=3,g=!1,w=!1,k=!1,F=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,a=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(C){for(var N=t(f);N!==null;){if(N.callback===null)r(f);else if(N.startTime<=C)r(f),N.sortIndex=N.expirationTime,n(s,N);else break;N=t(f)}}function v(C){if(k=!1,d(C),!w)if(t(s)!==null)w=!0,pl(E);else{var N=t(f);N!==null&&ml(v,N.startTime-C)}}function E(C,N){w=!1,k&&(k=!1,c(P),P=-1),g=!0;var z=p;try{for(d(N),m=t(s);m!==null&&(!(m.expirationTime>N)||C&&!xe());){var H=m.callback;if(typeof H=="function"){m.callback=null,p=m.priorityLevel;var X=H(m.expirationTime<=N);N=e.unstable_now(),typeof X=="function"?m.callback=X:m===t(s)&&r(s),d(N)}else r(s);m=t(s)}if(m!==null)var Jt=!0;else{var hn=t(f);hn!==null&&ml(v,hn.startTime-N),Jt=!1}return Jt}finally{m=null,p=z,g=!1}}var _=!1,x=null,P=-1,B=5,L=-1;function xe(){return!(e.unstable_now()-L<B)}function it(){if(x!==null){var C=e.unstable_now();L=C;var N=!0;try{N=x(!0,C)}finally{N?ot():(_=!1,x=null)}}else _=!1}var ot;if(typeof a=="function")ot=function(){a(it)};else if(typeof MessageChannel<"u"){var Ti=new MessageChannel,qa=Ti.port2;Ti.port1.onmessage=it,ot=function(){qa.postMessage(null)}}else ot=function(){F(it,0)};function pl(C){x=C,_||(_=!0,ot())}function ml(C,N){P=F(function(){C(e.unstable_now())},N)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(C){C.callback=null},e.unstable_continueExecution=function(){w||g||(w=!0,pl(E))},e.unstable_forceFrameRate=function(C){0>C||125<C?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):B=0<C?Math.floor(1e3/C):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_getFirstCallbackNode=function(){return t(s)},e.unstable_next=function(C){switch(p){case 1:case 2:case 3:var N=3;break;default:N=p}var z=p;p=N;try{return C()}finally{p=z}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(C,N){switch(C){case 1:case 2:case 3:case 4:case 5:break;default:C=3}var z=p;p=C;try{return N()}finally{p=z}},e.unstable_scheduleCallback=function(C,N,z){var H=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?H+z:H):z=H,C){case 1:var X=-1;break;case 2:X=250;break;case 5:X=1073741823;break;case 4:X=1e4;break;default:X=5e3}return X=z+X,C={id:h++,callback:N,priorityLevel:C,startTime:z,expirationTime:X,sortIndex:-1},z>H?(C.sortIndex=z,n(f,C),t(s)===null&&C===t(f)&&(k?(c(P),P=-1):k=!0,ml(v,z-H))):(C.sortIndex=X,n(s,C),w||g||(w=!0,pl(E))),C},e.unstable_shouldYield=xe,e.unstable_wrapCallback=function(C){var N=p;return function(){var z=p;p=N;try{return C.apply(this,arguments)}finally{p=z}}}})(qo);Jo.exports=qo;var vf=Jo.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var yf=Uu,ve=vf;function y(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t<arguments.length;t++)n+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+e+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var bo=new Set,Tt={};function Tn(e,n){Zn(e,n),Zn(e+"Capture",n)}function Zn(e,n){for(Tt[e]=n,e=0;e<n.length;e++)bo.add(n[e])}var He=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Bl=Object.prototype.hasOwnProperty,gf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Oi={},Di={};function wf(e){return Bl.call(Di,e)?!0:Bl.call(Oi,e)?!1:gf.test(e)?Di[e]=!0:(Oi[e]=!0,!1)}function kf(e,n,t,r){if(t!==null&&t.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Sf(e,n,t,r){if(n===null||typeof n>"u"||kf(e,n,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function oe(e,n,t,r,l,u,i){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=u,this.removeEmptyString=i}var b={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){b[e]=new oe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];b[n]=new oe(n,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){b[e]=new oe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){b[e]=new oe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){b[e]=new oe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){b[e]=new oe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){b[e]=new oe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){b[e]=new oe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){b[e]=new oe(e,5,!1,e.toLowerCase(),null,!1,!1)});var $u=/[\-:]([a-z])/g;function Vu(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var n=e.replace($u,Vu);b[n]=new oe(n,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace($u,Vu);b[n]=new oe(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace($u,Vu);b[n]=new oe(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){b[e]=new oe(e,1,!1,e.toLowerCase(),null,!1,!1)});b.xlinkHref=new oe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){b[e]=new oe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Au(e,n,t,r){var l=b.hasOwnProperty(n)?b[n]:null;(l!==null?l.type!==0:r||!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(Sf(n,t,l,r)&&(t=null),r||l===null?wf(n)&&(t===null?e.removeAttribute(n):e.setAttribute(n,""+t)):l.mustUseProperty?e[l.propertyName]=t===null?l.type===3?!1:"":t:(n=l.attributeName,r=l.attributeNamespace,t===null?e.removeAttribute(n):(l=l.type,t=l===3||l===4&&t===!0?"":""+t,r?e.setAttributeNS(r,n,t):e.setAttribute(n,t))))}var Ye=yf.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,er=Symbol.for("react.element"),Mn=Symbol.for("react.portal"),On=Symbol.for("react.fragment"),Bu=Symbol.for("react.strict_mode"),Hl=Symbol.for("react.profiler"),es=Symbol.for("react.provider"),ns=Symbol.for("react.context"),Hu=Symbol.for("react.forward_ref"),Wl=Symbol.for("react.suspense"),Ql=Symbol.for("react.suspense_list"),Wu=Symbol.for("react.memo"),Ge=Symbol.for("react.lazy"),ts=Symbol.for("react.offscreen"),Ii=Symbol.iterator;function st(e){return e===null||typeof e!="object"?null:(e=Ii&&e[Ii]||e["@@iterator"],typeof e=="function"?e:null)}var V=Object.assign,yl;function vt(e){if(yl===void 0)try{throw Error()}catch(t){var n=t.stack.trim().match(/\n( *(at )?)/);yl=n&&n[1]||""}return` +`+yl+e}var gl=!1;function wl(e,n){if(!e||gl)return"";gl=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n)if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(n,[])}catch(f){var r=f}Reflect.construct(e,[],n)}else{try{n.call()}catch(f){r=f}e.call(n.prototype)}else{try{throw Error()}catch(f){r=f}e()}}catch(f){if(f&&r&&typeof f.stack=="string"){for(var l=f.stack.split(` +`),u=r.stack.split(` +`),i=l.length-1,o=u.length-1;1<=i&&0<=o&&l[i]!==u[o];)o--;for(;1<=i&&0<=o;i--,o--)if(l[i]!==u[o]){if(i!==1||o!==1)do if(i--,o--,0>o||l[i]!==u[o]){var s=` +`+l[i].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}while(1<=i&&0<=o);break}}}finally{gl=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?vt(e):""}function Ef(e){switch(e.tag){case 5:return vt(e.type);case 16:return vt("Lazy");case 13:return vt("Suspense");case 19:return vt("SuspenseList");case 0:case 2:case 15:return e=wl(e.type,!1),e;case 11:return e=wl(e.type.render,!1),e;case 1:return e=wl(e.type,!0),e;default:return""}}function Kl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case On:return"Fragment";case Mn:return"Portal";case Hl:return"Profiler";case Bu:return"StrictMode";case Wl:return"Suspense";case Ql:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ns:return(e.displayName||"Context")+".Consumer";case es:return(e._context.displayName||"Context")+".Provider";case Hu:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Wu:return n=e.displayName||null,n!==null?n:Kl(e.type)||"Memo";case Ge:n=e._payload,e=e._init;try{return Kl(e(n))}catch{}}return null}function Cf(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Kl(n);case 8:return n===Bu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function fn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function rs(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function _f(e){var n=rs(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var l=t.get,u=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,u.call(this,i)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function nr(e){e._valueTracker||(e._valueTracker=_f(e))}function ls(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=rs(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function zr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Yl(e,n){var t=n.checked;return V({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function Fi(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=fn(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function us(e,n){n=n.checked,n!=null&&Au(e,"checked",n,!1)}function Xl(e,n){us(e,n);var t=fn(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?Gl(e,n.type,t):n.hasOwnProperty("defaultValue")&&Gl(e,n.type,fn(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function ji(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function Gl(e,n,t){(n!=="number"||zr(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var yt=Array.isArray;function Wn(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l<t.length;l++)n["$"+t[l]]=!0;for(t=0;t<e.length;t++)l=n.hasOwnProperty("$"+e[t].value),e[t].selected!==l&&(e[t].selected=l),l&&r&&(e[t].defaultSelected=!0)}else{for(t=""+fn(t),n=null,l=0;l<e.length;l++){if(e[l].value===t){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}n!==null||e[l].disabled||(n=e[l])}n!==null&&(n.selected=!0)}}function Zl(e,n){if(n.dangerouslySetInnerHTML!=null)throw Error(y(91));return V({},n,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Ui(e,n){var t=n.value;if(t==null){if(t=n.children,n=n.defaultValue,t!=null){if(n!=null)throw Error(y(92));if(yt(t)){if(1<t.length)throw Error(y(93));t=t[0]}n=t}n==null&&(n=""),t=n}e._wrapperState={initialValue:fn(t)}}function is(e,n){var t=fn(n.value),r=fn(n.defaultValue);t!=null&&(t=""+t,t!==e.value&&(e.value=t),n.defaultValue==null&&e.defaultValue!==t&&(e.defaultValue=t)),r!=null&&(e.defaultValue=""+r)}function $i(e){var n=e.textContent;n===e._wrapperState.initialValue&&n!==""&&n!==null&&(e.value=n)}function os(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Jl(e,n){return e==null||e==="http://www.w3.org/1999/xhtml"?os(n):e==="http://www.w3.org/2000/svg"&&n==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var tr,ss=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(n,t,r,l){MSApp.execUnsafeLocalFunction(function(){return e(n,t,r,l)})}:e}(function(e,n){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=n;else{for(tr=tr||document.createElement("div"),tr.innerHTML="<svg>"+n.valueOf().toString()+"</svg>",n=tr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function Lt(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var kt={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},xf=["Webkit","ms","Moz","O"];Object.keys(kt).forEach(function(e){xf.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),kt[n]=kt[e]})});function as(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||kt.hasOwnProperty(e)&&kt[e]?(""+n).trim():n+"px"}function fs(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,l=as(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}var Pf=V({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ql(e,n){if(n){if(Pf[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(y(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(y(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(y(61))}if(n.style!=null&&typeof n.style!="object")throw Error(y(62))}}function bl(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var eu=null;function Qu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var nu=null,Qn=null,Kn=null;function Vi(e){if(e=Gt(e)){if(typeof nu!="function")throw Error(y(280));var n=e.stateNode;n&&(n=tl(n),nu(e.stateNode,e.type,n))}}function cs(e){Qn?Kn?Kn.push(e):Kn=[e]:Qn=e}function ds(){if(Qn){var e=Qn,n=Kn;if(Kn=Qn=null,Vi(e),n)for(e=0;e<n.length;e++)Vi(n[e])}}function ps(e,n){return e(n)}function ms(){}var kl=!1;function hs(e,n,t){if(kl)return e(n,t);kl=!0;try{return ps(e,n,t)}finally{kl=!1,(Qn!==null||Kn!==null)&&(ms(),ds())}}function Rt(e,n){var t=e.stateNode;if(t===null)return null;var r=tl(t);if(r===null)return null;t=r[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(t&&typeof t!="function")throw Error(y(231,n,typeof t));return t}var tu=!1;if(He)try{var at={};Object.defineProperty(at,"passive",{get:function(){tu=!0}}),window.addEventListener("test",at,at),window.removeEventListener("test",at,at)}catch{tu=!1}function Nf(e,n,t,r,l,u,i,o,s){var f=Array.prototype.slice.call(arguments,3);try{n.apply(t,f)}catch(h){this.onError(h)}}var St=!1,Tr=null,Lr=!1,ru=null,zf={onError:function(e){St=!0,Tr=e}};function Tf(e,n,t,r,l,u,i,o,s){St=!1,Tr=null,Nf.apply(zf,arguments)}function Lf(e,n,t,r,l,u,i,o,s){if(Tf.apply(this,arguments),St){if(St){var f=Tr;St=!1,Tr=null}else throw Error(y(198));Lr||(Lr=!0,ru=f)}}function Ln(e){var n=e,t=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do n=e,n.flags&4098&&(t=n.return),e=n.return;while(e)}return n.tag===3?t:null}function vs(e){if(e.tag===13){var n=e.memoizedState;if(n===null&&(e=e.alternate,e!==null&&(n=e.memoizedState)),n!==null)return n.dehydrated}return null}function Ai(e){if(Ln(e)!==e)throw Error(y(188))}function Rf(e){var n=e.alternate;if(!n){if(n=Ln(e),n===null)throw Error(y(188));return n!==e?null:e}for(var t=e,r=n;;){var l=t.return;if(l===null)break;var u=l.alternate;if(u===null){if(r=l.return,r!==null){t=r;continue}break}if(l.child===u.child){for(u=l.child;u;){if(u===t)return Ai(l),e;if(u===r)return Ai(l),n;u=u.sibling}throw Error(y(188))}if(t.return!==r.return)t=l,r=u;else{for(var i=!1,o=l.child;o;){if(o===t){i=!0,t=l,r=u;break}if(o===r){i=!0,r=l,t=u;break}o=o.sibling}if(!i){for(o=u.child;o;){if(o===t){i=!0,t=u,r=l;break}if(o===r){i=!0,r=u,t=l;break}o=o.sibling}if(!i)throw Error(y(189))}}if(t.alternate!==r)throw Error(y(190))}if(t.tag!==3)throw Error(y(188));return t.stateNode.current===t?e:n}function ys(e){return e=Rf(e),e!==null?gs(e):null}function gs(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var n=gs(e);if(n!==null)return n;e=e.sibling}return null}var ws=ve.unstable_scheduleCallback,Bi=ve.unstable_cancelCallback,Mf=ve.unstable_shouldYield,Of=ve.unstable_requestPaint,W=ve.unstable_now,Df=ve.unstable_getCurrentPriorityLevel,Ku=ve.unstable_ImmediatePriority,ks=ve.unstable_UserBlockingPriority,Rr=ve.unstable_NormalPriority,If=ve.unstable_LowPriority,Ss=ve.unstable_IdlePriority,qr=null,Fe=null;function Ff(e){if(Fe&&typeof Fe.onCommitFiberRoot=="function")try{Fe.onCommitFiberRoot(qr,e,void 0,(e.current.flags&128)===128)}catch{}}var Le=Math.clz32?Math.clz32:$f,jf=Math.log,Uf=Math.LN2;function $f(e){return e>>>=0,e===0?32:31-(jf(e)/Uf|0)|0}var rr=64,lr=4194304;function gt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Mr(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,u=e.pingedLanes,i=t&268435455;if(i!==0){var o=i&~l;o!==0?r=gt(o):(u&=i,u!==0&&(r=gt(u)))}else i=t&~l,i!==0?r=gt(i):u!==0&&(r=gt(u));if(r===0)return 0;if(n!==0&&n!==r&&!(n&l)&&(l=r&-r,u=n&-n,l>=u||l===16&&(u&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0<n;)t=31-Le(n),l=1<<t,r|=e[t],n&=~l;return r}function Vf(e,n){switch(e){case 1:case 2:case 4:return n+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Af(e,n){for(var t=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,u=e.pendingLanes;0<u;){var i=31-Le(u),o=1<<i,s=l[i];s===-1?(!(o&t)||o&r)&&(l[i]=Vf(o,n)):s<=n&&(e.expiredLanes|=o),u&=~o}}function lu(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function Es(){var e=rr;return rr<<=1,!(rr&4194240)&&(rr=64),e}function Sl(e){for(var n=[],t=0;31>t;t++)n.push(e);return n}function Yt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Le(n),e[n]=t}function Bf(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<t;){var l=31-Le(t),u=1<<l;n[l]=0,r[l]=-1,e[l]=-1,t&=~u}}function Yu(e,n){var t=e.entangledLanes|=n;for(e=e.entanglements;t;){var r=31-Le(t),l=1<<r;l&n|e[r]&n&&(e[r]|=n),t&=~l}}var M=0;function Cs(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var _s,Xu,xs,Ps,Ns,uu=!1,ur=[],nn=null,tn=null,rn=null,Mt=new Map,Ot=new Map,Je=[],Hf="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Hi(e,n){switch(e){case"focusin":case"focusout":nn=null;break;case"dragenter":case"dragleave":tn=null;break;case"mouseover":case"mouseout":rn=null;break;case"pointerover":case"pointerout":Mt.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ot.delete(n.pointerId)}}function ft(e,n,t,r,l,u){return e===null||e.nativeEvent!==u?(e={blockedOn:n,domEventName:t,eventSystemFlags:r,nativeEvent:u,targetContainers:[l]},n!==null&&(n=Gt(n),n!==null&&Xu(n)),e):(e.eventSystemFlags|=r,n=e.targetContainers,l!==null&&n.indexOf(l)===-1&&n.push(l),e)}function Wf(e,n,t,r,l){switch(n){case"focusin":return nn=ft(nn,e,n,t,r,l),!0;case"dragenter":return tn=ft(tn,e,n,t,r,l),!0;case"mouseover":return rn=ft(rn,e,n,t,r,l),!0;case"pointerover":var u=l.pointerId;return Mt.set(u,ft(Mt.get(u)||null,e,n,t,r,l)),!0;case"gotpointercapture":return u=l.pointerId,Ot.set(u,ft(Ot.get(u)||null,e,n,t,r,l)),!0}return!1}function zs(e){var n=wn(e.target);if(n!==null){var t=Ln(n);if(t!==null){if(n=t.tag,n===13){if(n=vs(t),n!==null){e.blockedOn=n,Ns(e.priority,function(){xs(t)});return}}else if(n===3&&t.stateNode.current.memoizedState.isDehydrated){e.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}e.blockedOn=null}function gr(e){if(e.blockedOn!==null)return!1;for(var n=e.targetContainers;0<n.length;){var t=iu(e.domEventName,e.eventSystemFlags,n[0],e.nativeEvent);if(t===null){t=e.nativeEvent;var r=new t.constructor(t.type,t);eu=r,t.target.dispatchEvent(r),eu=null}else return n=Gt(t),n!==null&&Xu(n),e.blockedOn=t,!1;n.shift()}return!0}function Wi(e,n,t){gr(e)&&t.delete(n)}function Qf(){uu=!1,nn!==null&&gr(nn)&&(nn=null),tn!==null&&gr(tn)&&(tn=null),rn!==null&&gr(rn)&&(rn=null),Mt.forEach(Wi),Ot.forEach(Wi)}function ct(e,n){e.blockedOn===n&&(e.blockedOn=null,uu||(uu=!0,ve.unstable_scheduleCallback(ve.unstable_NormalPriority,Qf)))}function Dt(e){function n(l){return ct(l,e)}if(0<ur.length){ct(ur[0],e);for(var t=1;t<ur.length;t++){var r=ur[t];r.blockedOn===e&&(r.blockedOn=null)}}for(nn!==null&&ct(nn,e),tn!==null&&ct(tn,e),rn!==null&&ct(rn,e),Mt.forEach(n),Ot.forEach(n),t=0;t<Je.length;t++)r=Je[t],r.blockedOn===e&&(r.blockedOn=null);for(;0<Je.length&&(t=Je[0],t.blockedOn===null);)zs(t),t.blockedOn===null&&Je.shift()}var Yn=Ye.ReactCurrentBatchConfig,Or=!0;function Kf(e,n,t,r){var l=M,u=Yn.transition;Yn.transition=null;try{M=1,Gu(e,n,t,r)}finally{M=l,Yn.transition=u}}function Yf(e,n,t,r){var l=M,u=Yn.transition;Yn.transition=null;try{M=4,Gu(e,n,t,r)}finally{M=l,Yn.transition=u}}function Gu(e,n,t,r){if(Or){var l=iu(e,n,t,r);if(l===null)Rl(e,n,r,Dr,t),Hi(e,r);else if(Wf(l,e,n,t,r))r.stopPropagation();else if(Hi(e,r),n&4&&-1<Hf.indexOf(e)){for(;l!==null;){var u=Gt(l);if(u!==null&&_s(u),u=iu(e,n,t,r),u===null&&Rl(e,n,r,Dr,t),u===l)break;l=u}l!==null&&r.stopPropagation()}else Rl(e,n,r,null,t)}}var Dr=null;function iu(e,n,t,r){if(Dr=null,e=Qu(r),e=wn(e),e!==null)if(n=Ln(e),n===null)e=null;else if(t=n.tag,t===13){if(e=vs(n),e!==null)return e;e=null}else if(t===3){if(n.stateNode.current.memoizedState.isDehydrated)return n.tag===3?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null);return Dr=e,null}function Ts(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Df()){case Ku:return 1;case ks:return 4;case Rr:case If:return 16;case Ss:return 536870912;default:return 16}default:return 16}}var be=null,Zu=null,wr=null;function Ls(){if(wr)return wr;var e,n=Zu,t=n.length,r,l="value"in be?be.value:be.textContent,u=l.length;for(e=0;e<t&&n[e]===l[e];e++);var i=t-e;for(r=1;r<=i&&n[t-r]===l[u-r];r++);return wr=l.slice(e,1<r?1-r:void 0)}function kr(e){var n=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&n===13&&(e=13)):e=n,e===10&&(e=13),32<=e||e===13?e:0}function ir(){return!0}function Qi(){return!1}function ge(e){function n(t,r,l,u,i){this._reactName=t,this._targetInst=l,this.type=r,this.nativeEvent=u,this.target=i,this.currentTarget=null;for(var o in e)e.hasOwnProperty(o)&&(t=e[o],this[o]=t?t(u):u[o]);return this.isDefaultPrevented=(u.defaultPrevented!=null?u.defaultPrevented:u.returnValue===!1)?ir:Qi,this.isPropagationStopped=Qi,this}return V(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=ir)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=ir)},persist:function(){},isPersistent:ir}),n}var lt={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ju=ge(lt),Xt=V({},lt,{view:0,detail:0}),Xf=ge(Xt),El,Cl,dt,br=V({},Xt,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:qu,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==dt&&(dt&&e.type==="mousemove"?(El=e.screenX-dt.screenX,Cl=e.screenY-dt.screenY):Cl=El=0,dt=e),El)},movementY:function(e){return"movementY"in e?e.movementY:Cl}}),Ki=ge(br),Gf=V({},br,{dataTransfer:0}),Zf=ge(Gf),Jf=V({},Xt,{relatedTarget:0}),_l=ge(Jf),qf=V({},lt,{animationName:0,elapsedTime:0,pseudoElement:0}),bf=ge(qf),ec=V({},lt,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),nc=ge(ec),tc=V({},lt,{data:0}),Yi=ge(tc),rc={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},lc={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},uc={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ic(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):(e=uc[e])?!!n[e]:!1}function qu(){return ic}var oc=V({},Xt,{key:function(e){if(e.key){var n=rc[e.key]||e.key;if(n!=="Unidentified")return n}return e.type==="keypress"?(e=kr(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?lc[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:qu,charCode:function(e){return e.type==="keypress"?kr(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?kr(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),sc=ge(oc),ac=V({},br,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Xi=ge(ac),fc=V({},Xt,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:qu}),cc=ge(fc),dc=V({},lt,{propertyName:0,elapsedTime:0,pseudoElement:0}),pc=ge(dc),mc=V({},br,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),hc=ge(mc),vc=[9,13,27,32],bu=He&&"CompositionEvent"in window,Et=null;He&&"documentMode"in document&&(Et=document.documentMode);var yc=He&&"TextEvent"in window&&!Et,Rs=He&&(!bu||Et&&8<Et&&11>=Et),Gi=" ",Zi=!1;function Ms(e,n){switch(e){case"keyup":return vc.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Os(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Dn=!1;function gc(e,n){switch(e){case"compositionend":return Os(n);case"keypress":return n.which!==32?null:(Zi=!0,Gi);case"textInput":return e=n.data,e===Gi&&Zi?null:e;default:return null}}function wc(e,n){if(Dn)return e==="compositionend"||!bu&&Ms(e,n)?(e=Ls(),wr=Zu=be=null,Dn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return Rs&&n.locale!=="ko"?null:n.data;default:return null}}var kc={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ji(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n==="input"?!!kc[e.type]:n==="textarea"}function Ds(e,n,t,r){cs(r),n=Ir(n,"onChange"),0<n.length&&(t=new Ju("onChange","change",null,t,r),e.push({event:t,listeners:n}))}var Ct=null,It=null;function Sc(e){Qs(e,0)}function el(e){var n=jn(e);if(ls(n))return e}function Ec(e,n){if(e==="change")return n}var Is=!1;if(He){var xl;if(He){var Pl="oninput"in document;if(!Pl){var qi=document.createElement("div");qi.setAttribute("oninput","return;"),Pl=typeof qi.oninput=="function"}xl=Pl}else xl=!1;Is=xl&&(!document.documentMode||9<document.documentMode)}function bi(){Ct&&(Ct.detachEvent("onpropertychange",Fs),It=Ct=null)}function Fs(e){if(e.propertyName==="value"&&el(It)){var n=[];Ds(n,It,e,Qu(e)),hs(Sc,n)}}function Cc(e,n,t){e==="focusin"?(bi(),Ct=n,It=t,Ct.attachEvent("onpropertychange",Fs)):e==="focusout"&&bi()}function _c(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return el(It)}function xc(e,n){if(e==="click")return el(n)}function Pc(e,n){if(e==="input"||e==="change")return el(n)}function Nc(e,n){return e===n&&(e!==0||1/e===1/n)||e!==e&&n!==n}var Me=typeof Object.is=="function"?Object.is:Nc;function Ft(e,n){if(Me(e,n))return!0;if(typeof e!="object"||e===null||typeof n!="object"||n===null)return!1;var t=Object.keys(e),r=Object.keys(n);if(t.length!==r.length)return!1;for(r=0;r<t.length;r++){var l=t[r];if(!Bl.call(n,l)||!Me(e[l],n[l]))return!1}return!0}function eo(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function no(e,n){var t=eo(e);e=0;for(var r;t;){if(t.nodeType===3){if(r=e+t.textContent.length,e<=n&&r>=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=eo(t)}}function js(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?js(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function Us(){for(var e=window,n=zr();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=zr(e.document)}return n}function ei(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function zc(e){var n=Us(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&js(t.ownerDocument.documentElement,t)){if(r!==null&&ei(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var l=t.textContent.length,u=Math.min(r.start,l);r=r.end===void 0?u:Math.min(r.end,l),!e.extend&&u>r&&(l=r,r=u,u=l),l=no(t,u);var i=no(t,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(n=n.createRange(),n.setStart(l.node,l.offset),e.removeAllRanges(),u>r?(e.addRange(n),e.extend(i.node,i.offset)):(n.setEnd(i.node,i.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<n.length;t++)e=n[t],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Tc=He&&"documentMode"in document&&11>=document.documentMode,In=null,ou=null,_t=null,su=!1;function to(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;su||In==null||In!==zr(r)||(r=In,"selectionStart"in r&&ei(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),_t&&Ft(_t,r)||(_t=r,r=Ir(ou,"onSelect"),0<r.length&&(n=new Ju("onSelect","select",null,n,t),e.push({event:n,listeners:r}),n.target=In)))}function or(e,n){var t={};return t[e.toLowerCase()]=n.toLowerCase(),t["Webkit"+e]="webkit"+n,t["Moz"+e]="moz"+n,t}var Fn={animationend:or("Animation","AnimationEnd"),animationiteration:or("Animation","AnimationIteration"),animationstart:or("Animation","AnimationStart"),transitionend:or("Transition","TransitionEnd")},Nl={},$s={};He&&($s=document.createElement("div").style,"AnimationEvent"in window||(delete Fn.animationend.animation,delete Fn.animationiteration.animation,delete Fn.animationstart.animation),"TransitionEvent"in window||delete Fn.transitionend.transition);function nl(e){if(Nl[e])return Nl[e];if(!Fn[e])return e;var n=Fn[e],t;for(t in n)if(n.hasOwnProperty(t)&&t in $s)return Nl[e]=n[t];return e}var Vs=nl("animationend"),As=nl("animationiteration"),Bs=nl("animationstart"),Hs=nl("transitionend"),Ws=new Map,ro="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function dn(e,n){Ws.set(e,n),Tn(n,[e])}for(var zl=0;zl<ro.length;zl++){var Tl=ro[zl],Lc=Tl.toLowerCase(),Rc=Tl[0].toUpperCase()+Tl.slice(1);dn(Lc,"on"+Rc)}dn(Vs,"onAnimationEnd");dn(As,"onAnimationIteration");dn(Bs,"onAnimationStart");dn("dblclick","onDoubleClick");dn("focusin","onFocus");dn("focusout","onBlur");dn(Hs,"onTransitionEnd");Zn("onMouseEnter",["mouseout","mouseover"]);Zn("onMouseLeave",["mouseout","mouseover"]);Zn("onPointerEnter",["pointerout","pointerover"]);Zn("onPointerLeave",["pointerout","pointerover"]);Tn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Tn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Tn("onBeforeInput",["compositionend","keypress","textInput","paste"]);Tn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Tn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Tn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var wt="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Mc=new Set("cancel close invalid load scroll toggle".split(" ").concat(wt));function lo(e,n,t){var r=e.type||"unknown-event";e.currentTarget=t,Lf(r,n,void 0,e),e.currentTarget=null}function Qs(e,n){n=(n&4)!==0;for(var t=0;t<e.length;t++){var r=e[t],l=r.event;r=r.listeners;e:{var u=void 0;if(n)for(var i=r.length-1;0<=i;i--){var o=r[i],s=o.instance,f=o.currentTarget;if(o=o.listener,s!==u&&l.isPropagationStopped())break e;lo(l,o,f),u=s}else for(i=0;i<r.length;i++){if(o=r[i],s=o.instance,f=o.currentTarget,o=o.listener,s!==u&&l.isPropagationStopped())break e;lo(l,o,f),u=s}}}if(Lr)throw e=ru,Lr=!1,ru=null,e}function D(e,n){var t=n[pu];t===void 0&&(t=n[pu]=new Set);var r=e+"__bubble";t.has(r)||(Ks(n,e,2,!1),t.add(r))}function Ll(e,n,t){var r=0;n&&(r|=4),Ks(t,e,r,n)}var sr="_reactListening"+Math.random().toString(36).slice(2);function jt(e){if(!e[sr]){e[sr]=!0,bo.forEach(function(t){t!=="selectionchange"&&(Mc.has(t)||Ll(t,!1,e),Ll(t,!0,e))});var n=e.nodeType===9?e:e.ownerDocument;n===null||n[sr]||(n[sr]=!0,Ll("selectionchange",!1,n))}}function Ks(e,n,t,r){switch(Ts(n)){case 1:var l=Kf;break;case 4:l=Yf;break;default:l=Gu}t=l.bind(null,n,t,e),l=void 0,!tu||n!=="touchstart"&&n!=="touchmove"&&n!=="wheel"||(l=!0),r?l!==void 0?e.addEventListener(n,t,{capture:!0,passive:l}):e.addEventListener(n,t,!0):l!==void 0?e.addEventListener(n,t,{passive:l}):e.addEventListener(n,t,!1)}function Rl(e,n,t,r,l){var u=r;if(!(n&1)&&!(n&2)&&r!==null)e:for(;;){if(r===null)return;var i=r.tag;if(i===3||i===4){var o=r.stateNode.containerInfo;if(o===l||o.nodeType===8&&o.parentNode===l)break;if(i===4)for(i=r.return;i!==null;){var s=i.tag;if((s===3||s===4)&&(s=i.stateNode.containerInfo,s===l||s.nodeType===8&&s.parentNode===l))return;i=i.return}for(;o!==null;){if(i=wn(o),i===null)return;if(s=i.tag,s===5||s===6){r=u=i;continue e}o=o.parentNode}}r=r.return}hs(function(){var f=u,h=Qu(t),m=[];e:{var p=Ws.get(e);if(p!==void 0){var g=Ju,w=e;switch(e){case"keypress":if(kr(t)===0)break e;case"keydown":case"keyup":g=sc;break;case"focusin":w="focus",g=_l;break;case"focusout":w="blur",g=_l;break;case"beforeblur":case"afterblur":g=_l;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":g=Ki;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":g=Zf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":g=cc;break;case Vs:case As:case Bs:g=bf;break;case Hs:g=pc;break;case"scroll":g=Xf;break;case"wheel":g=hc;break;case"copy":case"cut":case"paste":g=nc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":g=Xi}var k=(n&4)!==0,F=!k&&e==="scroll",c=k?p!==null?p+"Capture":null:p;k=[];for(var a=f,d;a!==null;){d=a;var v=d.stateNode;if(d.tag===5&&v!==null&&(d=v,c!==null&&(v=Rt(a,c),v!=null&&k.push(Ut(a,v,d)))),F)break;a=a.return}0<k.length&&(p=new g(p,w,null,t,h),m.push({event:p,listeners:k}))}}if(!(n&7)){e:{if(p=e==="mouseover"||e==="pointerover",g=e==="mouseout"||e==="pointerout",p&&t!==eu&&(w=t.relatedTarget||t.fromElement)&&(wn(w)||w[We]))break e;if((g||p)&&(p=h.window===h?h:(p=h.ownerDocument)?p.defaultView||p.parentWindow:window,g?(w=t.relatedTarget||t.toElement,g=f,w=w?wn(w):null,w!==null&&(F=Ln(w),w!==F||w.tag!==5&&w.tag!==6)&&(w=null)):(g=null,w=f),g!==w)){if(k=Ki,v="onMouseLeave",c="onMouseEnter",a="mouse",(e==="pointerout"||e==="pointerover")&&(k=Xi,v="onPointerLeave",c="onPointerEnter",a="pointer"),F=g==null?p:jn(g),d=w==null?p:jn(w),p=new k(v,a+"leave",g,t,h),p.target=F,p.relatedTarget=d,v=null,wn(h)===f&&(k=new k(c,a+"enter",w,t,h),k.target=d,k.relatedTarget=F,v=k),F=v,g&&w)n:{for(k=g,c=w,a=0,d=k;d;d=Rn(d))a++;for(d=0,v=c;v;v=Rn(v))d++;for(;0<a-d;)k=Rn(k),a--;for(;0<d-a;)c=Rn(c),d--;for(;a--;){if(k===c||c!==null&&k===c.alternate)break n;k=Rn(k),c=Rn(c)}k=null}else k=null;g!==null&&uo(m,p,g,k,!1),w!==null&&F!==null&&uo(m,F,w,k,!0)}}e:{if(p=f?jn(f):window,g=p.nodeName&&p.nodeName.toLowerCase(),g==="select"||g==="input"&&p.type==="file")var E=Ec;else if(Ji(p))if(Is)E=Pc;else{E=_c;var _=Cc}else(g=p.nodeName)&&g.toLowerCase()==="input"&&(p.type==="checkbox"||p.type==="radio")&&(E=xc);if(E&&(E=E(e,f))){Ds(m,E,t,h);break e}_&&_(e,p,f),e==="focusout"&&(_=p._wrapperState)&&_.controlled&&p.type==="number"&&Gl(p,"number",p.value)}switch(_=f?jn(f):window,e){case"focusin":(Ji(_)||_.contentEditable==="true")&&(In=_,ou=f,_t=null);break;case"focusout":_t=ou=In=null;break;case"mousedown":su=!0;break;case"contextmenu":case"mouseup":case"dragend":su=!1,to(m,t,h);break;case"selectionchange":if(Tc)break;case"keydown":case"keyup":to(m,t,h)}var x;if(bu)e:{switch(e){case"compositionstart":var P="onCompositionStart";break e;case"compositionend":P="onCompositionEnd";break e;case"compositionupdate":P="onCompositionUpdate";break e}P=void 0}else Dn?Ms(e,t)&&(P="onCompositionEnd"):e==="keydown"&&t.keyCode===229&&(P="onCompositionStart");P&&(Rs&&t.locale!=="ko"&&(Dn||P!=="onCompositionStart"?P==="onCompositionEnd"&&Dn&&(x=Ls()):(be=h,Zu="value"in be?be.value:be.textContent,Dn=!0)),_=Ir(f,P),0<_.length&&(P=new Yi(P,e,null,t,h),m.push({event:P,listeners:_}),x?P.data=x:(x=Os(t),x!==null&&(P.data=x)))),(x=yc?gc(e,t):wc(e,t))&&(f=Ir(f,"onBeforeInput"),0<f.length&&(h=new Yi("onBeforeInput","beforeinput",null,t,h),m.push({event:h,listeners:f}),h.data=x))}Qs(m,n)})}function Ut(e,n,t){return{instance:e,listener:n,currentTarget:t}}function Ir(e,n){for(var t=n+"Capture",r=[];e!==null;){var l=e,u=l.stateNode;l.tag===5&&u!==null&&(l=u,u=Rt(e,t),u!=null&&r.unshift(Ut(e,u,l)),u=Rt(e,n),u!=null&&r.push(Ut(e,u,l))),e=e.return}return r}function Rn(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function uo(e,n,t,r,l){for(var u=n._reactName,i=[];t!==null&&t!==r;){var o=t,s=o.alternate,f=o.stateNode;if(s!==null&&s===r)break;o.tag===5&&f!==null&&(o=f,l?(s=Rt(t,u),s!=null&&i.unshift(Ut(t,s,o))):l||(s=Rt(t,u),s!=null&&i.push(Ut(t,s,o)))),t=t.return}i.length!==0&&e.push({event:n,listeners:i})}var Oc=/\r\n?/g,Dc=/\u0000|\uFFFD/g;function io(e){return(typeof e=="string"?e:""+e).replace(Oc,` +`).replace(Dc,"")}function ar(e,n,t){if(n=io(n),io(e)!==n&&t)throw Error(y(425))}function Fr(){}var au=null,fu=null;function cu(e,n){return e==="textarea"||e==="noscript"||typeof n.children=="string"||typeof n.children=="number"||typeof n.dangerouslySetInnerHTML=="object"&&n.dangerouslySetInnerHTML!==null&&n.dangerouslySetInnerHTML.__html!=null}var du=typeof setTimeout=="function"?setTimeout:void 0,Ic=typeof clearTimeout=="function"?clearTimeout:void 0,oo=typeof Promise=="function"?Promise:void 0,Fc=typeof queueMicrotask=="function"?queueMicrotask:typeof oo<"u"?function(e){return oo.resolve(null).then(e).catch(jc)}:du;function jc(e){setTimeout(function(){throw e})}function Ml(e,n){var t=n,r=0;do{var l=t.nextSibling;if(e.removeChild(t),l&&l.nodeType===8)if(t=l.data,t==="/$"){if(r===0){e.removeChild(l),Dt(n);return}r--}else t!=="$"&&t!=="$?"&&t!=="$!"||r++;t=l}while(t);Dt(n)}function ln(e){for(;e!=null;e=e.nextSibling){var n=e.nodeType;if(n===1||n===3)break;if(n===8){if(n=e.data,n==="$"||n==="$!"||n==="$?")break;if(n==="/$")return null}}return e}function so(e){e=e.previousSibling;for(var n=0;e;){if(e.nodeType===8){var t=e.data;if(t==="$"||t==="$!"||t==="$?"){if(n===0)return e;n--}else t==="/$"&&n++}e=e.previousSibling}return null}var ut=Math.random().toString(36).slice(2),Ie="__reactFiber$"+ut,$t="__reactProps$"+ut,We="__reactContainer$"+ut,pu="__reactEvents$"+ut,Uc="__reactListeners$"+ut,$c="__reactHandles$"+ut;function wn(e){var n=e[Ie];if(n)return n;for(var t=e.parentNode;t;){if(n=t[We]||t[Ie]){if(t=n.alternate,n.child!==null||t!==null&&t.child!==null)for(e=so(e);e!==null;){if(t=e[Ie])return t;e=so(e)}return n}e=t,t=e.parentNode}return null}function Gt(e){return e=e[Ie]||e[We],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function jn(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(y(33))}function tl(e){return e[$t]||null}var mu=[],Un=-1;function pn(e){return{current:e}}function I(e){0>Un||(e.current=mu[Un],mu[Un]=null,Un--)}function O(e,n){Un++,mu[Un]=e.current,e.current=n}var cn={},re=pn(cn),fe=pn(!1),_n=cn;function Jn(e,n){var t=e.type.contextTypes;if(!t)return cn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},u;for(u in t)l[u]=n[u];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function ce(e){return e=e.childContextTypes,e!=null}function jr(){I(fe),I(re)}function ao(e,n,t){if(re.current!==cn)throw Error(y(168));O(re,n),O(fe,t)}function Ys(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(y(108,Cf(e)||"Unknown",l));return V({},t,r)}function Ur(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||cn,_n=re.current,O(re,e),O(fe,fe.current),!0}function fo(e,n,t){var r=e.stateNode;if(!r)throw Error(y(169));t?(e=Ys(e,n,_n),r.__reactInternalMemoizedMergedChildContext=e,I(fe),I(re),O(re,e)):I(fe),O(fe,t)}var $e=null,rl=!1,Ol=!1;function Xs(e){$e===null?$e=[e]:$e.push(e)}function Vc(e){rl=!0,Xs(e)}function mn(){if(!Ol&&$e!==null){Ol=!0;var e=0,n=M;try{var t=$e;for(M=1;e<t.length;e++){var r=t[e];do r=r(!0);while(r!==null)}$e=null,rl=!1}catch(l){throw $e!==null&&($e=$e.slice(e+1)),ws(Ku,mn),l}finally{M=n,Ol=!1}}return null}var $n=[],Vn=0,$r=null,Vr=0,we=[],ke=0,xn=null,Ve=1,Ae="";function yn(e,n){$n[Vn++]=Vr,$n[Vn++]=$r,$r=e,Vr=n}function Gs(e,n,t){we[ke++]=Ve,we[ke++]=Ae,we[ke++]=xn,xn=e;var r=Ve;e=Ae;var l=32-Le(r)-1;r&=~(1<<l),t+=1;var u=32-Le(n)+l;if(30<u){var i=l-l%5;u=(r&(1<<i)-1).toString(32),r>>=i,l-=i,Ve=1<<32-Le(n)+l|t<<l|r,Ae=u+e}else Ve=1<<u|t<<l|r,Ae=e}function ni(e){e.return!==null&&(yn(e,1),Gs(e,1,0))}function ti(e){for(;e===$r;)$r=$n[--Vn],$n[Vn]=null,Vr=$n[--Vn],$n[Vn]=null;for(;e===xn;)xn=we[--ke],we[ke]=null,Ae=we[--ke],we[ke]=null,Ve=we[--ke],we[ke]=null}var he=null,me=null,j=!1,Te=null;function Zs(e,n){var t=Se(5,null,null,0);t.elementType="DELETED",t.stateNode=n,t.return=e,n=e.deletions,n===null?(e.deletions=[t],e.flags|=16):n.push(t)}function co(e,n){switch(e.tag){case 5:var t=e.type;return n=n.nodeType!==1||t.toLowerCase()!==n.nodeName.toLowerCase()?null:n,n!==null?(e.stateNode=n,he=e,me=ln(n.firstChild),!0):!1;case 6:return n=e.pendingProps===""||n.nodeType!==3?null:n,n!==null?(e.stateNode=n,he=e,me=null,!0):!1;case 13:return n=n.nodeType!==8?null:n,n!==null?(t=xn!==null?{id:Ve,overflow:Ae}:null,e.memoizedState={dehydrated:n,treeContext:t,retryLane:1073741824},t=Se(18,null,null,0),t.stateNode=n,t.return=e,e.child=t,he=e,me=null,!0):!1;default:return!1}}function hu(e){return(e.mode&1)!==0&&(e.flags&128)===0}function vu(e){if(j){var n=me;if(n){var t=n;if(!co(e,n)){if(hu(e))throw Error(y(418));n=ln(t.nextSibling);var r=he;n&&co(e,n)?Zs(r,t):(e.flags=e.flags&-4097|2,j=!1,he=e)}}else{if(hu(e))throw Error(y(418));e.flags=e.flags&-4097|2,j=!1,he=e}}}function po(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;he=e}function fr(e){if(e!==he)return!1;if(!j)return po(e),j=!0,!1;var n;if((n=e.tag!==3)&&!(n=e.tag!==5)&&(n=e.type,n=n!=="head"&&n!=="body"&&!cu(e.type,e.memoizedProps)),n&&(n=me)){if(hu(e))throw Js(),Error(y(418));for(;n;)Zs(e,n),n=ln(n.nextSibling)}if(po(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(y(317));e:{for(e=e.nextSibling,n=0;e;){if(e.nodeType===8){var t=e.data;if(t==="/$"){if(n===0){me=ln(e.nextSibling);break e}n--}else t!=="$"&&t!=="$!"&&t!=="$?"||n++}e=e.nextSibling}me=null}}else me=he?ln(e.stateNode.nextSibling):null;return!0}function Js(){for(var e=me;e;)e=ln(e.nextSibling)}function qn(){me=he=null,j=!1}function ri(e){Te===null?Te=[e]:Te.push(e)}var Ac=Ye.ReactCurrentBatchConfig;function pt(e,n,t){if(e=t.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(y(309));var r=t.stateNode}if(!r)throw Error(y(147,e));var l=r,u=""+e;return n!==null&&n.ref!==null&&typeof n.ref=="function"&&n.ref._stringRef===u?n.ref:(n=function(i){var o=l.refs;i===null?delete o[u]:o[u]=i},n._stringRef=u,n)}if(typeof e!="string")throw Error(y(284));if(!t._owner)throw Error(y(290,e))}return e}function cr(e,n){throw e=Object.prototype.toString.call(n),Error(y(31,e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e))}function mo(e){var n=e._init;return n(e._payload)}function qs(e){function n(c,a){if(e){var d=c.deletions;d===null?(c.deletions=[a],c.flags|=16):d.push(a)}}function t(c,a){if(!e)return null;for(;a!==null;)n(c,a),a=a.sibling;return null}function r(c,a){for(c=new Map;a!==null;)a.key!==null?c.set(a.key,a):c.set(a.index,a),a=a.sibling;return c}function l(c,a){return c=an(c,a),c.index=0,c.sibling=null,c}function u(c,a,d){return c.index=d,e?(d=c.alternate,d!==null?(d=d.index,d<a?(c.flags|=2,a):d):(c.flags|=2,a)):(c.flags|=1048576,a)}function i(c){return e&&c.alternate===null&&(c.flags|=2),c}function o(c,a,d,v){return a===null||a.tag!==6?(a=Vl(d,c.mode,v),a.return=c,a):(a=l(a,d),a.return=c,a)}function s(c,a,d,v){var E=d.type;return E===On?h(c,a,d.props.children,v,d.key):a!==null&&(a.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Ge&&mo(E)===a.type)?(v=l(a,d.props),v.ref=pt(c,a,d),v.return=c,v):(v=Nr(d.type,d.key,d.props,null,c.mode,v),v.ref=pt(c,a,d),v.return=c,v)}function f(c,a,d,v){return a===null||a.tag!==4||a.stateNode.containerInfo!==d.containerInfo||a.stateNode.implementation!==d.implementation?(a=Al(d,c.mode,v),a.return=c,a):(a=l(a,d.children||[]),a.return=c,a)}function h(c,a,d,v,E){return a===null||a.tag!==7?(a=Cn(d,c.mode,v,E),a.return=c,a):(a=l(a,d),a.return=c,a)}function m(c,a,d){if(typeof a=="string"&&a!==""||typeof a=="number")return a=Vl(""+a,c.mode,d),a.return=c,a;if(typeof a=="object"&&a!==null){switch(a.$$typeof){case er:return d=Nr(a.type,a.key,a.props,null,c.mode,d),d.ref=pt(c,null,a),d.return=c,d;case Mn:return a=Al(a,c.mode,d),a.return=c,a;case Ge:var v=a._init;return m(c,v(a._payload),d)}if(yt(a)||st(a))return a=Cn(a,c.mode,d,null),a.return=c,a;cr(c,a)}return null}function p(c,a,d,v){var E=a!==null?a.key:null;if(typeof d=="string"&&d!==""||typeof d=="number")return E!==null?null:o(c,a,""+d,v);if(typeof d=="object"&&d!==null){switch(d.$$typeof){case er:return d.key===E?s(c,a,d,v):null;case Mn:return d.key===E?f(c,a,d,v):null;case Ge:return E=d._init,p(c,a,E(d._payload),v)}if(yt(d)||st(d))return E!==null?null:h(c,a,d,v,null);cr(c,d)}return null}function g(c,a,d,v,E){if(typeof v=="string"&&v!==""||typeof v=="number")return c=c.get(d)||null,o(a,c,""+v,E);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case er:return c=c.get(v.key===null?d:v.key)||null,s(a,c,v,E);case Mn:return c=c.get(v.key===null?d:v.key)||null,f(a,c,v,E);case Ge:var _=v._init;return g(c,a,d,_(v._payload),E)}if(yt(v)||st(v))return c=c.get(d)||null,h(a,c,v,E,null);cr(a,v)}return null}function w(c,a,d,v){for(var E=null,_=null,x=a,P=a=0,B=null;x!==null&&P<d.length;P++){x.index>P?(B=x,x=null):B=x.sibling;var L=p(c,x,d[P],v);if(L===null){x===null&&(x=B);break}e&&x&&L.alternate===null&&n(c,x),a=u(L,a,P),_===null?E=L:_.sibling=L,_=L,x=B}if(P===d.length)return t(c,x),j&&yn(c,P),E;if(x===null){for(;P<d.length;P++)x=m(c,d[P],v),x!==null&&(a=u(x,a,P),_===null?E=x:_.sibling=x,_=x);return j&&yn(c,P),E}for(x=r(c,x);P<d.length;P++)B=g(x,c,P,d[P],v),B!==null&&(e&&B.alternate!==null&&x.delete(B.key===null?P:B.key),a=u(B,a,P),_===null?E=B:_.sibling=B,_=B);return e&&x.forEach(function(xe){return n(c,xe)}),j&&yn(c,P),E}function k(c,a,d,v){var E=st(d);if(typeof E!="function")throw Error(y(150));if(d=E.call(d),d==null)throw Error(y(151));for(var _=E=null,x=a,P=a=0,B=null,L=d.next();x!==null&&!L.done;P++,L=d.next()){x.index>P?(B=x,x=null):B=x.sibling;var xe=p(c,x,L.value,v);if(xe===null){x===null&&(x=B);break}e&&x&&xe.alternate===null&&n(c,x),a=u(xe,a,P),_===null?E=xe:_.sibling=xe,_=xe,x=B}if(L.done)return t(c,x),j&&yn(c,P),E;if(x===null){for(;!L.done;P++,L=d.next())L=m(c,L.value,v),L!==null&&(a=u(L,a,P),_===null?E=L:_.sibling=L,_=L);return j&&yn(c,P),E}for(x=r(c,x);!L.done;P++,L=d.next())L=g(x,c,P,L.value,v),L!==null&&(e&&L.alternate!==null&&x.delete(L.key===null?P:L.key),a=u(L,a,P),_===null?E=L:_.sibling=L,_=L);return e&&x.forEach(function(it){return n(c,it)}),j&&yn(c,P),E}function F(c,a,d,v){if(typeof d=="object"&&d!==null&&d.type===On&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case er:e:{for(var E=d.key,_=a;_!==null;){if(_.key===E){if(E=d.type,E===On){if(_.tag===7){t(c,_.sibling),a=l(_,d.props.children),a.return=c,c=a;break e}}else if(_.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Ge&&mo(E)===_.type){t(c,_.sibling),a=l(_,d.props),a.ref=pt(c,_,d),a.return=c,c=a;break e}t(c,_);break}else n(c,_);_=_.sibling}d.type===On?(a=Cn(d.props.children,c.mode,v,d.key),a.return=c,c=a):(v=Nr(d.type,d.key,d.props,null,c.mode,v),v.ref=pt(c,a,d),v.return=c,c=v)}return i(c);case Mn:e:{for(_=d.key;a!==null;){if(a.key===_)if(a.tag===4&&a.stateNode.containerInfo===d.containerInfo&&a.stateNode.implementation===d.implementation){t(c,a.sibling),a=l(a,d.children||[]),a.return=c,c=a;break e}else{t(c,a);break}else n(c,a);a=a.sibling}a=Al(d,c.mode,v),a.return=c,c=a}return i(c);case Ge:return _=d._init,F(c,a,_(d._payload),v)}if(yt(d))return w(c,a,d,v);if(st(d))return k(c,a,d,v);cr(c,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,a!==null&&a.tag===6?(t(c,a.sibling),a=l(a,d),a.return=c,c=a):(t(c,a),a=Vl(d,c.mode,v),a.return=c,c=a),i(c)):t(c,a)}return F}var bn=qs(!0),bs=qs(!1),Ar=pn(null),Br=null,An=null,li=null;function ui(){li=An=Br=null}function ii(e){var n=Ar.current;I(Ar),e._currentValue=n}function yu(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function Xn(e,n){Br=e,li=An=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(ae=!0),e.firstContext=null)}function Ce(e){var n=e._currentValue;if(li!==e)if(e={context:e,memoizedValue:n,next:null},An===null){if(Br===null)throw Error(y(308));An=e,Br.dependencies={lanes:0,firstContext:e}}else An=An.next=e;return n}var kn=null;function oi(e){kn===null?kn=[e]:kn.push(e)}function ea(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,oi(n)):(t.next=l.next,l.next=t),n.interleaved=t,Qe(e,r)}function Qe(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Ze=!1;function si(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function na(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Be(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function un(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,R&2){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,Qe(e,t)}return l=r.interleaved,l===null?(n.next=n,oi(r)):(n.next=l.next,l.next=n),r.interleaved=n,Qe(e,t)}function Sr(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Yu(e,t)}}function ho(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,u=null;if(t=t.firstBaseUpdate,t!==null){do{var i={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};u===null?l=u=i:u=u.next=i,t=t.next}while(t!==null);u===null?l=u=n:u=u.next=n}else l=u=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:u,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function Hr(e,n,t,r){var l=e.updateQueue;Ze=!1;var u=l.firstBaseUpdate,i=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var s=o,f=s.next;s.next=null,i===null?u=f:i.next=f,i=s;var h=e.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==i&&(o===null?h.firstBaseUpdate=f:o.next=f,h.lastBaseUpdate=s))}if(u!==null){var m=l.baseState;i=0,h=f=s=null,o=u;do{var p=o.lane,g=o.eventTime;if((r&p)===p){h!==null&&(h=h.next={eventTime:g,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var w=e,k=o;switch(p=n,g=t,k.tag){case 1:if(w=k.payload,typeof w=="function"){m=w.call(g,m,p);break e}m=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=k.payload,p=typeof w=="function"?w.call(g,m,p):w,p==null)break e;m=V({},m,p);break e;case 2:Ze=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,p=l.effects,p===null?l.effects=[o]:p.push(o))}else g={eventTime:g,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(f=h=g,s=m):h=h.next=g,i|=p;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;p=o,o=p.next,p.next=null,l.lastBaseUpdate=p,l.shared.pending=null}}while(!0);if(h===null&&(s=m),l.baseState=s,l.firstBaseUpdate=f,l.lastBaseUpdate=h,n=l.shared.interleaved,n!==null){l=n;do i|=l.lane,l=l.next;while(l!==n)}else u===null&&(l.shared.lanes=0);Nn|=i,e.lanes=i,e.memoizedState=m}}function vo(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;n<e.length;n++){var r=e[n],l=r.callback;if(l!==null){if(r.callback=null,r=t,typeof l!="function")throw Error(y(191,l));l.call(r)}}}var Zt={},je=pn(Zt),Vt=pn(Zt),At=pn(Zt);function Sn(e){if(e===Zt)throw Error(y(174));return e}function ai(e,n){switch(O(At,n),O(Vt,e),O(je,Zt),e=n.nodeType,e){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:Jl(null,"");break;default:e=e===8?n.parentNode:n,n=e.namespaceURI||null,e=e.tagName,n=Jl(n,e)}I(je),O(je,n)}function et(){I(je),I(Vt),I(At)}function ta(e){Sn(At.current);var n=Sn(je.current),t=Jl(n,e.type);n!==t&&(O(Vt,e),O(je,t))}function fi(e){Vt.current===e&&(I(je),I(Vt))}var U=pn(0);function Wr(e){for(var n=e;n!==null;){if(n.tag===13){var t=n.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return n}else if(n.tag===19&&n.memoizedProps.revealOrder!==void 0){if(n.flags&128)return n}else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var Dl=[];function ci(){for(var e=0;e<Dl.length;e++)Dl[e]._workInProgressVersionPrimary=null;Dl.length=0}var Er=Ye.ReactCurrentDispatcher,Il=Ye.ReactCurrentBatchConfig,Pn=0,$=null,K=null,G=null,Qr=!1,xt=!1,Bt=0,Bc=0;function ee(){throw Error(y(321))}function di(e,n){if(n===null)return!1;for(var t=0;t<n.length&&t<e.length;t++)if(!Me(e[t],n[t]))return!1;return!0}function pi(e,n,t,r,l,u){if(Pn=u,$=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,Er.current=e===null||e.memoizedState===null?Kc:Yc,e=t(r,l),xt){u=0;do{if(xt=!1,Bt=0,25<=u)throw Error(y(301));u+=1,G=K=null,n.updateQueue=null,Er.current=Xc,e=t(r,l)}while(xt)}if(Er.current=Kr,n=K!==null&&K.next!==null,Pn=0,G=K=$=null,Qr=!1,n)throw Error(y(300));return e}function mi(){var e=Bt!==0;return Bt=0,e}function De(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return G===null?$.memoizedState=G=e:G=G.next=e,G}function _e(){if(K===null){var e=$.alternate;e=e!==null?e.memoizedState:null}else e=K.next;var n=G===null?$.memoizedState:G.next;if(n!==null)G=n,K=e;else{if(e===null)throw Error(y(310));K=e,e={memoizedState:K.memoizedState,baseState:K.baseState,baseQueue:K.baseQueue,queue:K.queue,next:null},G===null?$.memoizedState=G=e:G=G.next=e}return G}function Ht(e,n){return typeof n=="function"?n(e):n}function Fl(e){var n=_e(),t=n.queue;if(t===null)throw Error(y(311));t.lastRenderedReducer=e;var r=K,l=r.baseQueue,u=t.pending;if(u!==null){if(l!==null){var i=l.next;l.next=u.next,u.next=i}r.baseQueue=l=u,t.pending=null}if(l!==null){u=l.next,r=r.baseState;var o=i=null,s=null,f=u;do{var h=f.lane;if((Pn&h)===h)s!==null&&(s=s.next={lane:0,action:f.action,hasEagerState:f.hasEagerState,eagerState:f.eagerState,next:null}),r=f.hasEagerState?f.eagerState:e(r,f.action);else{var m={lane:h,action:f.action,hasEagerState:f.hasEagerState,eagerState:f.eagerState,next:null};s===null?(o=s=m,i=r):s=s.next=m,$.lanes|=h,Nn|=h}f=f.next}while(f!==null&&f!==u);s===null?i=r:s.next=o,Me(r,n.memoizedState)||(ae=!0),n.memoizedState=r,n.baseState=i,n.baseQueue=s,t.lastRenderedState=r}if(e=t.interleaved,e!==null){l=e;do u=l.lane,$.lanes|=u,Nn|=u,l=l.next;while(l!==e)}else l===null&&(t.lanes=0);return[n.memoizedState,t.dispatch]}function jl(e){var n=_e(),t=n.queue;if(t===null)throw Error(y(311));t.lastRenderedReducer=e;var r=t.dispatch,l=t.pending,u=n.memoizedState;if(l!==null){t.pending=null;var i=l=l.next;do u=e(u,i.action),i=i.next;while(i!==l);Me(u,n.memoizedState)||(ae=!0),n.memoizedState=u,n.baseQueue===null&&(n.baseState=u),t.lastRenderedState=u}return[u,r]}function ra(){}function la(e,n){var t=$,r=_e(),l=n(),u=!Me(r.memoizedState,l);if(u&&(r.memoizedState=l,ae=!0),r=r.queue,hi(oa.bind(null,t,r,e),[e]),r.getSnapshot!==n||u||G!==null&&G.memoizedState.tag&1){if(t.flags|=2048,Wt(9,ia.bind(null,t,r,l,n),void 0,null),Z===null)throw Error(y(349));Pn&30||ua(t,n,l)}return l}function ua(e,n,t){e.flags|=16384,e={getSnapshot:n,value:t},n=$.updateQueue,n===null?(n={lastEffect:null,stores:null},$.updateQueue=n,n.stores=[e]):(t=n.stores,t===null?n.stores=[e]:t.push(e))}function ia(e,n,t,r){n.value=t,n.getSnapshot=r,sa(n)&&aa(e)}function oa(e,n,t){return t(function(){sa(n)&&aa(e)})}function sa(e){var n=e.getSnapshot;e=e.value;try{var t=n();return!Me(e,t)}catch{return!0}}function aa(e){var n=Qe(e,1);n!==null&&Re(n,e,1,-1)}function yo(e){var n=De();return typeof e=="function"&&(e=e()),n.memoizedState=n.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ht,lastRenderedState:e},n.queue=e,e=e.dispatch=Qc.bind(null,$,e),[n.memoizedState,e]}function Wt(e,n,t,r){return e={tag:e,create:n,destroy:t,deps:r,next:null},n=$.updateQueue,n===null?(n={lastEffect:null,stores:null},$.updateQueue=n,n.lastEffect=e.next=e):(t=n.lastEffect,t===null?n.lastEffect=e.next=e:(r=t.next,t.next=e,e.next=r,n.lastEffect=e)),e}function fa(){return _e().memoizedState}function Cr(e,n,t,r){var l=De();$.flags|=e,l.memoizedState=Wt(1|n,t,void 0,r===void 0?null:r)}function ll(e,n,t,r){var l=_e();r=r===void 0?null:r;var u=void 0;if(K!==null){var i=K.memoizedState;if(u=i.destroy,r!==null&&di(r,i.deps)){l.memoizedState=Wt(n,t,u,r);return}}$.flags|=e,l.memoizedState=Wt(1|n,t,u,r)}function go(e,n){return Cr(8390656,8,e,n)}function hi(e,n){return ll(2048,8,e,n)}function ca(e,n){return ll(4,2,e,n)}function da(e,n){return ll(4,4,e,n)}function pa(e,n){if(typeof n=="function")return e=e(),n(e),function(){n(null)};if(n!=null)return e=e(),n.current=e,function(){n.current=null}}function ma(e,n,t){return t=t!=null?t.concat([e]):null,ll(4,4,pa.bind(null,n,e),t)}function vi(){}function ha(e,n){var t=_e();n=n===void 0?null:n;var r=t.memoizedState;return r!==null&&n!==null&&di(n,r[1])?r[0]:(t.memoizedState=[e,n],e)}function va(e,n){var t=_e();n=n===void 0?null:n;var r=t.memoizedState;return r!==null&&n!==null&&di(n,r[1])?r[0]:(e=e(),t.memoizedState=[e,n],e)}function ya(e,n,t){return Pn&21?(Me(t,n)||(t=Es(),$.lanes|=t,Nn|=t,e.baseState=!0),n):(e.baseState&&(e.baseState=!1,ae=!0),e.memoizedState=t)}function Hc(e,n){var t=M;M=t!==0&&4>t?t:4,e(!0);var r=Il.transition;Il.transition={};try{e(!1),n()}finally{M=t,Il.transition=r}}function ga(){return _e().memoizedState}function Wc(e,n,t){var r=sn(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},wa(e))ka(n,t);else if(t=ea(e,n,t,r),t!==null){var l=ue();Re(t,e,r,l),Sa(t,n,r)}}function Qc(e,n,t){var r=sn(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(wa(e))ka(n,l);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=n.lastRenderedReducer,u!==null))try{var i=n.lastRenderedState,o=u(i,t);if(l.hasEagerState=!0,l.eagerState=o,Me(o,i)){var s=n.interleaved;s===null?(l.next=l,oi(n)):(l.next=s.next,s.next=l),n.interleaved=l;return}}catch{}finally{}t=ea(e,n,l,r),t!==null&&(l=ue(),Re(t,e,r,l),Sa(t,n,r))}}function wa(e){var n=e.alternate;return e===$||n!==null&&n===$}function ka(e,n){xt=Qr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Sa(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Yu(e,t)}}var Kr={readContext:Ce,useCallback:ee,useContext:ee,useEffect:ee,useImperativeHandle:ee,useInsertionEffect:ee,useLayoutEffect:ee,useMemo:ee,useReducer:ee,useRef:ee,useState:ee,useDebugValue:ee,useDeferredValue:ee,useTransition:ee,useMutableSource:ee,useSyncExternalStore:ee,useId:ee,unstable_isNewReconciler:!1},Kc={readContext:Ce,useCallback:function(e,n){return De().memoizedState=[e,n===void 0?null:n],e},useContext:Ce,useEffect:go,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,Cr(4194308,4,pa.bind(null,n,e),t)},useLayoutEffect:function(e,n){return Cr(4194308,4,e,n)},useInsertionEffect:function(e,n){return Cr(4,2,e,n)},useMemo:function(e,n){var t=De();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=De();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Wc.bind(null,$,e),[r.memoizedState,e]},useRef:function(e){var n=De();return e={current:e},n.memoizedState=e},useState:yo,useDebugValue:vi,useDeferredValue:function(e){return De().memoizedState=e},useTransition:function(){var e=yo(!1),n=e[0];return e=Hc.bind(null,e[1]),De().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=$,l=De();if(j){if(t===void 0)throw Error(y(407));t=t()}else{if(t=n(),Z===null)throw Error(y(349));Pn&30||ua(r,n,t)}l.memoizedState=t;var u={value:t,getSnapshot:n};return l.queue=u,go(oa.bind(null,r,u,e),[e]),r.flags|=2048,Wt(9,ia.bind(null,r,u,t,n),void 0,null),t},useId:function(){var e=De(),n=Z.identifierPrefix;if(j){var t=Ae,r=Ve;t=(r&~(1<<32-Le(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=Bt++,0<t&&(n+="H"+t.toString(32)),n+=":"}else t=Bc++,n=":"+n+"r"+t.toString(32)+":";return e.memoizedState=n},unstable_isNewReconciler:!1},Yc={readContext:Ce,useCallback:ha,useContext:Ce,useEffect:hi,useImperativeHandle:ma,useInsertionEffect:ca,useLayoutEffect:da,useMemo:va,useReducer:Fl,useRef:fa,useState:function(){return Fl(Ht)},useDebugValue:vi,useDeferredValue:function(e){var n=_e();return ya(n,K.memoizedState,e)},useTransition:function(){var e=Fl(Ht)[0],n=_e().memoizedState;return[e,n]},useMutableSource:ra,useSyncExternalStore:la,useId:ga,unstable_isNewReconciler:!1},Xc={readContext:Ce,useCallback:ha,useContext:Ce,useEffect:hi,useImperativeHandle:ma,useInsertionEffect:ca,useLayoutEffect:da,useMemo:va,useReducer:jl,useRef:fa,useState:function(){return jl(Ht)},useDebugValue:vi,useDeferredValue:function(e){var n=_e();return K===null?n.memoizedState=e:ya(n,K.memoizedState,e)},useTransition:function(){var e=jl(Ht)[0],n=_e().memoizedState;return[e,n]},useMutableSource:ra,useSyncExternalStore:la,useId:ga,unstable_isNewReconciler:!1};function Ne(e,n){if(e&&e.defaultProps){n=V({},n),e=e.defaultProps;for(var t in e)n[t]===void 0&&(n[t]=e[t]);return n}return n}function gu(e,n,t,r){n=e.memoizedState,t=t(r,n),t=t==null?n:V({},n,t),e.memoizedState=t,e.lanes===0&&(e.updateQueue.baseState=t)}var ul={isMounted:function(e){return(e=e._reactInternals)?Ln(e)===e:!1},enqueueSetState:function(e,n,t){e=e._reactInternals;var r=ue(),l=sn(e),u=Be(r,l);u.payload=n,t!=null&&(u.callback=t),n=un(e,u,l),n!==null&&(Re(n,e,l,r),Sr(n,e,l))},enqueueReplaceState:function(e,n,t){e=e._reactInternals;var r=ue(),l=sn(e),u=Be(r,l);u.tag=1,u.payload=n,t!=null&&(u.callback=t),n=un(e,u,l),n!==null&&(Re(n,e,l,r),Sr(n,e,l))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var t=ue(),r=sn(e),l=Be(t,r);l.tag=2,n!=null&&(l.callback=n),n=un(e,l,r),n!==null&&(Re(n,e,r,t),Sr(n,e,r))}};function wo(e,n,t,r,l,u,i){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,u,i):n.prototype&&n.prototype.isPureReactComponent?!Ft(t,r)||!Ft(l,u):!0}function Ea(e,n,t){var r=!1,l=cn,u=n.contextType;return typeof u=="object"&&u!==null?u=Ce(u):(l=ce(n)?_n:re.current,r=n.contextTypes,u=(r=r!=null)?Jn(e,l):cn),n=new n(t,u),e.memoizedState=n.state!==null&&n.state!==void 0?n.state:null,n.updater=ul,e.stateNode=n,n._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=u),n}function ko(e,n,t,r){e=n.state,typeof n.componentWillReceiveProps=="function"&&n.componentWillReceiveProps(t,r),typeof n.UNSAFE_componentWillReceiveProps=="function"&&n.UNSAFE_componentWillReceiveProps(t,r),n.state!==e&&ul.enqueueReplaceState(n,n.state,null)}function wu(e,n,t,r){var l=e.stateNode;l.props=t,l.state=e.memoizedState,l.refs={},si(e);var u=n.contextType;typeof u=="object"&&u!==null?l.context=Ce(u):(u=ce(n)?_n:re.current,l.context=Jn(e,u)),l.state=e.memoizedState,u=n.getDerivedStateFromProps,typeof u=="function"&&(gu(e,n,u,t),l.state=e.memoizedState),typeof n.getDerivedStateFromProps=="function"||typeof l.getSnapshotBeforeUpdate=="function"||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(n=l.state,typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount(),n!==l.state&&ul.enqueueReplaceState(l,l.state,null),Hr(e,t,l,r),l.state=e.memoizedState),typeof l.componentDidMount=="function"&&(e.flags|=4194308)}function nt(e,n){try{var t="",r=n;do t+=Ef(r),r=r.return;while(r);var l=t}catch(u){l=` +Error generating stack: `+u.message+` +`+u.stack}return{value:e,source:n,stack:l,digest:null}}function Ul(e,n,t){return{value:e,source:null,stack:t??null,digest:n??null}}function ku(e,n){try{console.error(n.value)}catch(t){setTimeout(function(){throw t})}}var Gc=typeof WeakMap=="function"?WeakMap:Map;function Ca(e,n,t){t=Be(-1,t),t.tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){Xr||(Xr=!0,Lu=r),ku(e,n)},t}function _a(e,n,t){t=Be(-1,t),t.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=n.value;t.payload=function(){return r(l)},t.callback=function(){ku(e,n)}}var u=e.stateNode;return u!==null&&typeof u.componentDidCatch=="function"&&(t.callback=function(){ku(e,n),typeof r!="function"&&(on===null?on=new Set([this]):on.add(this));var i=n.stack;this.componentDidCatch(n.value,{componentStack:i!==null?i:""})}),t}function So(e,n,t){var r=e.pingCache;if(r===null){r=e.pingCache=new Gc;var l=new Set;r.set(n,l)}else l=r.get(n),l===void 0&&(l=new Set,r.set(n,l));l.has(t)||(l.add(t),e=ad.bind(null,e,n,t),n.then(e,e))}function Eo(e){do{var n;if((n=e.tag===13)&&(n=e.memoizedState,n=n!==null?n.dehydrated!==null:!0),n)return e;e=e.return}while(e!==null);return null}function Co(e,n,t,r,l){return e.mode&1?(e.flags|=65536,e.lanes=l,e):(e===n?e.flags|=65536:(e.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(n=Be(-1,1),n.tag=2,un(t,n,1))),t.lanes|=1),e)}var Zc=Ye.ReactCurrentOwner,ae=!1;function le(e,n,t,r){n.child=e===null?bs(n,null,t,r):bn(n,e.child,t,r)}function _o(e,n,t,r,l){t=t.render;var u=n.ref;return Xn(n,l),r=pi(e,n,t,r,u,l),t=mi(),e!==null&&!ae?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,Ke(e,n,l)):(j&&t&&ni(n),n.flags|=1,le(e,n,r,l),n.child)}function xo(e,n,t,r,l){if(e===null){var u=t.type;return typeof u=="function"&&!_i(u)&&u.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(n.tag=15,n.type=u,xa(e,n,u,r,l)):(e=Nr(t.type,null,r,n,n.mode,l),e.ref=n.ref,e.return=n,n.child=e)}if(u=e.child,!(e.lanes&l)){var i=u.memoizedProps;if(t=t.compare,t=t!==null?t:Ft,t(i,r)&&e.ref===n.ref)return Ke(e,n,l)}return n.flags|=1,e=an(u,r),e.ref=n.ref,e.return=n,n.child=e}function xa(e,n,t,r,l){if(e!==null){var u=e.memoizedProps;if(Ft(u,r)&&e.ref===n.ref)if(ae=!1,n.pendingProps=r=u,(e.lanes&l)!==0)e.flags&131072&&(ae=!0);else return n.lanes=e.lanes,Ke(e,n,l)}return Su(e,n,t,r,l)}function Pa(e,n,t){var r=n.pendingProps,l=r.children,u=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(n.mode&1))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},O(Hn,pe),pe|=t;else{if(!(t&1073741824))return e=u!==null?u.baseLanes|t:t,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,O(Hn,pe),pe|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=u!==null?u.baseLanes:t,O(Hn,pe),pe|=r}else u!==null?(r=u.baseLanes|t,n.memoizedState=null):r=t,O(Hn,pe),pe|=r;return le(e,n,l,t),n.child}function Na(e,n){var t=n.ref;(e===null&&t!==null||e!==null&&e.ref!==t)&&(n.flags|=512,n.flags|=2097152)}function Su(e,n,t,r,l){var u=ce(t)?_n:re.current;return u=Jn(n,u),Xn(n,l),t=pi(e,n,t,r,u,l),r=mi(),e!==null&&!ae?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,Ke(e,n,l)):(j&&r&&ni(n),n.flags|=1,le(e,n,t,l),n.child)}function Po(e,n,t,r,l){if(ce(t)){var u=!0;Ur(n)}else u=!1;if(Xn(n,l),n.stateNode===null)_r(e,n),Ea(n,t,r),wu(n,t,r,l),r=!0;else if(e===null){var i=n.stateNode,o=n.memoizedProps;i.props=o;var s=i.context,f=t.contextType;typeof f=="object"&&f!==null?f=Ce(f):(f=ce(t)?_n:re.current,f=Jn(n,f));var h=t.getDerivedStateFromProps,m=typeof h=="function"||typeof i.getSnapshotBeforeUpdate=="function";m||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(o!==r||s!==f)&&ko(n,i,r,f),Ze=!1;var p=n.memoizedState;i.state=p,Hr(n,r,i,l),s=n.memoizedState,o!==r||p!==s||fe.current||Ze?(typeof h=="function"&&(gu(n,t,h,r),s=n.memoizedState),(o=Ze||wo(n,t,o,r,p,s,f))?(m||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(n.flags|=4194308)):(typeof i.componentDidMount=="function"&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=s),i.props=r,i.state=s,i.context=f,r=o):(typeof i.componentDidMount=="function"&&(n.flags|=4194308),r=!1)}else{i=n.stateNode,na(e,n),o=n.memoizedProps,f=n.type===n.elementType?o:Ne(n.type,o),i.props=f,m=n.pendingProps,p=i.context,s=t.contextType,typeof s=="object"&&s!==null?s=Ce(s):(s=ce(t)?_n:re.current,s=Jn(n,s));var g=t.getDerivedStateFromProps;(h=typeof g=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(o!==m||p!==s)&&ko(n,i,r,s),Ze=!1,p=n.memoizedState,i.state=p,Hr(n,r,i,l);var w=n.memoizedState;o!==m||p!==w||fe.current||Ze?(typeof g=="function"&&(gu(n,t,g,r),w=n.memoizedState),(f=Ze||wo(n,t,f,r,p,w,s)||!1)?(h||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,w,s),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,w,s)),typeof i.componentDidUpdate=="function"&&(n.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(n.flags|=1024)):(typeof i.componentDidUpdate!="function"||o===e.memoizedProps&&p===e.memoizedState||(n.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&p===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=w),i.props=r,i.state=w,i.context=s,r=f):(typeof i.componentDidUpdate!="function"||o===e.memoizedProps&&p===e.memoizedState||(n.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&p===e.memoizedState||(n.flags|=1024),r=!1)}return Eu(e,n,t,r,u,l)}function Eu(e,n,t,r,l,u){Na(e,n);var i=(n.flags&128)!==0;if(!r&&!i)return l&&fo(n,t,!1),Ke(e,n,u);r=n.stateNode,Zc.current=n;var o=i&&typeof t.getDerivedStateFromError!="function"?null:r.render();return n.flags|=1,e!==null&&i?(n.child=bn(n,e.child,null,u),n.child=bn(n,null,o,u)):le(e,n,o,u),n.memoizedState=r.state,l&&fo(n,t,!0),n.child}function za(e){var n=e.stateNode;n.pendingContext?ao(e,n.pendingContext,n.pendingContext!==n.context):n.context&&ao(e,n.context,!1),ai(e,n.containerInfo)}function No(e,n,t,r,l){return qn(),ri(l),n.flags|=256,le(e,n,t,r),n.child}var Cu={dehydrated:null,treeContext:null,retryLane:0};function _u(e){return{baseLanes:e,cachePool:null,transitions:null}}function Ta(e,n,t){var r=n.pendingProps,l=U.current,u=!1,i=(n.flags&128)!==0,o;if((o=i)||(o=e!==null&&e.memoizedState===null?!1:(l&2)!==0),o?(u=!0,n.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),O(U,l&1),e===null)return vu(n),e=n.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(n.mode&1?e.data==="$!"?n.lanes=8:n.lanes=1073741824:n.lanes=1,null):(i=r.children,e=r.fallback,u?(r=n.mode,u=n.child,i={mode:"hidden",children:i},!(r&1)&&u!==null?(u.childLanes=0,u.pendingProps=i):u=sl(i,r,0,null),e=Cn(e,r,t,null),u.return=n,e.return=n,u.sibling=e,n.child=u,n.child.memoizedState=_u(t),n.memoizedState=Cu,e):yi(n,i));if(l=e.memoizedState,l!==null&&(o=l.dehydrated,o!==null))return Jc(e,n,i,r,o,l,t);if(u){u=r.fallback,i=n.mode,l=e.child,o=l.sibling;var s={mode:"hidden",children:r.children};return!(i&1)&&n.child!==l?(r=n.child,r.childLanes=0,r.pendingProps=s,n.deletions=null):(r=an(l,s),r.subtreeFlags=l.subtreeFlags&14680064),o!==null?u=an(o,u):(u=Cn(u,i,t,null),u.flags|=2),u.return=n,r.return=n,r.sibling=u,n.child=r,r=u,u=n.child,i=e.child.memoizedState,i=i===null?_u(t):{baseLanes:i.baseLanes|t,cachePool:null,transitions:i.transitions},u.memoizedState=i,u.childLanes=e.childLanes&~t,n.memoizedState=Cu,r}return u=e.child,e=u.sibling,r=an(u,{mode:"visible",children:r.children}),!(n.mode&1)&&(r.lanes=t),r.return=n,r.sibling=null,e!==null&&(t=n.deletions,t===null?(n.deletions=[e],n.flags|=16):t.push(e)),n.child=r,n.memoizedState=null,r}function yi(e,n){return n=sl({mode:"visible",children:n},e.mode,0,null),n.return=e,e.child=n}function dr(e,n,t,r){return r!==null&&ri(r),bn(n,e.child,null,t),e=yi(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function Jc(e,n,t,r,l,u,i){if(t)return n.flags&256?(n.flags&=-257,r=Ul(Error(y(422))),dr(e,n,i,r)):n.memoizedState!==null?(n.child=e.child,n.flags|=128,null):(u=r.fallback,l=n.mode,r=sl({mode:"visible",children:r.children},l,0,null),u=Cn(u,l,i,null),u.flags|=2,r.return=n,u.return=n,r.sibling=u,n.child=r,n.mode&1&&bn(n,e.child,null,i),n.child.memoizedState=_u(i),n.memoizedState=Cu,u);if(!(n.mode&1))return dr(e,n,i,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var o=r.dgst;return r=o,u=Error(y(419)),r=Ul(u,r,void 0),dr(e,n,i,r)}if(o=(i&e.childLanes)!==0,ae||o){if(r=Z,r!==null){switch(i&-i){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=l&(r.suspendedLanes|i)?0:l,l!==0&&l!==u.retryLane&&(u.retryLane=l,Qe(e,l),Re(r,e,l,-1))}return Ci(),r=Ul(Error(y(421))),dr(e,n,i,r)}return l.data==="$?"?(n.flags|=128,n.child=e.child,n=fd.bind(null,e),l._reactRetry=n,null):(e=u.treeContext,me=ln(l.nextSibling),he=n,j=!0,Te=null,e!==null&&(we[ke++]=Ve,we[ke++]=Ae,we[ke++]=xn,Ve=e.id,Ae=e.overflow,xn=n),n=yi(n,r.children),n.flags|=4096,n)}function zo(e,n,t){e.lanes|=n;var r=e.alternate;r!==null&&(r.lanes|=n),yu(e.return,n,t)}function $l(e,n,t,r,l){var u=e.memoizedState;u===null?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:l}:(u.isBackwards=n,u.rendering=null,u.renderingStartTime=0,u.last=r,u.tail=t,u.tailMode=l)}function La(e,n,t){var r=n.pendingProps,l=r.revealOrder,u=r.tail;if(le(e,n,r.children,t),r=U.current,r&2)r=r&1|2,n.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=n.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&zo(e,t,n);else if(e.tag===19)zo(e,t,n);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;e.sibling===null;){if(e.return===null||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(O(U,r),!(n.mode&1))n.memoizedState=null;else switch(l){case"forwards":for(t=n.child,l=null;t!==null;)e=t.alternate,e!==null&&Wr(e)===null&&(l=t),t=t.sibling;t=l,t===null?(l=n.child,n.child=null):(l=t.sibling,t.sibling=null),$l(n,!1,l,t,u);break;case"backwards":for(t=null,l=n.child,n.child=null;l!==null;){if(e=l.alternate,e!==null&&Wr(e)===null){n.child=l;break}e=l.sibling,l.sibling=t,t=l,l=e}$l(n,!0,t,null,u);break;case"together":$l(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function _r(e,n){!(n.mode&1)&&e!==null&&(e.alternate=null,n.alternate=null,n.flags|=2)}function Ke(e,n,t){if(e!==null&&(n.dependencies=e.dependencies),Nn|=n.lanes,!(t&n.childLanes))return null;if(e!==null&&n.child!==e.child)throw Error(y(153));if(n.child!==null){for(e=n.child,t=an(e,e.pendingProps),n.child=t,t.return=n;e.sibling!==null;)e=e.sibling,t=t.sibling=an(e,e.pendingProps),t.return=n;t.sibling=null}return n.child}function qc(e,n,t){switch(n.tag){case 3:za(n),qn();break;case 5:ta(n);break;case 1:ce(n.type)&&Ur(n);break;case 4:ai(n,n.stateNode.containerInfo);break;case 10:var r=n.type._context,l=n.memoizedProps.value;O(Ar,r._currentValue),r._currentValue=l;break;case 13:if(r=n.memoizedState,r!==null)return r.dehydrated!==null?(O(U,U.current&1),n.flags|=128,null):t&n.child.childLanes?Ta(e,n,t):(O(U,U.current&1),e=Ke(e,n,t),e!==null?e.sibling:null);O(U,U.current&1);break;case 19:if(r=(t&n.childLanes)!==0,e.flags&128){if(r)return La(e,n,t);n.flags|=128}if(l=n.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),O(U,U.current),r)break;return null;case 22:case 23:return n.lanes=0,Pa(e,n,t)}return Ke(e,n,t)}var Ra,xu,Ma,Oa;Ra=function(e,n){for(var t=n.child;t!==null;){if(t.tag===5||t.tag===6)e.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===n)break;for(;t.sibling===null;){if(t.return===null||t.return===n)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};xu=function(){};Ma=function(e,n,t,r){var l=e.memoizedProps;if(l!==r){e=n.stateNode,Sn(je.current);var u=null;switch(t){case"input":l=Yl(e,l),r=Yl(e,r),u=[];break;case"select":l=V({},l,{value:void 0}),r=V({},r,{value:void 0}),u=[];break;case"textarea":l=Zl(e,l),r=Zl(e,r),u=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Fr)}ql(t,r);var i;t=null;for(f in l)if(!r.hasOwnProperty(f)&&l.hasOwnProperty(f)&&l[f]!=null)if(f==="style"){var o=l[f];for(i in o)o.hasOwnProperty(i)&&(t||(t={}),t[i]="")}else f!=="dangerouslySetInnerHTML"&&f!=="children"&&f!=="suppressContentEditableWarning"&&f!=="suppressHydrationWarning"&&f!=="autoFocus"&&(Tt.hasOwnProperty(f)?u||(u=[]):(u=u||[]).push(f,null));for(f in r){var s=r[f];if(o=l!=null?l[f]:void 0,r.hasOwnProperty(f)&&s!==o&&(s!=null||o!=null))if(f==="style")if(o){for(i in o)!o.hasOwnProperty(i)||s&&s.hasOwnProperty(i)||(t||(t={}),t[i]="");for(i in s)s.hasOwnProperty(i)&&o[i]!==s[i]&&(t||(t={}),t[i]=s[i])}else t||(u||(u=[]),u.push(f,t)),t=s;else f==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,o=o?o.__html:void 0,s!=null&&o!==s&&(u=u||[]).push(f,s)):f==="children"?typeof s!="string"&&typeof s!="number"||(u=u||[]).push(f,""+s):f!=="suppressContentEditableWarning"&&f!=="suppressHydrationWarning"&&(Tt.hasOwnProperty(f)?(s!=null&&f==="onScroll"&&D("scroll",e),u||o===s||(u=[])):(u=u||[]).push(f,s))}t&&(u=u||[]).push("style",t);var f=u;(n.updateQueue=f)&&(n.flags|=4)}};Oa=function(e,n,t,r){t!==r&&(n.flags|=4)};function mt(e,n){if(!j)switch(e.tailMode){case"hidden":n=e.tail;for(var t=null;n!==null;)n.alternate!==null&&(t=n),n=n.sibling;t===null?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?n||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function ne(e){var n=e.alternate!==null&&e.alternate.child===e.child,t=0,r=0;if(n)for(var l=e.child;l!==null;)t|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)t|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=t,n}function bc(e,n,t){var r=n.pendingProps;switch(ti(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ne(n),null;case 1:return ce(n.type)&&jr(),ne(n),null;case 3:return r=n.stateNode,et(),I(fe),I(re),ci(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(fr(n)?n.flags|=4:e===null||e.memoizedState.isDehydrated&&!(n.flags&256)||(n.flags|=1024,Te!==null&&(Ou(Te),Te=null))),xu(e,n),ne(n),null;case 5:fi(n);var l=Sn(At.current);if(t=n.type,e!==null&&n.stateNode!=null)Ma(e,n,t,r,l),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!r){if(n.stateNode===null)throw Error(y(166));return ne(n),null}if(e=Sn(je.current),fr(n)){r=n.stateNode,t=n.type;var u=n.memoizedProps;switch(r[Ie]=n,r[$t]=u,e=(n.mode&1)!==0,t){case"dialog":D("cancel",r),D("close",r);break;case"iframe":case"object":case"embed":D("load",r);break;case"video":case"audio":for(l=0;l<wt.length;l++)D(wt[l],r);break;case"source":D("error",r);break;case"img":case"image":case"link":D("error",r),D("load",r);break;case"details":D("toggle",r);break;case"input":Fi(r,u),D("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!u.multiple},D("invalid",r);break;case"textarea":Ui(r,u),D("invalid",r)}ql(t,u),l=null;for(var i in u)if(u.hasOwnProperty(i)){var o=u[i];i==="children"?typeof o=="string"?r.textContent!==o&&(u.suppressHydrationWarning!==!0&&ar(r.textContent,o,e),l=["children",o]):typeof o=="number"&&r.textContent!==""+o&&(u.suppressHydrationWarning!==!0&&ar(r.textContent,o,e),l=["children",""+o]):Tt.hasOwnProperty(i)&&o!=null&&i==="onScroll"&&D("scroll",r)}switch(t){case"input":nr(r),ji(r,u,!0);break;case"textarea":nr(r),$i(r);break;case"select":case"option":break;default:typeof u.onClick=="function"&&(r.onclick=Fr)}r=l,n.updateQueue=r,r!==null&&(n.flags|=4)}else{i=l.nodeType===9?l:l.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=os(t)),e==="http://www.w3.org/1999/xhtml"?t==="script"?(e=i.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(t,{is:r.is}):(e=i.createElement(t),t==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,t),e[Ie]=n,e[$t]=r,Ra(e,n,!1,!1),n.stateNode=e;e:{switch(i=bl(t,r),t){case"dialog":D("cancel",e),D("close",e),l=r;break;case"iframe":case"object":case"embed":D("load",e),l=r;break;case"video":case"audio":for(l=0;l<wt.length;l++)D(wt[l],e);l=r;break;case"source":D("error",e),l=r;break;case"img":case"image":case"link":D("error",e),D("load",e),l=r;break;case"details":D("toggle",e),l=r;break;case"input":Fi(e,r),l=Yl(e,r),D("invalid",e);break;case"option":l=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},l=V({},r,{value:void 0}),D("invalid",e);break;case"textarea":Ui(e,r),l=Zl(e,r),D("invalid",e);break;default:l=r}ql(t,l),o=l;for(u in o)if(o.hasOwnProperty(u)){var s=o[u];u==="style"?fs(e,s):u==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,s!=null&&ss(e,s)):u==="children"?typeof s=="string"?(t!=="textarea"||s!=="")&&Lt(e,s):typeof s=="number"&&Lt(e,""+s):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(Tt.hasOwnProperty(u)?s!=null&&u==="onScroll"&&D("scroll",e):s!=null&&Au(e,u,s,i))}switch(t){case"input":nr(e),ji(e,r,!1);break;case"textarea":nr(e),$i(e);break;case"option":r.value!=null&&e.setAttribute("value",""+fn(r.value));break;case"select":e.multiple=!!r.multiple,u=r.value,u!=null?Wn(e,!!r.multiple,u,!1):r.defaultValue!=null&&Wn(e,!!r.multiple,r.defaultValue,!0);break;default:typeof l.onClick=="function"&&(e.onclick=Fr)}switch(t){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(n.flags|=4)}n.ref!==null&&(n.flags|=512,n.flags|=2097152)}return ne(n),null;case 6:if(e&&n.stateNode!=null)Oa(e,n,e.memoizedProps,r);else{if(typeof r!="string"&&n.stateNode===null)throw Error(y(166));if(t=Sn(At.current),Sn(je.current),fr(n)){if(r=n.stateNode,t=n.memoizedProps,r[Ie]=n,(u=r.nodeValue!==t)&&(e=he,e!==null))switch(e.tag){case 3:ar(r.nodeValue,t,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&ar(r.nodeValue,t,(e.mode&1)!==0)}u&&(n.flags|=4)}else r=(t.nodeType===9?t:t.ownerDocument).createTextNode(r),r[Ie]=n,n.stateNode=r}return ne(n),null;case 13:if(I(U),r=n.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(j&&me!==null&&n.mode&1&&!(n.flags&128))Js(),qn(),n.flags|=98560,u=!1;else if(u=fr(n),r!==null&&r.dehydrated!==null){if(e===null){if(!u)throw Error(y(318));if(u=n.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(y(317));u[Ie]=n}else qn(),!(n.flags&128)&&(n.memoizedState=null),n.flags|=4;ne(n),u=!1}else Te!==null&&(Ou(Te),Te=null),u=!0;if(!u)return n.flags&65536?n:null}return n.flags&128?(n.lanes=t,n):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(n.child.flags|=8192,n.mode&1&&(e===null||U.current&1?Y===0&&(Y=3):Ci())),n.updateQueue!==null&&(n.flags|=4),ne(n),null);case 4:return et(),xu(e,n),e===null&&jt(n.stateNode.containerInfo),ne(n),null;case 10:return ii(n.type._context),ne(n),null;case 17:return ce(n.type)&&jr(),ne(n),null;case 19:if(I(U),u=n.memoizedState,u===null)return ne(n),null;if(r=(n.flags&128)!==0,i=u.rendering,i===null)if(r)mt(u,!1);else{if(Y!==0||e!==null&&e.flags&128)for(e=n.child;e!==null;){if(i=Wr(e),i!==null){for(n.flags|=128,mt(u,!1),r=i.updateQueue,r!==null&&(n.updateQueue=r,n.flags|=4),n.subtreeFlags=0,r=t,t=n.child;t!==null;)u=t,e=r,u.flags&=14680066,i=u.alternate,i===null?(u.childLanes=0,u.lanes=e,u.child=null,u.subtreeFlags=0,u.memoizedProps=null,u.memoizedState=null,u.updateQueue=null,u.dependencies=null,u.stateNode=null):(u.childLanes=i.childLanes,u.lanes=i.lanes,u.child=i.child,u.subtreeFlags=0,u.deletions=null,u.memoizedProps=i.memoizedProps,u.memoizedState=i.memoizedState,u.updateQueue=i.updateQueue,u.type=i.type,e=i.dependencies,u.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),t=t.sibling;return O(U,U.current&1|2),n.child}e=e.sibling}u.tail!==null&&W()>tt&&(n.flags|=128,r=!0,mt(u,!1),n.lanes=4194304)}else{if(!r)if(e=Wr(i),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),mt(u,!0),u.tail===null&&u.tailMode==="hidden"&&!i.alternate&&!j)return ne(n),null}else 2*W()-u.renderingStartTime>tt&&t!==1073741824&&(n.flags|=128,r=!0,mt(u,!1),n.lanes=4194304);u.isBackwards?(i.sibling=n.child,n.child=i):(t=u.last,t!==null?t.sibling=i:n.child=i,u.last=i)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=W(),n.sibling=null,t=U.current,O(U,r?t&1|2:t&1),n):(ne(n),null);case 22:case 23:return Ei(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?pe&1073741824&&(ne(n),n.subtreeFlags&6&&(n.flags|=8192)):ne(n),null;case 24:return null;case 25:return null}throw Error(y(156,n.tag))}function ed(e,n){switch(ti(n),n.tag){case 1:return ce(n.type)&&jr(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return et(),I(fe),I(re),ci(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return fi(n),null;case 13:if(I(U),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(y(340));qn()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return I(U),null;case 4:return et(),null;case 10:return ii(n.type._context),null;case 22:case 23:return Ei(),null;case 24:return null;default:return null}}var pr=!1,te=!1,nd=typeof WeakSet=="function"?WeakSet:Set,S=null;function Bn(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){A(e,n,r)}else t.current=null}function Pu(e,n,t){try{t()}catch(r){A(e,n,r)}}var To=!1;function td(e,n){if(au=Or,e=Us(),ei(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var l=r.anchorOffset,u=r.focusNode;r=r.focusOffset;try{t.nodeType,u.nodeType}catch{t=null;break e}var i=0,o=-1,s=-1,f=0,h=0,m=e,p=null;n:for(;;){for(var g;m!==t||l!==0&&m.nodeType!==3||(o=i+l),m!==u||r!==0&&m.nodeType!==3||(s=i+r),m.nodeType===3&&(i+=m.nodeValue.length),(g=m.firstChild)!==null;)p=m,m=g;for(;;){if(m===e)break n;if(p===t&&++f===l&&(o=i),p===u&&++h===r&&(s=i),(g=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=g}t=o===-1||s===-1?null:{start:o,end:s}}else t=null}t=t||{start:0,end:0}}else t=null;for(fu={focusedElem:e,selectionRange:t},Or=!1,S=n;S!==null;)if(n=S,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,S=e;else for(;S!==null;){n=S;try{var w=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var k=w.memoizedProps,F=w.memoizedState,c=n.stateNode,a=c.getSnapshotBeforeUpdate(n.elementType===n.type?k:Ne(n.type,k),F);c.__reactInternalSnapshotBeforeUpdate=a}break;case 3:var d=n.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(y(163))}}catch(v){A(n,n.return,v)}if(e=n.sibling,e!==null){e.return=n.return,S=e;break}S=n.return}return w=To,To=!1,w}function Pt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var u=l.destroy;l.destroy=void 0,u!==void 0&&Pu(n,t,u)}l=l.next}while(l!==r)}}function il(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Nu(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function Da(e){var n=e.alternate;n!==null&&(e.alternate=null,Da(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[Ie],delete n[$t],delete n[pu],delete n[Uc],delete n[$c])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ia(e){return e.tag===5||e.tag===3||e.tag===4}function Lo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ia(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function zu(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Fr));else if(r!==4&&(e=e.child,e!==null))for(zu(e,n,t),e=e.sibling;e!==null;)zu(e,n,t),e=e.sibling}function Tu(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Tu(e,n,t),e=e.sibling;e!==null;)Tu(e,n,t),e=e.sibling}var J=null,ze=!1;function Xe(e,n,t){for(t=t.child;t!==null;)Fa(e,n,t),t=t.sibling}function Fa(e,n,t){if(Fe&&typeof Fe.onCommitFiberUnmount=="function")try{Fe.onCommitFiberUnmount(qr,t)}catch{}switch(t.tag){case 5:te||Bn(t,n);case 6:var r=J,l=ze;J=null,Xe(e,n,t),J=r,ze=l,J!==null&&(ze?(e=J,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):J.removeChild(t.stateNode));break;case 18:J!==null&&(ze?(e=J,t=t.stateNode,e.nodeType===8?Ml(e.parentNode,t):e.nodeType===1&&Ml(e,t),Dt(e)):Ml(J,t.stateNode));break;case 4:r=J,l=ze,J=t.stateNode.containerInfo,ze=!0,Xe(e,n,t),J=r,ze=l;break;case 0:case 11:case 14:case 15:if(!te&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var u=l,i=u.destroy;u=u.tag,i!==void 0&&(u&2||u&4)&&Pu(t,n,i),l=l.next}while(l!==r)}Xe(e,n,t);break;case 1:if(!te&&(Bn(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(o){A(t,n,o)}Xe(e,n,t);break;case 21:Xe(e,n,t);break;case 22:t.mode&1?(te=(r=te)||t.memoizedState!==null,Xe(e,n,t),te=r):Xe(e,n,t);break;default:Xe(e,n,t)}}function Ro(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new nd),n.forEach(function(r){var l=cd.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function Pe(e,n){var t=n.deletions;if(t!==null)for(var r=0;r<t.length;r++){var l=t[r];try{var u=e,i=n,o=i;e:for(;o!==null;){switch(o.tag){case 5:J=o.stateNode,ze=!1;break e;case 3:J=o.stateNode.containerInfo,ze=!0;break e;case 4:J=o.stateNode.containerInfo,ze=!0;break e}o=o.return}if(J===null)throw Error(y(160));Fa(u,i,l),J=null,ze=!1;var s=l.alternate;s!==null&&(s.return=null),l.return=null}catch(f){A(l,n,f)}}if(n.subtreeFlags&12854)for(n=n.child;n!==null;)ja(n,e),n=n.sibling}function ja(e,n){var t=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Pe(n,e),Oe(e),r&4){try{Pt(3,e,e.return),il(3,e)}catch(k){A(e,e.return,k)}try{Pt(5,e,e.return)}catch(k){A(e,e.return,k)}}break;case 1:Pe(n,e),Oe(e),r&512&&t!==null&&Bn(t,t.return);break;case 5:if(Pe(n,e),Oe(e),r&512&&t!==null&&Bn(t,t.return),e.flags&32){var l=e.stateNode;try{Lt(l,"")}catch(k){A(e,e.return,k)}}if(r&4&&(l=e.stateNode,l!=null)){var u=e.memoizedProps,i=t!==null?t.memoizedProps:u,o=e.type,s=e.updateQueue;if(e.updateQueue=null,s!==null)try{o==="input"&&u.type==="radio"&&u.name!=null&&us(l,u),bl(o,i);var f=bl(o,u);for(i=0;i<s.length;i+=2){var h=s[i],m=s[i+1];h==="style"?fs(l,m):h==="dangerouslySetInnerHTML"?ss(l,m):h==="children"?Lt(l,m):Au(l,h,m,f)}switch(o){case"input":Xl(l,u);break;case"textarea":is(l,u);break;case"select":var p=l._wrapperState.wasMultiple;l._wrapperState.wasMultiple=!!u.multiple;var g=u.value;g!=null?Wn(l,!!u.multiple,g,!1):p!==!!u.multiple&&(u.defaultValue!=null?Wn(l,!!u.multiple,u.defaultValue,!0):Wn(l,!!u.multiple,u.multiple?[]:"",!1))}l[$t]=u}catch(k){A(e,e.return,k)}}break;case 6:if(Pe(n,e),Oe(e),r&4){if(e.stateNode===null)throw Error(y(162));l=e.stateNode,u=e.memoizedProps;try{l.nodeValue=u}catch(k){A(e,e.return,k)}}break;case 3:if(Pe(n,e),Oe(e),r&4&&t!==null&&t.memoizedState.isDehydrated)try{Dt(n.containerInfo)}catch(k){A(e,e.return,k)}break;case 4:Pe(n,e),Oe(e);break;case 13:Pe(n,e),Oe(e),l=e.child,l.flags&8192&&(u=l.memoizedState!==null,l.stateNode.isHidden=u,!u||l.alternate!==null&&l.alternate.memoizedState!==null||(ki=W())),r&4&&Ro(e);break;case 22:if(h=t!==null&&t.memoizedState!==null,e.mode&1?(te=(f=te)||h,Pe(n,e),te=f):Pe(n,e),Oe(e),r&8192){if(f=e.memoizedState!==null,(e.stateNode.isHidden=f)&&!h&&e.mode&1)for(S=e,h=e.child;h!==null;){for(m=S=h;S!==null;){switch(p=S,g=p.child,p.tag){case 0:case 11:case 14:case 15:Pt(4,p,p.return);break;case 1:Bn(p,p.return);var w=p.stateNode;if(typeof w.componentWillUnmount=="function"){r=p,t=p.return;try{n=r,w.props=n.memoizedProps,w.state=n.memoizedState,w.componentWillUnmount()}catch(k){A(r,t,k)}}break;case 5:Bn(p,p.return);break;case 22:if(p.memoizedState!==null){Oo(m);continue}}g!==null?(g.return=p,S=g):Oo(m)}h=h.sibling}e:for(h=null,m=e;;){if(m.tag===5){if(h===null){h=m;try{l=m.stateNode,f?(u=l.style,typeof u.setProperty=="function"?u.setProperty("display","none","important"):u.display="none"):(o=m.stateNode,s=m.memoizedProps.style,i=s!=null&&s.hasOwnProperty("display")?s.display:null,o.style.display=as("display",i))}catch(k){A(e,e.return,k)}}}else if(m.tag===6){if(h===null)try{m.stateNode.nodeValue=f?"":m.memoizedProps}catch(k){A(e,e.return,k)}}else if((m.tag!==22&&m.tag!==23||m.memoizedState===null||m===e)&&m.child!==null){m.child.return=m,m=m.child;continue}if(m===e)break e;for(;m.sibling===null;){if(m.return===null||m.return===e)break e;h===m&&(h=null),m=m.return}h===m&&(h=null),m.sibling.return=m.return,m=m.sibling}}break;case 19:Pe(n,e),Oe(e),r&4&&Ro(e);break;case 21:break;default:Pe(n,e),Oe(e)}}function Oe(e){var n=e.flags;if(n&2){try{e:{for(var t=e.return;t!==null;){if(Ia(t)){var r=t;break e}t=t.return}throw Error(y(160))}switch(r.tag){case 5:var l=r.stateNode;r.flags&32&&(Lt(l,""),r.flags&=-33);var u=Lo(e);Tu(e,u,l);break;case 3:case 4:var i=r.stateNode.containerInfo,o=Lo(e);zu(e,o,i);break;default:throw Error(y(161))}}catch(s){A(e,e.return,s)}e.flags&=-3}n&4096&&(e.flags&=-4097)}function rd(e,n,t){S=e,Ua(e)}function Ua(e,n,t){for(var r=(e.mode&1)!==0;S!==null;){var l=S,u=l.child;if(l.tag===22&&r){var i=l.memoizedState!==null||pr;if(!i){var o=l.alternate,s=o!==null&&o.memoizedState!==null||te;o=pr;var f=te;if(pr=i,(te=s)&&!f)for(S=l;S!==null;)i=S,s=i.child,i.tag===22&&i.memoizedState!==null?Do(l):s!==null?(s.return=i,S=s):Do(l);for(;u!==null;)S=u,Ua(u),u=u.sibling;S=l,pr=o,te=f}Mo(e)}else l.subtreeFlags&8772&&u!==null?(u.return=l,S=u):Mo(e)}}function Mo(e){for(;S!==null;){var n=S;if(n.flags&8772){var t=n.alternate;try{if(n.flags&8772)switch(n.tag){case 0:case 11:case 15:te||il(5,n);break;case 1:var r=n.stateNode;if(n.flags&4&&!te)if(t===null)r.componentDidMount();else{var l=n.elementType===n.type?t.memoizedProps:Ne(n.type,t.memoizedProps);r.componentDidUpdate(l,t.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var u=n.updateQueue;u!==null&&vo(n,u,r);break;case 3:var i=n.updateQueue;if(i!==null){if(t=null,n.child!==null)switch(n.child.tag){case 5:t=n.child.stateNode;break;case 1:t=n.child.stateNode}vo(n,i,t)}break;case 5:var o=n.stateNode;if(t===null&&n.flags&4){t=o;var s=n.memoizedProps;switch(n.type){case"button":case"input":case"select":case"textarea":s.autoFocus&&t.focus();break;case"img":s.src&&(t.src=s.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(n.memoizedState===null){var f=n.alternate;if(f!==null){var h=f.memoizedState;if(h!==null){var m=h.dehydrated;m!==null&&Dt(m)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(y(163))}te||n.flags&512&&Nu(n)}catch(p){A(n,n.return,p)}}if(n===e){S=null;break}if(t=n.sibling,t!==null){t.return=n.return,S=t;break}S=n.return}}function Oo(e){for(;S!==null;){var n=S;if(n===e){S=null;break}var t=n.sibling;if(t!==null){t.return=n.return,S=t;break}S=n.return}}function Do(e){for(;S!==null;){var n=S;try{switch(n.tag){case 0:case 11:case 15:var t=n.return;try{il(4,n)}catch(s){A(n,t,s)}break;case 1:var r=n.stateNode;if(typeof r.componentDidMount=="function"){var l=n.return;try{r.componentDidMount()}catch(s){A(n,l,s)}}var u=n.return;try{Nu(n)}catch(s){A(n,u,s)}break;case 5:var i=n.return;try{Nu(n)}catch(s){A(n,i,s)}}}catch(s){A(n,n.return,s)}if(n===e){S=null;break}var o=n.sibling;if(o!==null){o.return=n.return,S=o;break}S=n.return}}var ld=Math.ceil,Yr=Ye.ReactCurrentDispatcher,gi=Ye.ReactCurrentOwner,Ee=Ye.ReactCurrentBatchConfig,R=0,Z=null,Q=null,q=0,pe=0,Hn=pn(0),Y=0,Qt=null,Nn=0,ol=0,wi=0,Nt=null,se=null,ki=0,tt=1/0,Ue=null,Xr=!1,Lu=null,on=null,mr=!1,en=null,Gr=0,zt=0,Ru=null,xr=-1,Pr=0;function ue(){return R&6?W():xr!==-1?xr:xr=W()}function sn(e){return e.mode&1?R&2&&q!==0?q&-q:Ac.transition!==null?(Pr===0&&(Pr=Es()),Pr):(e=M,e!==0||(e=window.event,e=e===void 0?16:Ts(e.type)),e):1}function Re(e,n,t,r){if(50<zt)throw zt=0,Ru=null,Error(y(185));Yt(e,t,r),(!(R&2)||e!==Z)&&(e===Z&&(!(R&2)&&(ol|=t),Y===4&&qe(e,q)),de(e,r),t===1&&R===0&&!(n.mode&1)&&(tt=W()+500,rl&&mn()))}function de(e,n){var t=e.callbackNode;Af(e,n);var r=Mr(e,e===Z?q:0);if(r===0)t!==null&&Bi(t),e.callbackNode=null,e.callbackPriority=0;else if(n=r&-r,e.callbackPriority!==n){if(t!=null&&Bi(t),n===1)e.tag===0?Vc(Io.bind(null,e)):Xs(Io.bind(null,e)),Fc(function(){!(R&6)&&mn()}),t=null;else{switch(Cs(r)){case 1:t=Ku;break;case 4:t=ks;break;case 16:t=Rr;break;case 536870912:t=Ss;break;default:t=Rr}t=Ka(t,$a.bind(null,e))}e.callbackPriority=n,e.callbackNode=t}}function $a(e,n){if(xr=-1,Pr=0,R&6)throw Error(y(327));var t=e.callbackNode;if(Gn()&&e.callbackNode!==t)return null;var r=Mr(e,e===Z?q:0);if(r===0)return null;if(r&30||r&e.expiredLanes||n)n=Zr(e,r);else{n=r;var l=R;R|=2;var u=Aa();(Z!==e||q!==n)&&(Ue=null,tt=W()+500,En(e,n));do try{od();break}catch(o){Va(e,o)}while(!0);ui(),Yr.current=u,R=l,Q!==null?n=0:(Z=null,q=0,n=Y)}if(n!==0){if(n===2&&(l=lu(e),l!==0&&(r=l,n=Mu(e,l))),n===1)throw t=Qt,En(e,0),qe(e,r),de(e,W()),t;if(n===6)qe(e,r);else{if(l=e.current.alternate,!(r&30)&&!ud(l)&&(n=Zr(e,r),n===2&&(u=lu(e),u!==0&&(r=u,n=Mu(e,u))),n===1))throw t=Qt,En(e,0),qe(e,r),de(e,W()),t;switch(e.finishedWork=l,e.finishedLanes=r,n){case 0:case 1:throw Error(y(345));case 2:gn(e,se,Ue);break;case 3:if(qe(e,r),(r&130023424)===r&&(n=ki+500-W(),10<n)){if(Mr(e,0)!==0)break;if(l=e.suspendedLanes,(l&r)!==r){ue(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=du(gn.bind(null,e,se,Ue),n);break}gn(e,se,Ue);break;case 4:if(qe(e,r),(r&4194240)===r)break;for(n=e.eventTimes,l=-1;0<r;){var i=31-Le(r);u=1<<i,i=n[i],i>l&&(l=i),r&=~u}if(r=l,r=W()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*ld(r/1960))-r,10<r){e.timeoutHandle=du(gn.bind(null,e,se,Ue),r);break}gn(e,se,Ue);break;case 5:gn(e,se,Ue);break;default:throw Error(y(329))}}}return de(e,W()),e.callbackNode===t?$a.bind(null,e):null}function Mu(e,n){var t=Nt;return e.current.memoizedState.isDehydrated&&(En(e,n).flags|=256),e=Zr(e,n),e!==2&&(n=se,se=t,n!==null&&Ou(n)),e}function Ou(e){se===null?se=e:se.push.apply(se,e)}function ud(e){for(var n=e;;){if(n.flags&16384){var t=n.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var r=0;r<t.length;r++){var l=t[r],u=l.getSnapshot;l=l.value;try{if(!Me(u(),l))return!1}catch{return!1}}}if(t=n.child,n.subtreeFlags&16384&&t!==null)t.return=n,n=t;else{if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}function qe(e,n){for(n&=~wi,n&=~ol,e.suspendedLanes|=n,e.pingedLanes&=~n,e=e.expirationTimes;0<n;){var t=31-Le(n),r=1<<t;e[t]=-1,n&=~r}}function Io(e){if(R&6)throw Error(y(327));Gn();var n=Mr(e,0);if(!(n&1))return de(e,W()),null;var t=Zr(e,n);if(e.tag!==0&&t===2){var r=lu(e);r!==0&&(n=r,t=Mu(e,r))}if(t===1)throw t=Qt,En(e,0),qe(e,n),de(e,W()),t;if(t===6)throw Error(y(345));return e.finishedWork=e.current.alternate,e.finishedLanes=n,gn(e,se,Ue),de(e,W()),null}function Si(e,n){var t=R;R|=1;try{return e(n)}finally{R=t,R===0&&(tt=W()+500,rl&&mn())}}function zn(e){en!==null&&en.tag===0&&!(R&6)&&Gn();var n=R;R|=1;var t=Ee.transition,r=M;try{if(Ee.transition=null,M=1,e)return e()}finally{M=r,Ee.transition=t,R=n,!(R&6)&&mn()}}function Ei(){pe=Hn.current,I(Hn)}function En(e,n){e.finishedWork=null,e.finishedLanes=0;var t=e.timeoutHandle;if(t!==-1&&(e.timeoutHandle=-1,Ic(t)),Q!==null)for(t=Q.return;t!==null;){var r=t;switch(ti(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&jr();break;case 3:et(),I(fe),I(re),ci();break;case 5:fi(r);break;case 4:et();break;case 13:I(U);break;case 19:I(U);break;case 10:ii(r.type._context);break;case 22:case 23:Ei()}t=t.return}if(Z=e,Q=e=an(e.current,null),q=pe=n,Y=0,Qt=null,wi=ol=Nn=0,se=Nt=null,kn!==null){for(n=0;n<kn.length;n++)if(t=kn[n],r=t.interleaved,r!==null){t.interleaved=null;var l=r.next,u=t.pending;if(u!==null){var i=u.next;u.next=l,r.next=i}t.pending=r}kn=null}return e}function Va(e,n){do{var t=Q;try{if(ui(),Er.current=Kr,Qr){for(var r=$.memoizedState;r!==null;){var l=r.queue;l!==null&&(l.pending=null),r=r.next}Qr=!1}if(Pn=0,G=K=$=null,xt=!1,Bt=0,gi.current=null,t===null||t.return===null){Y=1,Qt=n,Q=null;break}e:{var u=e,i=t.return,o=t,s=n;if(n=q,o.flags|=32768,s!==null&&typeof s=="object"&&typeof s.then=="function"){var f=s,h=o,m=h.tag;if(!(h.mode&1)&&(m===0||m===11||m===15)){var p=h.alternate;p?(h.updateQueue=p.updateQueue,h.memoizedState=p.memoizedState,h.lanes=p.lanes):(h.updateQueue=null,h.memoizedState=null)}var g=Eo(i);if(g!==null){g.flags&=-257,Co(g,i,o,u,n),g.mode&1&&So(u,f,n),n=g,s=f;var w=n.updateQueue;if(w===null){var k=new Set;k.add(s),n.updateQueue=k}else w.add(s);break e}else{if(!(n&1)){So(u,f,n),Ci();break e}s=Error(y(426))}}else if(j&&o.mode&1){var F=Eo(i);if(F!==null){!(F.flags&65536)&&(F.flags|=256),Co(F,i,o,u,n),ri(nt(s,o));break e}}u=s=nt(s,o),Y!==4&&(Y=2),Nt===null?Nt=[u]:Nt.push(u),u=i;do{switch(u.tag){case 3:u.flags|=65536,n&=-n,u.lanes|=n;var c=Ca(u,s,n);ho(u,c);break e;case 1:o=s;var a=u.type,d=u.stateNode;if(!(u.flags&128)&&(typeof a.getDerivedStateFromError=="function"||d!==null&&typeof d.componentDidCatch=="function"&&(on===null||!on.has(d)))){u.flags|=65536,n&=-n,u.lanes|=n;var v=_a(u,o,n);ho(u,v);break e}}u=u.return}while(u!==null)}Ha(t)}catch(E){n=E,Q===t&&t!==null&&(Q=t=t.return);continue}break}while(!0)}function Aa(){var e=Yr.current;return Yr.current=Kr,e===null?Kr:e}function Ci(){(Y===0||Y===3||Y===2)&&(Y=4),Z===null||!(Nn&268435455)&&!(ol&268435455)||qe(Z,q)}function Zr(e,n){var t=R;R|=2;var r=Aa();(Z!==e||q!==n)&&(Ue=null,En(e,n));do try{id();break}catch(l){Va(e,l)}while(!0);if(ui(),R=t,Yr.current=r,Q!==null)throw Error(y(261));return Z=null,q=0,Y}function id(){for(;Q!==null;)Ba(Q)}function od(){for(;Q!==null&&!Mf();)Ba(Q)}function Ba(e){var n=Qa(e.alternate,e,pe);e.memoizedProps=e.pendingProps,n===null?Ha(e):Q=n,gi.current=null}function Ha(e){var n=e;do{var t=n.alternate;if(e=n.return,n.flags&32768){if(t=ed(t,n),t!==null){t.flags&=32767,Q=t;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Y=6,Q=null;return}}else if(t=bc(t,n,pe),t!==null){Q=t;return}if(n=n.sibling,n!==null){Q=n;return}Q=n=e}while(n!==null);Y===0&&(Y=5)}function gn(e,n,t){var r=M,l=Ee.transition;try{Ee.transition=null,M=1,sd(e,n,t,r)}finally{Ee.transition=l,M=r}return null}function sd(e,n,t,r){do Gn();while(en!==null);if(R&6)throw Error(y(327));t=e.finishedWork;var l=e.finishedLanes;if(t===null)return null;if(e.finishedWork=null,e.finishedLanes=0,t===e.current)throw Error(y(177));e.callbackNode=null,e.callbackPriority=0;var u=t.lanes|t.childLanes;if(Bf(e,u),e===Z&&(Q=Z=null,q=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||mr||(mr=!0,Ka(Rr,function(){return Gn(),null})),u=(t.flags&15990)!==0,t.subtreeFlags&15990||u){u=Ee.transition,Ee.transition=null;var i=M;M=1;var o=R;R|=4,gi.current=null,td(e,t),ja(t,e),zc(fu),Or=!!au,fu=au=null,e.current=t,rd(t),Of(),R=o,M=i,Ee.transition=u}else e.current=t;if(mr&&(mr=!1,en=e,Gr=l),u=e.pendingLanes,u===0&&(on=null),Ff(t.stateNode),de(e,W()),n!==null)for(r=e.onRecoverableError,t=0;t<n.length;t++)l=n[t],r(l.value,{componentStack:l.stack,digest:l.digest});if(Xr)throw Xr=!1,e=Lu,Lu=null,e;return Gr&1&&e.tag!==0&&Gn(),u=e.pendingLanes,u&1?e===Ru?zt++:(zt=0,Ru=e):zt=0,mn(),null}function Gn(){if(en!==null){var e=Cs(Gr),n=Ee.transition,t=M;try{if(Ee.transition=null,M=16>e?16:e,en===null)var r=!1;else{if(e=en,en=null,Gr=0,R&6)throw Error(y(331));var l=R;for(R|=4,S=e.current;S!==null;){var u=S,i=u.child;if(S.flags&16){var o=u.deletions;if(o!==null){for(var s=0;s<o.length;s++){var f=o[s];for(S=f;S!==null;){var h=S;switch(h.tag){case 0:case 11:case 15:Pt(8,h,u)}var m=h.child;if(m!==null)m.return=h,S=m;else for(;S!==null;){h=S;var p=h.sibling,g=h.return;if(Da(h),h===f){S=null;break}if(p!==null){p.return=g,S=p;break}S=g}}}var w=u.alternate;if(w!==null){var k=w.child;if(k!==null){w.child=null;do{var F=k.sibling;k.sibling=null,k=F}while(k!==null)}}S=u}}if(u.subtreeFlags&2064&&i!==null)i.return=u,S=i;else e:for(;S!==null;){if(u=S,u.flags&2048)switch(u.tag){case 0:case 11:case 15:Pt(9,u,u.return)}var c=u.sibling;if(c!==null){c.return=u.return,S=c;break e}S=u.return}}var a=e.current;for(S=a;S!==null;){i=S;var d=i.child;if(i.subtreeFlags&2064&&d!==null)d.return=i,S=d;else e:for(i=a;S!==null;){if(o=S,o.flags&2048)try{switch(o.tag){case 0:case 11:case 15:il(9,o)}}catch(E){A(o,o.return,E)}if(o===i){S=null;break e}var v=o.sibling;if(v!==null){v.return=o.return,S=v;break e}S=o.return}}if(R=l,mn(),Fe&&typeof Fe.onPostCommitFiberRoot=="function")try{Fe.onPostCommitFiberRoot(qr,e)}catch{}r=!0}return r}finally{M=t,Ee.transition=n}}return!1}function Fo(e,n,t){n=nt(t,n),n=Ca(e,n,1),e=un(e,n,1),n=ue(),e!==null&&(Yt(e,1,n),de(e,n))}function A(e,n,t){if(e.tag===3)Fo(e,e,t);else for(;n!==null;){if(n.tag===3){Fo(n,e,t);break}else if(n.tag===1){var r=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(on===null||!on.has(r))){e=nt(t,e),e=_a(n,e,1),n=un(n,e,1),e=ue(),n!==null&&(Yt(n,1,e),de(n,e));break}}n=n.return}}function ad(e,n,t){var r=e.pingCache;r!==null&&r.delete(n),n=ue(),e.pingedLanes|=e.suspendedLanes&t,Z===e&&(q&t)===t&&(Y===4||Y===3&&(q&130023424)===q&&500>W()-ki?En(e,0):wi|=t),de(e,n)}function Wa(e,n){n===0&&(e.mode&1?(n=lr,lr<<=1,!(lr&130023424)&&(lr=4194304)):n=1);var t=ue();e=Qe(e,n),e!==null&&(Yt(e,n,t),de(e,t))}function fd(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),Wa(e,t)}function cd(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(y(314))}r!==null&&r.delete(n),Wa(e,t)}var Qa;Qa=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||fe.current)ae=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return ae=!1,qc(e,n,t);ae=!!(e.flags&131072)}else ae=!1,j&&n.flags&1048576&&Gs(n,Vr,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;_r(e,n),e=n.pendingProps;var l=Jn(n,re.current);Xn(n,t),l=pi(null,n,r,e,l,t);var u=mi();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,ce(r)?(u=!0,Ur(n)):u=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,si(n),l.updater=ul,n.stateNode=l,l._reactInternals=n,wu(n,r,e,t),n=Eu(null,n,r,!0,u,t)):(n.tag=0,j&&u&&ni(n),le(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(_r(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=pd(r),e=Ne(r,e),l){case 0:n=Su(null,n,r,e,t);break e;case 1:n=Po(null,n,r,e,t);break e;case 11:n=_o(null,n,r,e,t);break e;case 14:n=xo(null,n,r,Ne(r.type,e),t);break e}throw Error(y(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:Ne(r,l),Su(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:Ne(r,l),Po(e,n,r,l,t);case 3:e:{if(za(n),e===null)throw Error(y(387));r=n.pendingProps,u=n.memoizedState,l=u.element,na(e,n),Hr(n,r,null,t);var i=n.memoizedState;if(r=i.element,u.isDehydrated)if(u={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},n.updateQueue.baseState=u,n.memoizedState=u,n.flags&256){l=nt(Error(y(423)),n),n=No(e,n,r,t,l);break e}else if(r!==l){l=nt(Error(y(424)),n),n=No(e,n,r,t,l);break e}else for(me=ln(n.stateNode.containerInfo.firstChild),he=n,j=!0,Te=null,t=bs(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(qn(),r===l){n=Ke(e,n,t);break e}le(e,n,r,t)}n=n.child}return n;case 5:return ta(n),e===null&&vu(n),r=n.type,l=n.pendingProps,u=e!==null?e.memoizedProps:null,i=l.children,cu(r,l)?i=null:u!==null&&cu(r,u)&&(n.flags|=32),Na(e,n),le(e,n,i,t),n.child;case 6:return e===null&&vu(n),null;case 13:return Ta(e,n,t);case 4:return ai(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=bn(n,null,r,t):le(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:Ne(r,l),_o(e,n,r,l,t);case 7:return le(e,n,n.pendingProps,t),n.child;case 8:return le(e,n,n.pendingProps.children,t),n.child;case 12:return le(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,u=n.memoizedProps,i=l.value,O(Ar,r._currentValue),r._currentValue=i,u!==null)if(Me(u.value,i)){if(u.children===l.children&&!fe.current){n=Ke(e,n,t);break e}}else for(u=n.child,u!==null&&(u.return=n);u!==null;){var o=u.dependencies;if(o!==null){i=u.child;for(var s=o.firstContext;s!==null;){if(s.context===r){if(u.tag===1){s=Be(-1,t&-t),s.tag=2;var f=u.updateQueue;if(f!==null){f=f.shared;var h=f.pending;h===null?s.next=s:(s.next=h.next,h.next=s),f.pending=s}}u.lanes|=t,s=u.alternate,s!==null&&(s.lanes|=t),yu(u.return,t,n),o.lanes|=t;break}s=s.next}}else if(u.tag===10)i=u.type===n.type?null:u.child;else if(u.tag===18){if(i=u.return,i===null)throw Error(y(341));i.lanes|=t,o=i.alternate,o!==null&&(o.lanes|=t),yu(i,t,n),i=u.sibling}else i=u.child;if(i!==null)i.return=u;else for(i=u;i!==null;){if(i===n){i=null;break}if(u=i.sibling,u!==null){u.return=i.return,i=u;break}i=i.return}u=i}le(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,Xn(n,t),l=Ce(l),r=r(l),n.flags|=1,le(e,n,r,t),n.child;case 14:return r=n.type,l=Ne(r,n.pendingProps),l=Ne(r.type,l),xo(e,n,r,l,t);case 15:return xa(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:Ne(r,l),_r(e,n),n.tag=1,ce(r)?(e=!0,Ur(n)):e=!1,Xn(n,t),Ea(n,r,l),wu(n,r,l,t),Eu(null,n,r,!0,e,t);case 19:return La(e,n,t);case 22:return Pa(e,n,t)}throw Error(y(156,n.tag))};function Ka(e,n){return ws(e,n)}function dd(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Se(e,n,t,r){return new dd(e,n,t,r)}function _i(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pd(e){if(typeof e=="function")return _i(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Hu)return 11;if(e===Wu)return 14}return 2}function an(e,n){var t=e.alternate;return t===null?(t=Se(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Nr(e,n,t,r,l,u){var i=2;if(r=e,typeof e=="function")_i(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case On:return Cn(t.children,l,u,n);case Bu:i=8,l|=8;break;case Hl:return e=Se(12,t,n,l|2),e.elementType=Hl,e.lanes=u,e;case Wl:return e=Se(13,t,n,l),e.elementType=Wl,e.lanes=u,e;case Ql:return e=Se(19,t,n,l),e.elementType=Ql,e.lanes=u,e;case ts:return sl(t,l,u,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case es:i=10;break e;case ns:i=9;break e;case Hu:i=11;break e;case Wu:i=14;break e;case Ge:i=16,r=null;break e}throw Error(y(130,e==null?e:typeof e,""))}return n=Se(i,t,n,l),n.elementType=e,n.type=r,n.lanes=u,n}function Cn(e,n,t,r){return e=Se(7,e,r,n),e.lanes=t,e}function sl(e,n,t,r){return e=Se(22,e,r,n),e.elementType=ts,e.lanes=t,e.stateNode={isHidden:!1},e}function Vl(e,n,t){return e=Se(6,e,null,n),e.lanes=t,e}function Al(e,n,t){return n=Se(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function md(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Sl(0),this.expirationTimes=Sl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Sl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function xi(e,n,t,r,l,u,i,o,s){return e=new md(e,n,t,o,s),n===1?(n=1,u===!0&&(n|=8)):n=0,u=Se(3,null,null,n),e.current=u,u.stateNode=e,u.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},si(u),e}function hd(e,n,t){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Mn,key:r==null?null:""+r,children:e,containerInfo:n,implementation:t}}function Ya(e){if(!e)return cn;e=e._reactInternals;e:{if(Ln(e)!==e||e.tag!==1)throw Error(y(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(ce(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(n!==null);throw Error(y(171))}if(e.tag===1){var t=e.type;if(ce(t))return Ys(e,t,n)}return n}function Xa(e,n,t,r,l,u,i,o,s){return e=xi(t,r,!0,e,l,u,i,o,s),e.context=Ya(null),t=e.current,r=ue(),l=sn(t),u=Be(r,l),u.callback=n??null,un(t,u,l),e.current.lanes=l,Yt(e,l,r),de(e,r),e}function al(e,n,t,r){var l=n.current,u=ue(),i=sn(l);return t=Ya(t),n.context===null?n.context=t:n.pendingContext=t,n=Be(u,i),n.payload={element:e},r=r===void 0?null:r,r!==null&&(n.callback=r),e=un(l,n,i),e!==null&&(Re(e,l,i,u),Sr(e,l,i)),i}function Jr(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function jo(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t<n?t:n}}function Pi(e,n){jo(e,n),(e=e.alternate)&&jo(e,n)}var Ga=typeof reportError=="function"?reportError:function(e){console.error(e)};function Ni(e){this._internalRoot=e}fl.prototype.render=Ni.prototype.render=function(e){var n=this._internalRoot;if(n===null)throw Error(y(409));al(e,n,null,null)};fl.prototype.unmount=Ni.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var n=e.containerInfo;zn(function(){al(null,e,null,null)}),n[We]=null}};function fl(e){this._internalRoot=e}fl.prototype.unstable_scheduleHydration=function(e){if(e){var n=Ps();e={blockedOn:null,target:e,priority:n};for(var t=0;t<Je.length&&n!==0&&n<Je[t].priority;t++);Je.splice(t,0,e),t===0&&zs(e)}};function zi(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function cl(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function Uo(){}function vd(e,n,t,r,l){if(l){if(typeof r=="function"){var u=r;r=function(){var f=Jr(i);u.call(f)}}var i=Xa(n,r,e,0,null,!1,!1,"",Uo);return e._reactRootContainer=i,e[We]=i.current,jt(e.nodeType===8?e.parentNode:e),zn(),i}for(;l=e.lastChild;)e.removeChild(l);if(typeof r=="function"){var o=r;r=function(){var f=Jr(s);o.call(f)}}var s=xi(e,0,!1,null,null,!1,!1,"",Uo);return e._reactRootContainer=s,e[We]=s.current,jt(e.nodeType===8?e.parentNode:e),zn(function(){al(n,s,t,r)}),s}function dl(e,n,t,r,l){var u=t._reactRootContainer;if(u){var i=u;if(typeof l=="function"){var o=l;l=function(){var s=Jr(i);o.call(s)}}al(n,i,e,l)}else i=vd(t,n,e,l,r);return Jr(i)}_s=function(e){switch(e.tag){case 3:var n=e.stateNode;if(n.current.memoizedState.isDehydrated){var t=gt(n.pendingLanes);t!==0&&(Yu(n,t|1),de(n,W()),!(R&6)&&(tt=W()+500,mn()))}break;case 13:zn(function(){var r=Qe(e,1);if(r!==null){var l=ue();Re(r,e,1,l)}}),Pi(e,1)}};Xu=function(e){if(e.tag===13){var n=Qe(e,134217728);if(n!==null){var t=ue();Re(n,e,134217728,t)}Pi(e,134217728)}};xs=function(e){if(e.tag===13){var n=sn(e),t=Qe(e,n);if(t!==null){var r=ue();Re(t,e,n,r)}Pi(e,n)}};Ps=function(){return M};Ns=function(e,n){var t=M;try{return M=e,n()}finally{M=t}};nu=function(e,n,t){switch(n){case"input":if(Xl(e,t),n=t.name,t.type==="radio"&&n!=null){for(t=e;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),n=0;n<t.length;n++){var r=t[n];if(r!==e&&r.form===e.form){var l=tl(r);if(!l)throw Error(y(90));ls(r),Xl(r,l)}}}break;case"textarea":is(e,t);break;case"select":n=t.value,n!=null&&Wn(e,!!t.multiple,n,!1)}};ps=Si;ms=zn;var yd={usingClientEntryPoint:!1,Events:[Gt,jn,tl,cs,ds,Si]},ht={findFiberByHostInstance:wn,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},gd={bundleType:ht.bundleType,version:ht.version,rendererPackageName:ht.rendererPackageName,rendererConfig:ht.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Ye.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=ys(e),e===null?null:e.stateNode},findFiberByHostInstance:ht.findFiberByHostInstance,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var hr=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!hr.isDisabled&&hr.supportsFiber)try{qr=hr.inject(gd),Fe=hr}catch{}}ye.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=yd;ye.createPortal=function(e,n){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!zi(n))throw Error(y(200));return hd(e,n,null,t)};ye.createRoot=function(e,n){if(!zi(e))throw Error(y(299));var t=!1,r="",l=Ga;return n!=null&&(n.unstable_strictMode===!0&&(t=!0),n.identifierPrefix!==void 0&&(r=n.identifierPrefix),n.onRecoverableError!==void 0&&(l=n.onRecoverableError)),n=xi(e,1,!1,null,null,t,!1,r,l),e[We]=n.current,jt(e.nodeType===8?e.parentNode:e),new Ni(n)};ye.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(y(188)):(e=Object.keys(e).join(","),Error(y(268,e)));return e=ys(n),e=e===null?null:e.stateNode,e};ye.flushSync=function(e){return zn(e)};ye.hydrate=function(e,n,t){if(!cl(n))throw Error(y(200));return dl(null,e,n,!0,t)};ye.hydrateRoot=function(e,n,t){if(!zi(e))throw Error(y(405));var r=t!=null&&t.hydratedSources||null,l=!1,u="",i=Ga;if(t!=null&&(t.unstable_strictMode===!0&&(l=!0),t.identifierPrefix!==void 0&&(u=t.identifierPrefix),t.onRecoverableError!==void 0&&(i=t.onRecoverableError)),n=Xa(n,null,e,1,t??null,l,!1,u,i),e[We]=n.current,jt(e),r)for(e=0;e<r.length;e++)t=r[e],l=t._getVersion,l=l(t._source),n.mutableSourceEagerHydrationData==null?n.mutableSourceEagerHydrationData=[t,l]:n.mutableSourceEagerHydrationData.push(t,l);return new fl(n)};ye.render=function(e,n,t){if(!cl(n))throw Error(y(200));return dl(null,e,n,!1,t)};ye.unmountComponentAtNode=function(e){if(!cl(e))throw Error(y(40));return e._reactRootContainer?(zn(function(){dl(null,null,e,!1,function(){e._reactRootContainer=null,e[We]=null})}),!0):!1};ye.unstable_batchedUpdates=Si;ye.unstable_renderSubtreeIntoContainer=function(e,n,t,r){if(!cl(t))throw Error(y(200));if(e==null||e._reactInternals===void 0)throw Error(y(38));return dl(e,n,t,!1,r)};ye.version="18.3.1-next-f1338f8080-20240426";function Za(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Za)}catch(e){console.error(e)}}Za(),Zo.exports=ye;var Ja=Zo.exports;const wd=Vo(Ja),Ed=$o({__proto__:null,default:wd},[Ja]);export{Sd as R,Ed as a,hf as b,Ja as c,wd as d,kd as e,Vo as g,Uu as r}; diff --git a/pkg/ui/frontend/dist/assets/react-router-Bj-soKrx.js b/pkg/ui/frontend/dist/assets/react-router-Bj-soKrx.js new file mode 100644 index 0000000000000..b0f79b109cbed --- /dev/null +++ b/pkg/ui/frontend/dist/assets/react-router-Bj-soKrx.js @@ -0,0 +1,29 @@ +import{r as v,R as en,a as tn,b as rn}from"./react-core-D_V7s-9r.js";/** + * @remix-run/router v1.21.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function V(){return V=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},V.apply(this,arguments)}var J;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(J||(J={}));const Gt="popstate";function nn(e){e===void 0&&(e={});function t(n,a){let{pathname:l,search:o,hash:d}=n.location;return Ze("",{pathname:l,search:o,hash:d},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function r(n,a){return typeof a=="string"?a:Le(a)}return on(t,r,null,e)}function U(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Ne(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function an(){return Math.random().toString(36).substr(2,8)}function Xt(e,t){return{usr:e.state,key:e.key,idx:t}}function Ze(e,t,r,n){return r===void 0&&(r=null),V({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?he(t):t,{state:r,key:t&&t.key||n||an()})}function Le(e){let{pathname:t="/",search:r="",hash:n=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function he(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let n=e.indexOf("?");n>=0&&(t.search=e.substr(n),e=e.substr(0,n)),e&&(t.pathname=e)}return t}function on(e,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:l=!1}=n,o=a.history,d=J.Pop,u=null,f=h();f==null&&(f=0,o.replaceState(V({},o.state,{idx:f}),""));function h(){return(o.state||{idx:null}).idx}function p(){d=J.Pop;let R=h(),j=R==null?null:R-f;f=R,u&&u({action:d,location:x.location,delta:j})}function y(R,j){d=J.Push;let M=Ze(x.location,R,j);f=h()+1;let I=Xt(M,f),k=x.createHref(M);try{o.pushState(I,"",k)}catch(X){if(X instanceof DOMException&&X.name==="DataCloneError")throw X;a.location.assign(k)}l&&u&&u({action:d,location:x.location,delta:1})}function b(R,j){d=J.Replace;let M=Ze(x.location,R,j);f=h();let I=Xt(M,f),k=x.createHref(M);o.replaceState(I,"",k),l&&u&&u({action:d,location:x.location,delta:0})}function S(R){let j=a.location.origin!=="null"?a.location.origin:a.location.href,M=typeof R=="string"?R:Le(R);return M=M.replace(/ $/,"%20"),U(j,"No window.location.(origin|href) available to create URL for href: "+M),new URL(M,j)}let x={get action(){return d},get location(){return e(a,o)},listen(R){if(u)throw new Error("A history only accepts one active listener");return a.addEventListener(Gt,p),u=R,()=>{a.removeEventListener(Gt,p),u=null}},createHref(R){return t(a,R)},createURL:S,encodeLocation(R){let j=S(R);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:y,replace:b,go(R){return o.go(R)}};return x}var z;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(z||(z={}));const ln=new Set(["lazy","caseSensitive","path","id","index","children"]);function sn(e){return e.index===!0}function pt(e,t,r,n){return r===void 0&&(r=[]),n===void 0&&(n={}),e.map((a,l)=>{let o=[...r,String(l)],d=typeof a.id=="string"?a.id:o.join("-");if(U(a.index!==!0||!a.children,"Cannot specify children on an index route"),U(!n[d],'Found a route id collision on id "'+d+`". Route id's must be globally unique within Data Router usages`),sn(a)){let u=V({},a,t(a),{id:d});return n[d]=u,u}else{let u=V({},a,t(a),{id:d,children:void 0});return n[d]=u,a.children&&(u.children=pt(a.children,t,o,n)),u}})}function xe(e,t,r){return r===void 0&&(r="/"),ht(e,t,r,!1)}function ht(e,t,r,n){let a=typeof t=="string"?he(t):t,l=Ae(a.pathname||"/",r);if(l==null)return null;let o=vr(e);dn(o);let d=null;for(let u=0;d==null&&u<o.length;++u){let f=Rn(l);d=bn(o[u],f,n)}return d}function un(e,t){let{route:r,pathname:n,params:a}=e;return{id:r.id,pathname:n,params:a,data:t[r.id],handle:r.handle}}function vr(e,t,r,n){t===void 0&&(t=[]),r===void 0&&(r=[]),n===void 0&&(n="");let a=(l,o,d)=>{let u={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:o,route:l};u.relativePath.startsWith("/")&&(U(u.relativePath.startsWith(n),'Absolute route path "'+u.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),u.relativePath=u.relativePath.slice(n.length));let f=fe([n,u.relativePath]),h=r.concat(u);l.children&&l.children.length>0&&(U(l.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+f+'".')),vr(l.children,t,h,f)),!(l.path==null&&!l.index)&&t.push({path:f,score:vn(f,l.index),routesMeta:h})};return e.forEach((l,o)=>{var d;if(l.path===""||!((d=l.path)!=null&&d.includes("?")))a(l,o);else for(let u of yr(l.path))a(l,o,u)}),t}function yr(e){let t=e.split("/");if(t.length===0)return[];let[r,...n]=t,a=r.endsWith("?"),l=r.replace(/\?$/,"");if(n.length===0)return a?[l,""]:[l];let o=yr(n.join("/")),d=[];return d.push(...o.map(u=>u===""?l:[l,u].join("/"))),a&&d.push(...o),d.map(u=>e.startsWith("/")&&u===""?"/":u)}function dn(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:yn(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const cn=/^:[\w-]+$/,fn=3,hn=2,pn=1,mn=10,gn=-2,Qt=e=>e==="*";function vn(e,t){let r=e.split("/"),n=r.length;return r.some(Qt)&&(n+=gn),t&&(n+=hn),r.filter(a=>!Qt(a)).reduce((a,l)=>a+(cn.test(l)?fn:l===""?pn:mn),n)}function yn(e,t){return e.length===t.length&&e.slice(0,-1).every((n,a)=>n===t[a])?e[e.length-1]-t[t.length-1]:0}function bn(e,t,r){r===void 0&&(r=!1);let{routesMeta:n}=e,a={},l="/",o=[];for(let d=0;d<n.length;++d){let u=n[d],f=d===n.length-1,h=l==="/"?t:t.slice(l.length)||"/",p=qe({path:u.relativePath,caseSensitive:u.caseSensitive,end:f},h),y=u.route;if(!p&&f&&r&&!n[n.length-1].route.index&&(p=qe({path:u.relativePath,caseSensitive:u.caseSensitive,end:!1},h)),!p)return null;Object.assign(a,p.params),o.push({params:a,pathname:fe([l,p.pathname]),pathnameBase:xn(fe([l,p.pathnameBase])),route:y}),p.pathnameBase!=="/"&&(l=fe([l,p.pathnameBase]))}return o}function qe(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[r,n]=wn(e.path,e.caseSensitive,e.end),a=t.match(r);if(!a)return null;let l=a[0],o=l.replace(/(.)\/+$/,"$1"),d=a.slice(1);return{params:n.reduce((f,h,p)=>{let{paramName:y,isOptional:b}=h;if(y==="*"){let x=d[p]||"";o=l.slice(0,l.length-x.length).replace(/(.)\/+$/,"$1")}const S=d[p];return b&&!S?f[y]=void 0:f[y]=(S||"").replace(/%2F/g,"/"),f},{}),pathname:l,pathnameBase:o,pattern:e}}function wn(e,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),Ne(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let n=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,d,u)=>(n.push({paramName:d,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(n.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),n]}function Rn(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ne(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Ae(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=e.charAt(r);return n&&n!=="/"?null:e.slice(r)||"/"}function En(e,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof e=="string"?he(e):e;return{pathname:r?r.startsWith("/")?r:Sn(r,t):t,search:Pn(n),hash:Dn(a)}}function Sn(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?r.length>1&&r.pop():a!=="."&&r.push(a)}),r.length>1?r.join("/"):"/"}function xt(e,t,r,n){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function br(e){return e.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function Ft(e,t){let r=br(e);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function _t(e,t,r,n){n===void 0&&(n=!1);let a;typeof e=="string"?a=he(e):(a=V({},e),U(!a.pathname||!a.pathname.includes("?"),xt("?","pathname","search",a)),U(!a.pathname||!a.pathname.includes("#"),xt("#","pathname","hash",a)),U(!a.search||!a.search.includes("#"),xt("#","search","hash",a)));let l=e===""||a.pathname==="",o=l?"/":a.pathname,d;if(o==null)d=r;else{let p=t.length-1;if(!n&&o.startsWith("..")){let y=o.split("/");for(;y[0]==="..";)y.shift(),p-=1;a.pathname=y.join("/")}d=p>=0?t[p]:"/"}let u=En(a,d),f=o&&o!=="/"&&o.endsWith("/"),h=(l||o===".")&&r.endsWith("/");return!u.pathname.endsWith("/")&&(f||h)&&(u.pathname+="/"),u}const fe=e=>e.join("/").replace(/\/\/+/g,"/"),xn=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Pn=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Dn=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class mt{constructor(t,r,n,a){a===void 0&&(a=!1),this.status=t,this.statusText=r||"",this.internal=a,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}}function vt(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const wr=["post","put","patch","delete"],Ln=new Set(wr),Cn=["get",...wr],Mn=new Set(Cn),Tn=new Set([301,302,303,307,308]),Un=new Set([307,308]),Pt={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Fn={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Je={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},Ot=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,_n=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),Rr="remix-router-transitions";function On(e){const t=e.window?e.window:typeof window<"u"?window:void 0,r=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",n=!r;U(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let a;if(e.mapRouteProperties)a=e.mapRouteProperties;else if(e.detectErrorBoundary){let i=e.detectErrorBoundary;a=s=>({hasErrorBoundary:i(s)})}else a=_n;let l={},o=pt(e.routes,a,void 0,l),d,u=e.basename||"/",f=e.dataStrategy||Nn,h=e.patchRoutesOnNavigation,p=V({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),y=null,b=new Set,S=null,x=null,R=null,j=e.hydrationData!=null,M=xe(o,e.history.location,u),I=null;if(M==null&&!h){let i=ae(404,{pathname:e.history.location.pathname}),{matches:s,route:c}=sr(o);M=s,I={[c.id]:i}}M&&!e.hydrationData&&st(M,o,e.history.location.pathname).active&&(M=null);let k;if(M)if(M.some(i=>i.route.lazy))k=!1;else if(!M.some(i=>i.route.loader))k=!0;else if(p.v7_partialHydration){let i=e.hydrationData?e.hydrationData.loaderData:null,s=e.hydrationData?e.hydrationData.errors:null;if(s){let c=M.findIndex(g=>s[g.route.id]!==void 0);k=M.slice(0,c+1).every(g=>!Ct(g.route,i,s))}else k=M.every(c=>!Ct(c.route,i,s))}else k=e.hydrationData!=null;else if(k=!1,M=[],p.v7_partialHydration){let i=st(null,o,e.history.location.pathname);i.active&&i.matches&&(M=i.matches)}let X,m={historyAction:e.history.action,location:e.history.location,matches:M,initialized:k,navigation:Pt,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||I,fetchers:new Map,blockers:new Map},ee=J.Pop,F=!1,O,$=!1,te=new Map,Q=null,ne=!1,Z=!1,Me=[],nt=new Set,G=new Map,at=0,ke=-1,Te=new Map,ue=new Set,Ue=new Map,He=new Map,oe=new Set,be=new Map,we=new Map,it;function Ir(){if(y=e.history.listen(i=>{let{action:s,location:c,delta:g}=i;if(it){it(),it=void 0;return}Ne(we.size===0||g!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let w=Wt({currentLocation:m.location,nextLocation:c,historyAction:s});if(w&&g!=null){let L=new Promise(T=>{it=T});e.history.go(g*-1),lt(w,{state:"blocked",location:c,proceed(){lt(w,{state:"proceeding",proceed:void 0,reset:void 0,location:c}),L.then(()=>e.history.go(g))},reset(){let T=new Map(m.blockers);T.set(w,Je),re({blockers:T})}});return}return Re(s,c)}),r){Zn(t,te);let i=()=>qn(t,te);t.addEventListener("pagehide",i),Q=()=>t.removeEventListener("pagehide",i)}return m.initialized||Re(J.Pop,m.location,{initialHydration:!0}),X}function Nr(){y&&y(),Q&&Q(),b.clear(),O&&O.abort(),m.fetchers.forEach((i,s)=>ot(s)),m.blockers.forEach((i,s)=>Vt(s))}function Ar(i){return b.add(i),()=>b.delete(i)}function re(i,s){s===void 0&&(s={}),m=V({},m,i);let c=[],g=[];p.v7_fetcherPersist&&m.fetchers.forEach((w,L)=>{w.state==="idle"&&(oe.has(L)?g.push(L):c.push(L))}),oe.forEach(w=>{!m.fetchers.has(w)&&!G.has(w)&&g.push(w)}),[...b].forEach(w=>w(m,{deletedFetchers:g,viewTransitionOpts:s.viewTransitionOpts,flushSync:s.flushSync===!0})),p.v7_fetcherPersist?(c.forEach(w=>m.fetchers.delete(w)),g.forEach(w=>ot(w))):g.forEach(w=>oe.delete(w))}function Fe(i,s,c){var g,w;let{flushSync:L}=c===void 0?{}:c,T=m.actionData!=null&&m.navigation.formMethod!=null&&le(m.navigation.formMethod)&&m.navigation.state==="loading"&&((g=i.state)==null?void 0:g._isRedirect)!==!0,P;s.actionData?Object.keys(s.actionData).length>0?P=s.actionData:P=null:T?P=m.actionData:P=null;let D=s.loaderData?or(m.loaderData,s.loaderData,s.matches||[],s.errors):m.loaderData,E=m.blockers;E.size>0&&(E=new Map(E),E.forEach((B,q)=>E.set(q,Je)));let C=F===!0||m.navigation.formMethod!=null&&le(m.navigation.formMethod)&&((w=i.state)==null?void 0:w._isRedirect)!==!0;d&&(o=d,d=void 0),ne||ee===J.Pop||(ee===J.Push?e.history.push(i,i.state):ee===J.Replace&&e.history.replace(i,i.state));let _;if(ee===J.Pop){let B=te.get(m.location.pathname);B&&B.has(i.pathname)?_={currentLocation:m.location,nextLocation:i}:te.has(i.pathname)&&(_={currentLocation:i,nextLocation:m.location})}else if($){let B=te.get(m.location.pathname);B?B.add(i.pathname):(B=new Set([i.pathname]),te.set(m.location.pathname,B)),_={currentLocation:m.location,nextLocation:i}}re(V({},s,{actionData:P,loaderData:D,historyAction:ee,location:i,initialized:!0,navigation:Pt,revalidation:"idle",restoreScrollPosition:Jt(i,s.matches||m.matches),preventScrollReset:C,blockers:E}),{viewTransitionOpts:_,flushSync:L===!0}),ee=J.Pop,F=!1,$=!1,ne=!1,Z=!1,Me=[]}async function It(i,s){if(typeof i=="number"){e.history.go(i);return}let c=Lt(m.location,m.matches,u,p.v7_prependBasename,i,p.v7_relativeSplatPath,s==null?void 0:s.fromRouteId,s==null?void 0:s.relative),{path:g,submission:w,error:L}=Zt(p.v7_normalizeFormMethod,!1,c,s),T=m.location,P=Ze(m.location,g,s&&s.state);P=V({},P,e.history.encodeLocation(P));let D=s&&s.replace!=null?s.replace:void 0,E=J.Push;D===!0?E=J.Replace:D===!1||w!=null&&le(w.formMethod)&&w.formAction===m.location.pathname+m.location.search&&(E=J.Replace);let C=s&&"preventScrollReset"in s?s.preventScrollReset===!0:void 0,_=(s&&s.flushSync)===!0,B=Wt({currentLocation:T,nextLocation:P,historyAction:E});if(B){lt(B,{state:"blocked",location:P,proceed(){lt(B,{state:"proceeding",proceed:void 0,reset:void 0,location:P}),It(i,s)},reset(){let q=new Map(m.blockers);q.set(B,Je),re({blockers:q})}});return}return await Re(E,P,{submission:w,pendingError:L,preventScrollReset:C,replace:s&&s.replace,enableViewTransition:s&&s.viewTransition,flushSync:_})}function zr(){if(wt(),re({revalidation:"loading"}),m.navigation.state!=="submitting"){if(m.navigation.state==="idle"){Re(m.historyAction,m.location,{startUninterruptedRevalidation:!0});return}Re(ee||m.historyAction,m.navigation.location,{overrideNavigation:m.navigation,enableViewTransition:$===!0})}}async function Re(i,s,c){O&&O.abort(),O=null,ee=i,ne=(c&&c.startUninterruptedRevalidation)===!0,Xr(m.location,m.matches),F=(c&&c.preventScrollReset)===!0,$=(c&&c.enableViewTransition)===!0;let g=d||o,w=c&&c.overrideNavigation,L=xe(g,s,u),T=(c&&c.flushSync)===!0,P=st(L,g,s.pathname);if(P.active&&P.matches&&(L=P.matches),!L){let{error:H,notFoundMatches:A,route:W}=Rt(s.pathname);Fe(s,{matches:A,loaderData:{},errors:{[W.id]:H}},{flushSync:T});return}if(m.initialized&&!Z&&Vn(m.location,s)&&!(c&&c.submission&&le(c.submission.formMethod))){Fe(s,{matches:L},{flushSync:T});return}O=new AbortController;let D=Be(e.history,s,O.signal,c&&c.submission),E;if(c&&c.pendingError)E=[Pe(L).route.id,{type:z.error,error:c.pendingError}];else if(c&&c.submission&&le(c.submission.formMethod)){let H=await kr(D,s,c.submission,L,P.active,{replace:c.replace,flushSync:T});if(H.shortCircuited)return;if(H.pendingActionResult){let[A,W]=H.pendingActionResult;if(ie(W)&&vt(W.error)&&W.error.status===404){O=null,Fe(s,{matches:H.matches,loaderData:{},errors:{[A]:W.error}});return}}L=H.matches||L,E=H.pendingActionResult,w=Dt(s,c.submission),T=!1,P.active=!1,D=Be(e.history,D.url,D.signal)}let{shortCircuited:C,matches:_,loaderData:B,errors:q}=await Hr(D,s,L,P.active,w,c&&c.submission,c&&c.fetcherSubmission,c&&c.replace,c&&c.initialHydration===!0,T,E);C||(O=null,Fe(s,V({matches:_||L},lr(E),{loaderData:B,errors:q})))}async function kr(i,s,c,g,w,L){L===void 0&&(L={}),wt();let T=Xn(s,c);if(re({navigation:T},{flushSync:L.flushSync===!0}),w){let E=await ut(g,s.pathname,i.signal);if(E.type==="aborted")return{shortCircuited:!0};if(E.type==="error"){let C=Pe(E.partialMatches).route.id;return{matches:E.partialMatches,pendingActionResult:[C,{type:z.error,error:E.error}]}}else if(E.matches)g=E.matches;else{let{notFoundMatches:C,error:_,route:B}=Rt(s.pathname);return{matches:C,pendingActionResult:[B.id,{type:z.error,error:_}]}}}let P,D=Xe(g,s);if(!D.route.action&&!D.route.lazy)P={type:z.error,error:ae(405,{method:i.method,pathname:s.pathname,routeId:D.route.id})};else if(P=(await $e("action",m,i,[D],g,null))[D.route.id],i.signal.aborted)return{shortCircuited:!0};if(De(P)){let E;return L&&L.replace!=null?E=L.replace:E=nr(P.response.headers.get("Location"),new URL(i.url),u)===m.location.pathname+m.location.search,await Ee(i,P,!0,{submission:c,replace:E}),{shortCircuited:!0}}if(ve(P))throw ae(400,{type:"defer-action"});if(ie(P)){let E=Pe(g,D.route.id);return(L&&L.replace)!==!0&&(ee=J.Push),{matches:g,pendingActionResult:[E.route.id,P]}}return{matches:g,pendingActionResult:[D.route.id,P]}}async function Hr(i,s,c,g,w,L,T,P,D,E,C){let _=w||Dt(s,L),B=L||T||dr(_),q=!ne&&(!p.v7_partialHydration||!D);if(g){if(q){let K=Nt(C);re(V({navigation:_},K!==void 0?{actionData:K}:{}),{flushSync:E})}let N=await ut(c,s.pathname,i.signal);if(N.type==="aborted")return{shortCircuited:!0};if(N.type==="error"){let K=Pe(N.partialMatches).route.id;return{matches:N.partialMatches,loaderData:{},errors:{[K]:N.error}}}else if(N.matches)c=N.matches;else{let{error:K,notFoundMatches:Oe,route:Ke}=Rt(s.pathname);return{matches:Oe,loaderData:{},errors:{[Ke.id]:K}}}}let H=d||o,[A,W]=er(e.history,m,c,B,s,p.v7_partialHydration&&D===!0,p.v7_skipActionErrorRevalidation,Z,Me,nt,oe,Ue,ue,H,u,C);if(Et(N=>!(c&&c.some(K=>K.route.id===N))||A&&A.some(K=>K.route.id===N)),ke=++at,A.length===0&&W.length===0){let N=Ht();return Fe(s,V({matches:c,loaderData:{},errors:C&&ie(C[1])?{[C[0]]:C[1].error}:null},lr(C),N?{fetchers:new Map(m.fetchers)}:{}),{flushSync:E}),{shortCircuited:!0}}if(q){let N={};if(!g){N.navigation=_;let K=Nt(C);K!==void 0&&(N.actionData=K)}W.length>0&&(N.fetchers=$r(W)),re(N,{flushSync:E})}W.forEach(N=>{me(N.key),N.controller&&G.set(N.key,N.controller)});let _e=()=>W.forEach(N=>me(N.key));O&&O.signal.addEventListener("abort",_e);let{loaderResults:Ve,fetcherResults:ce}=await At(m,c,A,W,i);if(i.signal.aborted)return{shortCircuited:!0};O&&O.signal.removeEventListener("abort",_e),W.forEach(N=>G.delete(N.key));let se=ft(Ve);if(se)return await Ee(i,se.result,!0,{replace:P}),{shortCircuited:!0};if(se=ft(ce),se)return ue.add(se.key),await Ee(i,se.result,!0,{replace:P}),{shortCircuited:!0};let{loaderData:St,errors:We}=ir(m,c,Ve,C,W,ce,be);be.forEach((N,K)=>{N.subscribe(Oe=>{(Oe||N.done)&&be.delete(K)})}),p.v7_partialHydration&&D&&m.errors&&(We=V({},m.errors,We));let Se=Ht(),dt=$t(ke),ct=Se||dt||W.length>0;return V({matches:c,loaderData:St,errors:We},ct?{fetchers:new Map(m.fetchers)}:{})}function Nt(i){if(i&&!ie(i[1]))return{[i[0]]:i[1].data};if(m.actionData)return Object.keys(m.actionData).length===0?null:m.actionData}function $r(i){return i.forEach(s=>{let c=m.fetchers.get(s.key),g=Ye(void 0,c?c.data:void 0);m.fetchers.set(s.key,g)}),new Map(m.fetchers)}function Vr(i,s,c,g){if(n)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");me(i);let w=(g&&g.flushSync)===!0,L=d||o,T=Lt(m.location,m.matches,u,p.v7_prependBasename,c,p.v7_relativeSplatPath,s,g==null?void 0:g.relative),P=xe(L,T,u),D=st(P,L,T);if(D.active&&D.matches&&(P=D.matches),!P){de(i,s,ae(404,{pathname:T}),{flushSync:w});return}let{path:E,submission:C,error:_}=Zt(p.v7_normalizeFormMethod,!0,T,g);if(_){de(i,s,_,{flushSync:w});return}let B=Xe(P,E),q=(g&&g.preventScrollReset)===!0;if(C&&le(C.formMethod)){Wr(i,s,E,B,P,D.active,w,q,C);return}Ue.set(i,{routeId:s,path:E}),Kr(i,s,E,B,P,D.active,w,q,C)}async function Wr(i,s,c,g,w,L,T,P,D){wt(),Ue.delete(i);function E(Y){if(!Y.route.action&&!Y.route.lazy){let je=ae(405,{method:D.formMethod,pathname:c,routeId:s});return de(i,s,je,{flushSync:T}),!0}return!1}if(!L&&E(g))return;let C=m.fetchers.get(i);pe(i,Qn(D,C),{flushSync:T});let _=new AbortController,B=Be(e.history,c,_.signal,D);if(L){let Y=await ut(w,c,B.signal);if(Y.type==="aborted")return;if(Y.type==="error"){de(i,s,Y.error,{flushSync:T});return}else if(Y.matches){if(w=Y.matches,g=Xe(w,c),E(g))return}else{de(i,s,ae(404,{pathname:c}),{flushSync:T});return}}G.set(i,_);let q=at,A=(await $e("action",m,B,[g],w,i))[g.route.id];if(B.signal.aborted){G.get(i)===_&&G.delete(i);return}if(p.v7_fetcherPersist&&oe.has(i)){if(De(A)||ie(A)){pe(i,ge(void 0));return}}else{if(De(A))if(G.delete(i),ke>q){pe(i,ge(void 0));return}else return ue.add(i),pe(i,Ye(D)),Ee(B,A,!1,{fetcherSubmission:D,preventScrollReset:P});if(ie(A)){de(i,s,A.error);return}}if(ve(A))throw ae(400,{type:"defer-action"});let W=m.navigation.location||m.location,_e=Be(e.history,W,_.signal),Ve=d||o,ce=m.navigation.state!=="idle"?xe(Ve,m.navigation.location,u):m.matches;U(ce,"Didn't find any matches after fetcher action");let se=++at;Te.set(i,se);let St=Ye(D,A.data);m.fetchers.set(i,St);let[We,Se]=er(e.history,m,ce,D,W,!1,p.v7_skipActionErrorRevalidation,Z,Me,nt,oe,Ue,ue,Ve,u,[g.route.id,A]);Se.filter(Y=>Y.key!==i).forEach(Y=>{let je=Y.key,Yt=m.fetchers.get(je),qr=Ye(void 0,Yt?Yt.data:void 0);m.fetchers.set(je,qr),me(je),Y.controller&&G.set(je,Y.controller)}),re({fetchers:new Map(m.fetchers)});let dt=()=>Se.forEach(Y=>me(Y.key));_.signal.addEventListener("abort",dt);let{loaderResults:ct,fetcherResults:N}=await At(m,ce,We,Se,_e);if(_.signal.aborted)return;_.signal.removeEventListener("abort",dt),Te.delete(i),G.delete(i),Se.forEach(Y=>G.delete(Y.key));let K=ft(ct);if(K)return Ee(_e,K.result,!1,{preventScrollReset:P});if(K=ft(N),K)return ue.add(K.key),Ee(_e,K.result,!1,{preventScrollReset:P});let{loaderData:Oe,errors:Ke}=ir(m,ce,ct,void 0,Se,N,be);if(m.fetchers.has(i)){let Y=ge(A.data);m.fetchers.set(i,Y)}$t(se),m.navigation.state==="loading"&&se>ke?(U(ee,"Expected pending action"),O&&O.abort(),Fe(m.navigation.location,{matches:ce,loaderData:Oe,errors:Ke,fetchers:new Map(m.fetchers)})):(re({errors:Ke,loaderData:or(m.loaderData,Oe,ce,Ke),fetchers:new Map(m.fetchers)}),Z=!1)}async function Kr(i,s,c,g,w,L,T,P,D){let E=m.fetchers.get(i);pe(i,Ye(D,E?E.data:void 0),{flushSync:T});let C=new AbortController,_=Be(e.history,c,C.signal);if(L){let A=await ut(w,c,_.signal);if(A.type==="aborted")return;if(A.type==="error"){de(i,s,A.error,{flushSync:T});return}else if(A.matches)w=A.matches,g=Xe(w,c);else{de(i,s,ae(404,{pathname:c}),{flushSync:T});return}}G.set(i,C);let B=at,H=(await $e("loader",m,_,[g],w,i))[g.route.id];if(ve(H)&&(H=await jt(H,_.signal,!0)||H),G.get(i)===C&&G.delete(i),!_.signal.aborted){if(oe.has(i)){pe(i,ge(void 0));return}if(De(H))if(ke>B){pe(i,ge(void 0));return}else{ue.add(i),await Ee(_,H,!1,{preventScrollReset:P});return}if(ie(H)){de(i,s,H.error);return}U(!ve(H),"Unhandled fetcher deferred data"),pe(i,ge(H.data))}}async function Ee(i,s,c,g){let{submission:w,fetcherSubmission:L,preventScrollReset:T,replace:P}=g===void 0?{}:g;s.response.headers.has("X-Remix-Revalidate")&&(Z=!0);let D=s.response.headers.get("Location");U(D,"Expected a Location header on the redirect Response"),D=nr(D,new URL(i.url),u);let E=Ze(m.location,D,{_isRedirect:!0});if(r){let A=!1;if(s.response.headers.has("X-Remix-Reload-Document"))A=!0;else if(Ot.test(D)){const W=e.history.createURL(D);A=W.origin!==t.location.origin||Ae(W.pathname,u)==null}if(A){P?t.location.replace(D):t.location.assign(D);return}}O=null;let C=P===!0||s.response.headers.has("X-Remix-Replace")?J.Replace:J.Push,{formMethod:_,formAction:B,formEncType:q}=m.navigation;!w&&!L&&_&&B&&q&&(w=dr(m.navigation));let H=w||L;if(Un.has(s.response.status)&&H&&le(H.formMethod))await Re(C,E,{submission:V({},H,{formAction:D}),preventScrollReset:T||F,enableViewTransition:c?$:void 0});else{let A=Dt(E,w);await Re(C,E,{overrideNavigation:A,fetcherSubmission:L,preventScrollReset:T||F,enableViewTransition:c?$:void 0})}}async function $e(i,s,c,g,w,L){let T,P={};try{T=await An(f,i,s,c,g,w,L,l,a)}catch(D){return g.forEach(E=>{P[E.route.id]={type:z.error,error:D}}),P}for(let[D,E]of Object.entries(T))if(Wn(E)){let C=E.result;P[D]={type:z.redirect,response:Hn(C,c,D,w,u,p.v7_relativeSplatPath)}}else P[D]=await kn(E);return P}async function At(i,s,c,g,w){let L=i.matches,T=$e("loader",i,w,c,s,null),P=Promise.all(g.map(async C=>{if(C.matches&&C.match&&C.controller){let B=(await $e("loader",i,Be(e.history,C.path,C.controller.signal),[C.match],C.matches,C.key))[C.match.route.id];return{[C.key]:B}}else return Promise.resolve({[C.key]:{type:z.error,error:ae(404,{pathname:C.path})}})})),D=await T,E=(await P).reduce((C,_)=>Object.assign(C,_),{});return await Promise.all([Yn(s,D,w.signal,L,i.loaderData),Gn(s,E,g)]),{loaderResults:D,fetcherResults:E}}function wt(){Z=!0,Me.push(...Et()),Ue.forEach((i,s)=>{G.has(s)&&nt.add(s),me(s)})}function pe(i,s,c){c===void 0&&(c={}),m.fetchers.set(i,s),re({fetchers:new Map(m.fetchers)},{flushSync:(c&&c.flushSync)===!0})}function de(i,s,c,g){g===void 0&&(g={});let w=Pe(m.matches,s);ot(i),re({errors:{[w.route.id]:c},fetchers:new Map(m.fetchers)},{flushSync:(g&&g.flushSync)===!0})}function zt(i){return He.set(i,(He.get(i)||0)+1),oe.has(i)&&oe.delete(i),m.fetchers.get(i)||Fn}function ot(i){let s=m.fetchers.get(i);G.has(i)&&!(s&&s.state==="loading"&&Te.has(i))&&me(i),Ue.delete(i),Te.delete(i),ue.delete(i),p.v7_fetcherPersist&&oe.delete(i),nt.delete(i),m.fetchers.delete(i)}function Jr(i){let s=(He.get(i)||0)-1;s<=0?(He.delete(i),oe.add(i),p.v7_fetcherPersist||ot(i)):He.set(i,s),re({fetchers:new Map(m.fetchers)})}function me(i){let s=G.get(i);s&&(s.abort(),G.delete(i))}function kt(i){for(let s of i){let c=zt(s),g=ge(c.data);m.fetchers.set(s,g)}}function Ht(){let i=[],s=!1;for(let c of ue){let g=m.fetchers.get(c);U(g,"Expected fetcher: "+c),g.state==="loading"&&(ue.delete(c),i.push(c),s=!0)}return kt(i),s}function $t(i){let s=[];for(let[c,g]of Te)if(g<i){let w=m.fetchers.get(c);U(w,"Expected fetcher: "+c),w.state==="loading"&&(me(c),Te.delete(c),s.push(c))}return kt(s),s.length>0}function Yr(i,s){let c=m.blockers.get(i)||Je;return we.get(i)!==s&&we.set(i,s),c}function Vt(i){m.blockers.delete(i),we.delete(i)}function lt(i,s){let c=m.blockers.get(i)||Je;U(c.state==="unblocked"&&s.state==="blocked"||c.state==="blocked"&&s.state==="blocked"||c.state==="blocked"&&s.state==="proceeding"||c.state==="blocked"&&s.state==="unblocked"||c.state==="proceeding"&&s.state==="unblocked","Invalid blocker state transition: "+c.state+" -> "+s.state);let g=new Map(m.blockers);g.set(i,s),re({blockers:g})}function Wt(i){let{currentLocation:s,nextLocation:c,historyAction:g}=i;if(we.size===0)return;we.size>1&&Ne(!1,"A router only supports one blocker at a time");let w=Array.from(we.entries()),[L,T]=w[w.length-1],P=m.blockers.get(L);if(!(P&&P.state==="proceeding")&&T({currentLocation:s,nextLocation:c,historyAction:g}))return L}function Rt(i){let s=ae(404,{pathname:i}),c=d||o,{matches:g,route:w}=sr(c);return Et(),{notFoundMatches:g,route:w,error:s}}function Et(i){let s=[];return be.forEach((c,g)=>{(!i||i(g))&&(c.cancel(),s.push(g),be.delete(g))}),s}function Gr(i,s,c){if(S=i,R=s,x=c||null,!j&&m.navigation===Pt){j=!0;let g=Jt(m.location,m.matches);g!=null&&re({restoreScrollPosition:g})}return()=>{S=null,R=null,x=null}}function Kt(i,s){return x&&x(i,s.map(g=>un(g,m.loaderData)))||i.key}function Xr(i,s){if(S&&R){let c=Kt(i,s);S[c]=R()}}function Jt(i,s){if(S){let c=Kt(i,s),g=S[c];if(typeof g=="number")return g}return null}function st(i,s,c){if(h)if(i){if(Object.keys(i[0].params).length>0)return{active:!0,matches:ht(s,c,u,!0)}}else return{active:!0,matches:ht(s,c,u,!0)||[]};return{active:!1,matches:null}}async function ut(i,s,c){if(!h)return{type:"success",matches:i};let g=i;for(;;){let w=d==null,L=d||o,T=l;try{await h({path:s,matches:g,patch:(E,C)=>{c.aborted||rr(E,C,L,T,a)}})}catch(E){return{type:"error",error:E,partialMatches:g}}finally{w&&!c.aborted&&(o=[...o])}if(c.aborted)return{type:"aborted"};let P=xe(L,s,u);if(P)return{type:"success",matches:P};let D=ht(L,s,u,!0);if(!D||g.length===D.length&&g.every((E,C)=>E.route.id===D[C].route.id))return{type:"success",matches:null};g=D}}function Qr(i){l={},d=pt(i,a,void 0,l)}function Zr(i,s){let c=d==null;rr(i,s,d||o,l,a),c&&(o=[...o],re({}))}return X={get basename(){return u},get future(){return p},get state(){return m},get routes(){return o},get window(){return t},initialize:Ir,subscribe:Ar,enableScrollRestoration:Gr,navigate:It,fetch:Vr,revalidate:zr,createHref:i=>e.history.createHref(i),encodeLocation:i=>e.history.encodeLocation(i),getFetcher:zt,deleteFetcher:Jr,dispose:Nr,getBlocker:Yr,deleteBlocker:Vt,patchRoutes:Zr,_internalFetchControllers:G,_internalActiveDeferreds:be,_internalSetRoutes:Qr},X}function jn(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Lt(e,t,r,n,a,l,o,d){let u,f;if(o){u=[];for(let p of t)if(u.push(p),p.route.id===o){f=p;break}}else u=t,f=t[t.length-1];let h=_t(a||".",Ft(u,l),Ae(e.pathname,r)||e.pathname,d==="path");if(a==null&&(h.search=e.search,h.hash=e.hash),(a==null||a===""||a===".")&&f){let p=Bt(h.search);if(f.route.index&&!p)h.search=h.search?h.search.replace(/^\?/,"?index&"):"?index";else if(!f.route.index&&p){let y=new URLSearchParams(h.search),b=y.getAll("index");y.delete("index"),b.filter(x=>x).forEach(x=>y.append("index",x));let S=y.toString();h.search=S?"?"+S:""}}return n&&r!=="/"&&(h.pathname=h.pathname==="/"?r:fe([r,h.pathname])),Le(h)}function Zt(e,t,r,n){if(!n||!jn(n))return{path:r};if(n.formMethod&&!Jn(n.formMethod))return{path:r,error:ae(405,{method:n.formMethod})};let a=()=>({path:r,error:ae(400,{type:"invalid-body"})}),l=n.formMethod||"get",o=e?l.toUpperCase():l.toLowerCase(),d=xr(r);if(n.body!==void 0){if(n.formEncType==="text/plain"){if(!le(o))return a();let y=typeof n.body=="string"?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((b,S)=>{let[x,R]=S;return""+b+x+"="+R+` +`},""):String(n.body);return{path:r,submission:{formMethod:o,formAction:d,formEncType:n.formEncType,formData:void 0,json:void 0,text:y}}}else if(n.formEncType==="application/json"){if(!le(o))return a();try{let y=typeof n.body=="string"?JSON.parse(n.body):n.body;return{path:r,submission:{formMethod:o,formAction:d,formEncType:n.formEncType,formData:void 0,json:y,text:void 0}}}catch{return a()}}}U(typeof FormData=="function","FormData is not available in this environment");let u,f;if(n.formData)u=Mt(n.formData),f=n.formData;else if(n.body instanceof FormData)u=Mt(n.body),f=n.body;else if(n.body instanceof URLSearchParams)u=n.body,f=ar(u);else if(n.body==null)u=new URLSearchParams,f=new FormData;else try{u=new URLSearchParams(n.body),f=ar(u)}catch{return a()}let h={formMethod:o,formAction:d,formEncType:n&&n.formEncType||"application/x-www-form-urlencoded",formData:f,json:void 0,text:void 0};if(le(h.formMethod))return{path:r,submission:h};let p=he(r);return t&&p.search&&Bt(p.search)&&u.append("index",""),p.search="?"+u,{path:Le(p),submission:h}}function qt(e,t,r){r===void 0&&(r=!1);let n=e.findIndex(a=>a.route.id===t);return n>=0?e.slice(0,r?n+1:n):e}function er(e,t,r,n,a,l,o,d,u,f,h,p,y,b,S,x){let R=x?ie(x[1])?x[1].error:x[1].data:void 0,j=e.createURL(t.location),M=e.createURL(a),I=r;l&&t.errors?I=qt(r,Object.keys(t.errors)[0],!0):x&&ie(x[1])&&(I=qt(r,x[0]));let k=x?x[1].statusCode:void 0,X=o&&k&&k>=400,m=I.filter((F,O)=>{let{route:$}=F;if($.lazy)return!0;if($.loader==null)return!1;if(l)return Ct($,t.loaderData,t.errors);if(Bn(t.loaderData,t.matches[O],F)||u.some(ne=>ne===F.route.id))return!0;let te=t.matches[O],Q=F;return tr(F,V({currentUrl:j,currentParams:te.params,nextUrl:M,nextParams:Q.params},n,{actionResult:R,actionStatus:k,defaultShouldRevalidate:X?!1:d||j.pathname+j.search===M.pathname+M.search||j.search!==M.search||Er(te,Q)}))}),ee=[];return p.forEach((F,O)=>{if(l||!r.some(Z=>Z.route.id===F.routeId)||h.has(O))return;let $=xe(b,F.path,S);if(!$){ee.push({key:O,routeId:F.routeId,path:F.path,matches:null,match:null,controller:null});return}let te=t.fetchers.get(O),Q=Xe($,F.path),ne=!1;y.has(O)?ne=!1:f.has(O)?(f.delete(O),ne=!0):te&&te.state!=="idle"&&te.data===void 0?ne=d:ne=tr(Q,V({currentUrl:j,currentParams:t.matches[t.matches.length-1].params,nextUrl:M,nextParams:r[r.length-1].params},n,{actionResult:R,actionStatus:k,defaultShouldRevalidate:X?!1:d})),ne&&ee.push({key:O,routeId:F.routeId,path:F.path,matches:$,match:Q,controller:new AbortController})}),[m,ee]}function Ct(e,t,r){if(e.lazy)return!0;if(!e.loader)return!1;let n=t!=null&&t[e.id]!==void 0,a=r!=null&&r[e.id]!==void 0;return!n&&a?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!n&&!a}function Bn(e,t,r){let n=!t||r.route.id!==t.route.id,a=e[r.route.id]===void 0;return n||a}function Er(e,t){let r=e.route.path;return e.pathname!==t.pathname||r!=null&&r.endsWith("*")&&e.params["*"]!==t.params["*"]}function tr(e,t){if(e.route.shouldRevalidate){let r=e.route.shouldRevalidate(t);if(typeof r=="boolean")return r}return t.defaultShouldRevalidate}function rr(e,t,r,n,a){var l;let o;if(e){let f=n[e];U(f,"No route found to patch children into: routeId = "+e),f.children||(f.children=[]),o=f.children}else o=r;let d=t.filter(f=>!o.some(h=>Sr(f,h))),u=pt(d,a,[e||"_","patch",String(((l=o)==null?void 0:l.length)||"0")],n);o.push(...u)}function Sr(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((r,n)=>{var a;return(a=t.children)==null?void 0:a.some(l=>Sr(r,l))}):!1}async function In(e,t,r){if(!e.lazy)return;let n=await e.lazy();if(!e.lazy)return;let a=r[e.id];U(a,"No route found in manifest");let l={};for(let o in n){let u=a[o]!==void 0&&o!=="hasErrorBoundary";Ne(!u,'Route "'+a.id+'" has a static property "'+o+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+o+'" will be ignored.')),!u&&!ln.has(o)&&(l[o]=n[o])}Object.assign(a,l),Object.assign(a,V({},t(a),{lazy:void 0}))}async function Nn(e){let{matches:t}=e,r=t.filter(a=>a.shouldLoad);return(await Promise.all(r.map(a=>a.resolve()))).reduce((a,l,o)=>Object.assign(a,{[r[o].route.id]:l}),{})}async function An(e,t,r,n,a,l,o,d,u,f){let h=l.map(b=>b.route.lazy?In(b.route,u,d):void 0),p=l.map((b,S)=>{let x=h[S],R=a.some(M=>M.route.id===b.route.id);return V({},b,{shouldLoad:R,resolve:async M=>(M&&n.method==="GET"&&(b.route.lazy||b.route.loader)&&(R=!0),R?zn(t,n,b,x,M,f):Promise.resolve({type:z.data,result:void 0}))})}),y=await e({matches:p,request:n,params:l[0].params,fetcherKey:o,context:f});try{await Promise.all(h)}catch{}return y}async function zn(e,t,r,n,a,l){let o,d,u=f=>{let h,p=new Promise((S,x)=>h=x);d=()=>h(),t.signal.addEventListener("abort",d);let y=S=>typeof f!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+r.route.id+"]"))):f({request:t,params:r.params,context:l},...S!==void 0?[S]:[]),b=(async()=>{try{return{type:"data",result:await(a?a(x=>y(x)):y())}}catch(S){return{type:"error",result:S}}})();return Promise.race([b,p])};try{let f=r.route[e];if(n)if(f){let h,[p]=await Promise.all([u(f).catch(y=>{h=y}),n]);if(h!==void 0)throw h;o=p}else if(await n,f=r.route[e],f)o=await u(f);else if(e==="action"){let h=new URL(t.url),p=h.pathname+h.search;throw ae(405,{method:t.method,pathname:p,routeId:r.route.id})}else return{type:z.data,result:void 0};else if(f)o=await u(f);else{let h=new URL(t.url),p=h.pathname+h.search;throw ae(404,{pathname:p})}U(o.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+r.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(f){return{type:z.error,result:f}}finally{d&&t.signal.removeEventListener("abort",d)}return o}async function kn(e){let{result:t,type:r}=e;if(Pr(t)){let f;try{let h=t.headers.get("Content-Type");h&&/\bapplication\/json\b/.test(h)?t.body==null?f=null:f=await t.json():f=await t.text()}catch(h){return{type:z.error,error:h}}return r===z.error?{type:z.error,error:new mt(t.status,t.statusText,f),statusCode:t.status,headers:t.headers}:{type:z.data,data:f,statusCode:t.status,headers:t.headers}}if(r===z.error){if(ur(t)){var n;if(t.data instanceof Error){var a;return{type:z.error,error:t.data,statusCode:(a=t.init)==null?void 0:a.status}}t=new mt(((n=t.init)==null?void 0:n.status)||500,void 0,t.data)}return{type:z.error,error:t,statusCode:vt(t)?t.status:void 0}}if(Kn(t)){var l,o;return{type:z.deferred,deferredData:t,statusCode:(l=t.init)==null?void 0:l.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}if(ur(t)){var d,u;return{type:z.data,data:t.data,statusCode:(d=t.init)==null?void 0:d.status,headers:(u=t.init)!=null&&u.headers?new Headers(t.init.headers):void 0}}return{type:z.data,data:t}}function Hn(e,t,r,n,a,l){let o=e.headers.get("Location");if(U(o,"Redirects returned/thrown from loaders/actions must have a Location header"),!Ot.test(o)){let d=n.slice(0,n.findIndex(u=>u.route.id===r)+1);o=Lt(new URL(t.url),d,a,!0,o,l),e.headers.set("Location",o)}return e}function nr(e,t,r){if(Ot.test(e)){let n=e,a=n.startsWith("//")?new URL(t.protocol+n):new URL(n),l=Ae(a.pathname,r)!=null;if(a.origin===t.origin&&l)return a.pathname+a.search+a.hash}return e}function Be(e,t,r,n){let a=e.createURL(xr(t)).toString(),l={signal:r};if(n&&le(n.formMethod)){let{formMethod:o,formEncType:d}=n;l.method=o.toUpperCase(),d==="application/json"?(l.headers=new Headers({"Content-Type":d}),l.body=JSON.stringify(n.json)):d==="text/plain"?l.body=n.text:d==="application/x-www-form-urlencoded"&&n.formData?l.body=Mt(n.formData):l.body=n.formData}return new Request(a,l)}function Mt(e){let t=new URLSearchParams;for(let[r,n]of e.entries())t.append(r,typeof n=="string"?n:n.name);return t}function ar(e){let t=new FormData;for(let[r,n]of e.entries())t.append(r,n);return t}function $n(e,t,r,n,a){let l={},o=null,d,u=!1,f={},h=r&&ie(r[1])?r[1].error:void 0;return e.forEach(p=>{if(!(p.route.id in t))return;let y=p.route.id,b=t[y];if(U(!De(b),"Cannot handle redirect results in processLoaderData"),ie(b)){let S=b.error;h!==void 0&&(S=h,h=void 0),o=o||{};{let x=Pe(e,y);o[x.route.id]==null&&(o[x.route.id]=S)}l[y]=void 0,u||(u=!0,d=vt(b.error)?b.error.status:500),b.headers&&(f[y]=b.headers)}else ve(b)?(n.set(y,b.deferredData),l[y]=b.deferredData.data,b.statusCode!=null&&b.statusCode!==200&&!u&&(d=b.statusCode),b.headers&&(f[y]=b.headers)):(l[y]=b.data,b.statusCode&&b.statusCode!==200&&!u&&(d=b.statusCode),b.headers&&(f[y]=b.headers))}),h!==void 0&&r&&(o={[r[0]]:h},l[r[0]]=void 0),{loaderData:l,errors:o,statusCode:d||200,loaderHeaders:f}}function ir(e,t,r,n,a,l,o){let{loaderData:d,errors:u}=$n(t,r,n,o);return a.forEach(f=>{let{key:h,match:p,controller:y}=f,b=l[h];if(U(b,"Did not find corresponding fetcher result"),!(y&&y.signal.aborted))if(ie(b)){let S=Pe(e.matches,p==null?void 0:p.route.id);u&&u[S.route.id]||(u=V({},u,{[S.route.id]:b.error})),e.fetchers.delete(h)}else if(De(b))U(!1,"Unhandled fetcher revalidation redirect");else if(ve(b))U(!1,"Unhandled fetcher deferred data");else{let S=ge(b.data);e.fetchers.set(h,S)}}),{loaderData:d,errors:u}}function or(e,t,r,n){let a=V({},t);for(let l of r){let o=l.route.id;if(t.hasOwnProperty(o)?t[o]!==void 0&&(a[o]=t[o]):e[o]!==void 0&&l.route.loader&&(a[o]=e[o]),n&&n.hasOwnProperty(o))break}return a}function lr(e){return e?ie(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Pe(e,t){return(t?e.slice(0,e.findIndex(n=>n.route.id===t)+1):[...e]).reverse().find(n=>n.route.hasErrorBoundary===!0)||e[0]}function sr(e){let t=e.length===1?e[0]:e.find(r=>r.index||!r.path||r.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function ae(e,t){let{pathname:r,routeId:n,method:a,type:l,message:o}=t===void 0?{}:t,d="Unknown Server Error",u="Unknown @remix-run/router error";return e===400?(d="Bad Request",a&&r&&n?u="You made a "+a+' request to "'+r+'" but '+('did not provide a `loader` for route "'+n+'", ')+"so there is no way to handle the request.":l==="defer-action"?u="defer() is not supported in actions":l==="invalid-body"&&(u="Unable to encode submission body")):e===403?(d="Forbidden",u='Route "'+n+'" does not match URL "'+r+'"'):e===404?(d="Not Found",u='No route matches URL "'+r+'"'):e===405&&(d="Method Not Allowed",a&&r&&n?u="You made a "+a.toUpperCase()+' request to "'+r+'" but '+('did not provide an `action` for route "'+n+'", ')+"so there is no way to handle the request.":a&&(u='Invalid request method "'+a.toUpperCase()+'"')),new mt(e||500,d,new Error(u),!0)}function ft(e){let t=Object.entries(e);for(let r=t.length-1;r>=0;r--){let[n,a]=t[r];if(De(a))return{key:n,result:a}}}function xr(e){let t=typeof e=="string"?he(e):e;return Le(V({},t,{hash:""}))}function Vn(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function Wn(e){return Pr(e.result)&&Tn.has(e.result.status)}function ve(e){return e.type===z.deferred}function ie(e){return e.type===z.error}function De(e){return(e&&e.type)===z.redirect}function ur(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function Kn(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function Pr(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function Jn(e){return Mn.has(e.toLowerCase())}function le(e){return Ln.has(e.toLowerCase())}async function Yn(e,t,r,n,a){let l=Object.entries(t);for(let o=0;o<l.length;o++){let[d,u]=l[o],f=e.find(y=>(y==null?void 0:y.route.id)===d);if(!f)continue;let h=n.find(y=>y.route.id===f.route.id),p=h!=null&&!Er(h,f)&&(a&&a[f.route.id])!==void 0;ve(u)&&p&&await jt(u,r,!1).then(y=>{y&&(t[d]=y)})}}async function Gn(e,t,r){for(let n=0;n<r.length;n++){let{key:a,routeId:l,controller:o}=r[n],d=t[a];e.find(f=>(f==null?void 0:f.route.id)===l)&&ve(d)&&(U(o,"Expected an AbortController for revalidating fetcher deferred result"),await jt(d,o.signal,!0).then(f=>{f&&(t[a]=f)}))}}async function jt(e,t,r){if(r===void 0&&(r=!1),!await e.deferredData.resolveData(t)){if(r)try{return{type:z.data,data:e.deferredData.unwrappedData}}catch(a){return{type:z.error,error:a}}return{type:z.data,data:e.deferredData.data}}}function Bt(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Xe(e,t){let r=typeof t=="string"?he(t).search:t.search;if(e[e.length-1].route.index&&Bt(r||""))return e[e.length-1];let n=br(e);return n[n.length-1]}function dr(e){let{formMethod:t,formAction:r,formEncType:n,text:a,formData:l,json:o}=e;if(!(!t||!r||!n)){if(a!=null)return{formMethod:t,formAction:r,formEncType:n,formData:void 0,json:void 0,text:a};if(l!=null)return{formMethod:t,formAction:r,formEncType:n,formData:l,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:r,formEncType:n,formData:void 0,json:o,text:void 0}}}function Dt(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Xn(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Ye(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Qn(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function ge(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function Zn(e,t){try{let r=e.sessionStorage.getItem(Rr);if(r){let n=JSON.parse(r);for(let[a,l]of Object.entries(n||{}))l&&Array.isArray(l)&&t.set(a,new Set(l||[]))}}catch{}}function qn(e,t){if(t.size>0){let r={};for(let[n,a]of t)r[n]=[...a];try{e.sessionStorage.setItem(Rr,JSON.stringify(r))}catch(n){Ne(!1,"Failed to save applied view transitions in sessionStorage ("+n+").")}}}/** + * React Router v6.28.2 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function et(){return et=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},et.apply(this,arguments)}const yt=v.createContext(null),Dr=v.createContext(null),Ce=v.createContext(null),bt=v.createContext(null),ye=v.createContext({outlet:null,matches:[],isDataRoute:!1}),Lr=v.createContext(null);function ea(e,t){let{relative:r}=t===void 0?{}:t;rt()||U(!1);let{basename:n,navigator:a}=v.useContext(Ce),{hash:l,pathname:o,search:d}=Tr(e,{relative:r}),u=o;return n!=="/"&&(u=o==="/"?n:fe([n,o])),a.createHref({pathname:u,search:d,hash:l})}function rt(){return v.useContext(bt)!=null}function ze(){return rt()||U(!1),v.useContext(bt).location}function Cr(e){v.useContext(Ce).static||v.useLayoutEffect(e)}function Mr(){let{isDataRoute:e}=v.useContext(ye);return e?fa():ta()}function ta(){rt()||U(!1);let e=v.useContext(yt),{basename:t,future:r,navigator:n}=v.useContext(Ce),{matches:a}=v.useContext(ye),{pathname:l}=ze(),o=JSON.stringify(Ft(a,r.v7_relativeSplatPath)),d=v.useRef(!1);return Cr(()=>{d.current=!0}),v.useCallback(function(f,h){if(h===void 0&&(h={}),!d.current)return;if(typeof f=="number"){n.go(f);return}let p=_t(f,JSON.parse(o),l,h.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:fe([t,p.pathname])),(h.replace?n.replace:n.push)(p,h.state,h)},[t,n,o,l,e])}function Qa(){let{matches:e}=v.useContext(ye),t=e[e.length-1];return t?t.params:{}}function Tr(e,t){let{relative:r}=t===void 0?{}:t,{future:n}=v.useContext(Ce),{matches:a}=v.useContext(ye),{pathname:l}=ze(),o=JSON.stringify(Ft(a,n.v7_relativeSplatPath));return v.useMemo(()=>_t(e,JSON.parse(o),l,r==="path"),[e,o,l,r])}function ra(e,t){return Ur(e,t)}function Ur(e,t,r,n){rt()||U(!1);let{navigator:a}=v.useContext(Ce),{matches:l}=v.useContext(ye),o=l[l.length-1],d=o?o.params:{};o&&o.pathname;let u=o?o.pathnameBase:"/";o&&o.route;let f=ze(),h;if(t){var p;let R=typeof t=="string"?he(t):t;u==="/"||(p=R.pathname)!=null&&p.startsWith(u)||U(!1),h=R}else h=f;let y=h.pathname||"/",b=y;if(u!=="/"){let R=u.replace(/^\//,"").split("/");b="/"+y.replace(/^\//,"").split("/").slice(R.length).join("/")}let S=xe(e,{pathname:b}),x=la(S&&S.map(R=>Object.assign({},R,{params:Object.assign({},d,R.params),pathname:fe([u,a.encodeLocation?a.encodeLocation(R.pathname).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?u:fe([u,a.encodeLocation?a.encodeLocation(R.pathnameBase).pathname:R.pathnameBase])})),l,r,n);return t&&x?v.createElement(bt.Provider,{value:{location:et({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:J.Pop}},x):x}function na(){let e=ca(),t=vt(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),r?v.createElement("pre",{style:a},r):null,null)}const aa=v.createElement(na,null);class ia extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?v.createElement(ye.Provider,{value:this.props.routeContext},v.createElement(Lr.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function oa(e){let{routeContext:t,match:r,children:n}=e,a=v.useContext(yt);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),v.createElement(ye.Provider,{value:t},n)}function la(e,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),e==null){var l;if(!r)return null;if(r.errors)e=r.matches;else if((l=n)!=null&&l.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let o=e,d=(a=r)==null?void 0:a.errors;if(d!=null){let h=o.findIndex(p=>p.route.id&&(d==null?void 0:d[p.route.id])!==void 0);h>=0||U(!1),o=o.slice(0,Math.min(o.length,h+1))}let u=!1,f=-1;if(r&&n&&n.v7_partialHydration)for(let h=0;h<o.length;h++){let p=o[h];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(f=h),p.route.id){let{loaderData:y,errors:b}=r,S=p.route.loader&&y[p.route.id]===void 0&&(!b||b[p.route.id]===void 0);if(p.route.lazy||S){u=!0,f>=0?o=o.slice(0,f+1):o=[o[0]];break}}}return o.reduceRight((h,p,y)=>{let b,S=!1,x=null,R=null;r&&(b=d&&p.route.id?d[p.route.id]:void 0,x=p.route.errorElement||aa,u&&(f<0&&y===0?(S=!0,R=null):f===y&&(S=!0,R=p.route.hydrateFallbackElement||null)));let j=t.concat(o.slice(0,y+1)),M=()=>{let I;return b?I=x:S?I=R:p.route.Component?I=v.createElement(p.route.Component,null):p.route.element?I=p.route.element:I=h,v.createElement(oa,{match:p,routeContext:{outlet:h,matches:j,isDataRoute:r!=null},children:I})};return r&&(p.route.ErrorBoundary||p.route.errorElement||y===0)?v.createElement(ia,{location:r.location,revalidation:r.revalidation,component:x,error:b,children:M(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):M()},null)}var Fr=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Fr||{}),gt=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(gt||{});function sa(e){let t=v.useContext(yt);return t||U(!1),t}function ua(e){let t=v.useContext(Dr);return t||U(!1),t}function da(e){let t=v.useContext(ye);return t||U(!1),t}function _r(e){let t=da(),r=t.matches[t.matches.length-1];return r.route.id||U(!1),r.route.id}function ca(){var e;let t=v.useContext(Lr),r=ua(gt.UseRouteError),n=_r(gt.UseRouteError);return t!==void 0?t:(e=r.errors)==null?void 0:e[n]}function fa(){let{router:e}=sa(Fr.UseNavigateStable),t=_r(gt.UseNavigateStable),r=v.useRef(!1);return Cr(()=>{r.current=!0}),v.useCallback(function(a,l){l===void 0&&(l={}),r.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,et({fromRouteId:t},l)))},[e,t])}const cr={};function ha(e,t){cr[t]||(cr[t]=!0,console.warn(t))}const Ie=(e,t,r)=>ha(e,"⚠️ React Router Future Flag Warning: "+t+". "+("You can use the `"+e+"` future flag to opt-in early. ")+("For more information, see "+r+"."));function pa(e,t){(e==null?void 0:e.v7_startTransition)===void 0&&Ie("v7_startTransition","React Router will begin wrapping state updates in `React.startTransition` in v7","https://reactrouter.com/v6/upgrading/future#v7_starttransition"),(e==null?void 0:e.v7_relativeSplatPath)===void 0&&(!t||!t.v7_relativeSplatPath)&&Ie("v7_relativeSplatPath","Relative route resolution within Splat routes is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath"),t&&(t.v7_fetcherPersist===void 0&&Ie("v7_fetcherPersist","The persistence behavior of fetchers is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist"),t.v7_normalizeFormMethod===void 0&&Ie("v7_normalizeFormMethod","Casing of `formMethod` fields is being normalized to uppercase in v7","https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod"),t.v7_partialHydration===void 0&&Ie("v7_partialHydration","`RouterProvider` hydration behavior is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_partialhydration"),t.v7_skipActionErrorRevalidation===void 0&&Ie("v7_skipActionErrorRevalidation","The revalidation behavior after 4xx/5xx `action` responses is changing in v7","https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation"))}function ma(e){U(!1)}function ga(e){let{basename:t="/",children:r=null,location:n,navigationType:a=J.Pop,navigator:l,static:o=!1,future:d}=e;rt()&&U(!1);let u=t.replace(/^\/*/,"/"),f=v.useMemo(()=>({basename:u,navigator:l,static:o,future:et({v7_relativeSplatPath:!1},d)}),[u,d,l,o]);typeof n=="string"&&(n=he(n));let{pathname:h="/",search:p="",hash:y="",state:b=null,key:S="default"}=n,x=v.useMemo(()=>{let R=Ae(h,u);return R==null?null:{location:{pathname:R,search:p,hash:y,state:b,key:S},navigationType:a}},[u,h,p,y,b,S,a]);return x==null?null:v.createElement(Ce.Provider,{value:f},v.createElement(bt.Provider,{children:r,value:x}))}function Za(e){let{children:t,location:r}=e;return ra(Tt(t),r)}new Promise(()=>{});function Tt(e,t){t===void 0&&(t=[]);let r=[];return v.Children.forEach(e,(n,a)=>{if(!v.isValidElement(n))return;let l=[...t,a];if(n.type===v.Fragment){r.push.apply(r,Tt(n.props.children,l));return}n.type!==ma&&U(!1),!n.props.index||!n.props.children||U(!1);let o={id:n.props.id||l.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(o.children=Tt(n.props.children,l)),r.push(o)}),r}function va(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:v.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:v.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:v.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** + * React Router DOM v6.28.2 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function tt(){return tt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},tt.apply(this,arguments)}function ya(e,t){if(e==null)return{};var r={},n=Object.keys(e),a,l;for(l=0;l<n.length;l++)a=n[l],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}function ba(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function wa(e,t){return e.button===0&&(!t||t==="_self")&&!ba(e)}function Ut(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,r)=>{let n=e[r];return t.concat(Array.isArray(n)?n.map(a=>[r,a]):[[r,n]])},[]))}function Ra(e,t){let r=Ut(e);return t&&t.forEach((n,a)=>{r.has(a)||t.getAll(a).forEach(l=>{r.append(a,l)})}),r}const Ea=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Sa="6";try{window.__reactRouterVersion=Sa}catch{}function qa(e,t){return On({basename:t==null?void 0:t.basename,future:tt({},t==null?void 0:t.future,{v7_prependBasename:!0}),history:nn({window:t==null?void 0:t.window}),hydrationData:(t==null?void 0:t.hydrationData)||xa(),routes:e,mapRouteProperties:va,dataStrategy:t==null?void 0:t.dataStrategy,patchRoutesOnNavigation:t==null?void 0:t.patchRoutesOnNavigation,window:t==null?void 0:t.window}).initialize()}function xa(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=tt({},t,{errors:Pa(t.errors)})),t}function Pa(e){if(!e)return null;let t=Object.entries(e),r={};for(let[n,a]of t)if(a&&a.__type==="RouteErrorResponse")r[n]=new mt(a.status,a.statusText,a.data,a.internal===!0);else if(a&&a.__type==="Error"){if(a.__subType){let l=window[a.__subType];if(typeof l=="function")try{let o=new l(a.message);o.stack="",r[n]=o}catch{}}if(r[n]==null){let l=new Error(a.message);l.stack="",r[n]=l}}else r[n]=a;return r}const Da=v.createContext({isTransitioning:!1}),La=v.createContext(new Map),Ca="startTransition",fr=en[Ca],Ma="flushSync",hr=tn[Ma];function Ta(e){fr?fr(e):e()}function Ge(e){hr?hr(e):e()}class Ua{constructor(){this.status="pending",this.promise=new Promise((t,r)=>{this.resolve=n=>{this.status==="pending"&&(this.status="resolved",t(n))},this.reject=n=>{this.status==="pending"&&(this.status="rejected",r(n))}})}}function ei(e){let{fallbackElement:t,router:r,future:n}=e,[a,l]=v.useState(r.state),[o,d]=v.useState(),[u,f]=v.useState({isTransitioning:!1}),[h,p]=v.useState(),[y,b]=v.useState(),[S,x]=v.useState(),R=v.useRef(new Map),{v7_startTransition:j}=n||{},M=v.useCallback(F=>{j?Ta(F):F()},[j]),I=v.useCallback((F,O)=>{let{deletedFetchers:$,flushSync:te,viewTransitionOpts:Q}=O;F.fetchers.forEach((Z,Me)=>{Z.data!==void 0&&R.current.set(Me,Z.data)}),$.forEach(Z=>R.current.delete(Z));let ne=r.window==null||r.window.document==null||typeof r.window.document.startViewTransition!="function";if(!Q||ne){te?Ge(()=>l(F)):M(()=>l(F));return}if(te){Ge(()=>{y&&(h&&h.resolve(),y.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:Q.currentLocation,nextLocation:Q.nextLocation})});let Z=r.window.document.startViewTransition(()=>{Ge(()=>l(F))});Z.finished.finally(()=>{Ge(()=>{p(void 0),b(void 0),d(void 0),f({isTransitioning:!1})})}),Ge(()=>b(Z));return}y?(h&&h.resolve(),y.skipTransition(),x({state:F,currentLocation:Q.currentLocation,nextLocation:Q.nextLocation})):(d(F),f({isTransitioning:!0,flushSync:!1,currentLocation:Q.currentLocation,nextLocation:Q.nextLocation}))},[r.window,y,h,R,M]);v.useLayoutEffect(()=>r.subscribe(I),[r,I]),v.useEffect(()=>{u.isTransitioning&&!u.flushSync&&p(new Ua)},[u]),v.useEffect(()=>{if(h&&o&&r.window){let F=o,O=h.promise,$=r.window.document.startViewTransition(async()=>{M(()=>l(F)),await O});$.finished.finally(()=>{p(void 0),b(void 0),d(void 0),f({isTransitioning:!1})}),b($)}},[M,o,h,r.window]),v.useEffect(()=>{h&&o&&a.location.key===o.location.key&&h.resolve()},[h,y,a.location,o]),v.useEffect(()=>{!u.isTransitioning&&S&&(d(S.state),f({isTransitioning:!0,flushSync:!1,currentLocation:S.currentLocation,nextLocation:S.nextLocation}),x(void 0))},[u.isTransitioning,S]),v.useEffect(()=>{},[]);let k=v.useMemo(()=>({createHref:r.createHref,encodeLocation:r.encodeLocation,go:F=>r.navigate(F),push:(F,O,$)=>r.navigate(F,{state:O,preventScrollReset:$==null?void 0:$.preventScrollReset}),replace:(F,O,$)=>r.navigate(F,{replace:!0,state:O,preventScrollReset:$==null?void 0:$.preventScrollReset})}),[r]),X=r.basename||"/",m=v.useMemo(()=>({router:r,navigator:k,static:!1,basename:X}),[r,k,X]),ee=v.useMemo(()=>({v7_relativeSplatPath:r.future.v7_relativeSplatPath}),[r.future.v7_relativeSplatPath]);return v.useEffect(()=>pa(n,r.future),[n,r.future]),v.createElement(v.Fragment,null,v.createElement(yt.Provider,{value:m},v.createElement(Dr.Provider,{value:a},v.createElement(La.Provider,{value:R.current},v.createElement(Da.Provider,{value:u},v.createElement(ga,{basename:X,location:a.location,navigationType:a.historyAction,navigator:k,future:ee},a.initialized||r.future.v7_partialHydration?v.createElement(Fa,{routes:r.routes,future:r.future,state:a}):t))))),null)}const Fa=v.memo(_a);function _a(e){let{routes:t,future:r,state:n}=e;return Ur(t,void 0,n,r)}const Oa=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ja=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ti=v.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:l,replace:o,state:d,target:u,to:f,preventScrollReset:h,viewTransition:p}=t,y=ya(t,Ea),{basename:b}=v.useContext(Ce),S,x=!1;if(typeof f=="string"&&ja.test(f)&&(S=f,Oa))try{let I=new URL(window.location.href),k=f.startsWith("//")?new URL(I.protocol+f):new URL(f),X=Ae(k.pathname,b);k.origin===I.origin&&X!=null?f=X+k.search+k.hash:x=!0}catch{}let R=ea(f,{relative:a}),j=Ba(f,{replace:o,state:d,target:u,preventScrollReset:h,relative:a,viewTransition:p});function M(I){n&&n(I),I.defaultPrevented||j(I)}return v.createElement("a",tt({},y,{href:S||R,onClick:x||l?n:M,ref:r,target:u}))});var pr;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(pr||(pr={}));var mr;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(mr||(mr={}));function Ba(e,t){let{target:r,replace:n,state:a,preventScrollReset:l,relative:o,viewTransition:d}=t===void 0?{}:t,u=Mr(),f=ze(),h=Tr(e,{relative:o});return v.useCallback(p=>{if(wa(p,r)){p.preventDefault();let y=n!==void 0?n:Le(f)===Le(h);u(e,{replace:y,state:a,preventScrollReset:l,relative:o,viewTransition:d})}},[f,u,h,n,a,r,e,l,o,d])}function ri(e){let t=v.useRef(Ut(e)),r=v.useRef(!1),n=ze(),a=v.useMemo(()=>Ra(n.search,r.current?null:t.current),[n.search]),l=Mr(),o=v.useCallback((d,u)=>{const f=Ut(typeof d=="function"?d(a):d);r.current=!0,l("?"+f,u)},[l,a]);return[a,o]}var Ia=function(t){return t.join("/").replace(/\/\/+/g,"/")},Na=/^:\w+$/,Aa=3,za=2,ka=1,Ha=10,$a=-2,gr=function(t){return t==="*"};function Va(e,t){var r=e.split("/"),n=r.length;return r.some(gr)&&(n+=$a),t&&(n+=za),r.filter(function(a){return!gr(a)}).reduce(function(a,l){return Na.test(l)?a+Aa:l===""?a+ka:a+Ha},n)}function Wa(e,t){var r=e.length===t.length&&e.slice(0,-1).every(function(n,a){return n===t[a]});return r?e[e.length-1]-t[t.length-1]:0}function Or(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"";return e.forEach(function(a,l){var o;if(typeof a.path!="string"&&!a.index&&!(!((o=a.children)===null||o===void 0)&&o.length))throw new Error("useBreadcrumbs: `path` or `index` must be provided in every route object");if(a.path&&a.index)throw new Error("useBreadcrumbs: `path` and `index` cannot be provided at the same time");var d={relativePath:a.path||"",childrenIndex:l,route:a};if(d.relativePath.charAt(0)==="/"){if(!d.relativePath.startsWith(n))throw new Error("useBreadcrumbs: The absolute path of the child route must start with the parent path");d.relativePath=d.relativePath.slice(n.length)}var u=Ia([n,d.relativePath]),f=r.concat(d);if(a.children&&a.children.length>0){if(a.index)throw new Error("useBreadcrumbs: Index route cannot have child routes");Or(a.children,t,f,u)}t.push({path:u,score:Va(u,a.index),routesMeta:f})}),t}function Ka(e){return e.sort(function(t,r){return t.score!==r.score?r.score-t.score:Wa(t.routesMeta.map(function(n){return n.childrenIndex}),r.routesMeta.map(function(n){return n.childrenIndex}))})}var Qe=Symbol("NO_BREADCRUMB"),jr=function(t){return t.replace(/^[\s_]+|[\s_]+$/g,"").replace(/[-_\s]+/g," ").replace(/^[a-z]/,function(r){return r.toUpperCase()})},Br=function(t){var r=t.breadcrumb,n=t.match,a=t.location,l=t.props,o=Object.assign({match:n,location:a,key:n.pathname},l||{});return Object.assign(Object.assign({},o),{breadcrumb:typeof r=="string"?v.createElement("span",{key:o.key},r):rn.createElement(r,Object.assign({},o))})},Ja=function(t){var r=t.currentSection,n=t.location,a=t.pathSection,l=t.defaultFormatter,o=qe({end:!0,path:a},a);return Br({breadcrumb:l?l(r):jr(r),match:o,location:n})},Ya=function(t){var r=t.currentSection,n=t.disableDefaults,a=t.excludePaths,l=t.defaultFormatter,o=t.location,d=t.pathSection,u=t.branches,f,h=function(y){return qe({path:y,end:!0},d)!=null};return a&&a.some(h)?Qe:(u.some(function(p){var y=p.path,b=p.routesMeta,S=b[b.length-1].route,x=S.breadcrumb;if(!x&&S.index){var R=b[b.length-2];R&&R.route.breadcrumb&&(x=R.route.breadcrumb)}var j=S.caseSensitive,M=S.props,I=qe({path:y,end:!0,caseSensitive:j},d);return I&&x===null?(f=Qe,!0):I?!x&&n?(f=Qe,!0):(f=Br({breadcrumb:x||(l?l(r):jr(r)),match:Object.assign(Object.assign({},I),{route:S}),location:o,props:M}),!0):!1}),f||(n?Qe:Ja({pathSection:d,currentSection:d==="/"?"Home":r,location:o,defaultFormatter:l})))},Ga=function(t){var r=t.routes,n=t.location,a=t.options,l=a===void 0?{}:a,o=n.pathname,d=Ka(Or(r)),u=[];return o.split("?")[0].split("/").reduce(function(f,h,p){var y=h?"".concat(f,"/").concat(h):"/";if(y==="/"&&p!==0)return"";var b=Ya(Object.assign({currentSection:h,location:n,pathSection:y,branches:d},l));return b!==Qe&&u.push(b),y==="/"?"":y},""),u},ni=function(t,r){return Ga({routes:t,location:ze(),options:r})};export{ti as L,Za as R,ri as a,Qa as b,ni as c,ze as d,ma as e,qa as f,ei as g,Mr as u}; diff --git a/pkg/ui/frontend/dist/assets/style-De_mcyPH.css b/pkg/ui/frontend/dist/assets/style-De_mcyPH.css new file mode 100644 index 0000000000000..c4b94cacd37cf --- /dev/null +++ b/pkg/ui/frontend/dist/assets/style-De_mcyPH.css @@ -0,0 +1 @@ +@charset "UTF-8";.react-datepicker__navigation-icon:before,.react-datepicker__year-read-view--down-arrow,.react-datepicker__month-read-view--down-arrow,.react-datepicker__month-year-read-view--down-arrow{border-color:#ccc;border-style:solid;border-width:3px 3px 0 0;content:"";display:block;height:9px;position:absolute;top:6px;width:9px}.react-datepicker-wrapper{display:inline-block;padding:0;border:0}.react-datepicker{font-family:Helvetica Neue,helvetica,arial,sans-serif;font-size:.8rem;background-color:#fff;color:#000;border:1px solid #aeaeae;border-radius:.3rem;display:inline-block;position:relative;line-height:initial}.react-datepicker--time-only .react-datepicker__time-container{border-left:0}.react-datepicker--time-only .react-datepicker__time,.react-datepicker--time-only .react-datepicker__time-box{border-bottom-left-radius:.3rem;border-bottom-right-radius:.3rem}.react-datepicker-popper{z-index:1;line-height:0}.react-datepicker-popper .react-datepicker__triangle{stroke:#aeaeae}.react-datepicker-popper[data-placement^=bottom] .react-datepicker__triangle{fill:#f0f0f0;color:#f0f0f0}.react-datepicker-popper[data-placement^=top] .react-datepicker__triangle{fill:#fff;color:#fff}.react-datepicker__header{text-align:center;background-color:#f0f0f0;border-bottom:1px solid #aeaeae;border-top-left-radius:.3rem;padding:8px 0;position:relative}.react-datepicker__header--time{padding-bottom:8px;padding-left:5px;padding-right:5px}.react-datepicker__header--time:not(.react-datepicker__header--time--only){border-top-left-radius:0}.react-datepicker__header:not(.react-datepicker__header--has-time-select){border-top-right-radius:.3rem}.react-datepicker__year-dropdown-container--select,.react-datepicker__month-dropdown-container--select,.react-datepicker__month-year-dropdown-container--select,.react-datepicker__year-dropdown-container--scroll,.react-datepicker__month-dropdown-container--scroll,.react-datepicker__month-year-dropdown-container--scroll{display:inline-block;margin:0 15px}.react-datepicker__current-month,.react-datepicker-time__header,.react-datepicker-year-header{margin-top:0;color:#000;font-weight:700;font-size:.944rem}h2.react-datepicker__current-month{padding:0;margin:0}.react-datepicker-time__header{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.react-datepicker__navigation{align-items:center;background:none;display:flex;justify-content:center;text-align:center;cursor:pointer;position:absolute;top:2px;padding:0;border:none;z-index:1;height:32px;width:32px;text-indent:-999em;overflow:hidden}.react-datepicker__navigation--previous{left:2px}.react-datepicker__navigation--next{right:2px}.react-datepicker__navigation--next--with-time:not(.react-datepicker__navigation--next--with-today-button){right:85px}.react-datepicker__navigation--years{position:relative;top:0;display:block;margin-left:auto;margin-right:auto}.react-datepicker__navigation--years-previous{top:4px}.react-datepicker__navigation--years-upcoming{top:-4px}.react-datepicker__navigation:hover *:before{border-color:#a6a6a6}.react-datepicker__navigation-icon{position:relative;top:-1px;font-size:20px;width:0}.react-datepicker__navigation-icon--next{left:-2px}.react-datepicker__navigation-icon--next:before{transform:rotate(45deg);left:-7px}.react-datepicker__navigation-icon--previous{right:-2px}.react-datepicker__navigation-icon--previous:before{transform:rotate(225deg);right:-7px}.react-datepicker__month-container{float:left}.react-datepicker__year{margin:.4rem;text-align:center}.react-datepicker__year-wrapper{display:flex;flex-wrap:wrap;max-width:180px}.react-datepicker__year .react-datepicker__year-text{display:inline-block;width:4rem;margin:2px}.react-datepicker__month{margin:.4rem;text-align:center}.react-datepicker__month .react-datepicker__month-text,.react-datepicker__month .react-datepicker__quarter-text{display:inline-block;width:4rem;margin:2px}.react-datepicker__input-time-container{clear:both;width:100%;float:left;margin:5px 0 10px 15px;text-align:left}.react-datepicker__input-time-container .react-datepicker-time__caption,.react-datepicker__input-time-container .react-datepicker-time__input-container{display:inline-block}.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__input{display:inline-block;margin-left:10px}.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__input input{width:auto}.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__input input[type=time]::-webkit-inner-spin-button,.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__input input[type=time]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__input input[type=time]{-moz-appearance:textfield}.react-datepicker__input-time-container .react-datepicker-time__input-container .react-datepicker-time__delimiter{margin-left:5px;display:inline-block}.react-datepicker__time-container{float:right;border-left:1px solid #aeaeae;width:85px}.react-datepicker__time-container--with-today-button{display:inline;border:1px solid #aeaeae;border-radius:.3rem;position:absolute;right:-87px;top:0}.react-datepicker__time-container .react-datepicker__time{position:relative;background:#fff;border-bottom-right-radius:.3rem}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box{width:85px;overflow-x:hidden;margin:0 auto;text-align:center;border-bottom-right-radius:.3rem}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list{list-style:none;margin:0;height:calc(195px + .85rem);overflow-y:scroll;padding-right:0;padding-left:0;width:100%;box-sizing:content-box}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item{height:30px;padding:5px 10px;white-space:nowrap}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item:hover{cursor:pointer;background-color:#f0f0f0}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item--selected{background-color:#216ba5;color:#fff;font-weight:700}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item--selected:hover{background-color:#216ba5}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item--disabled{color:#ccc}.react-datepicker__time-container .react-datepicker__time .react-datepicker__time-box ul.react-datepicker__time-list li.react-datepicker__time-list-item--disabled:hover{cursor:default;background-color:transparent}.react-datepicker__week-number{color:#ccc;display:inline-block;width:1.7rem;line-height:1.7rem;text-align:center;margin:.166rem}.react-datepicker__week-number.react-datepicker__week-number--clickable{cursor:pointer}.react-datepicker__week-number.react-datepicker__week-number--clickable:not(.react-datepicker__week-number--selected):hover{border-radius:.3rem;background-color:#f0f0f0}.react-datepicker__week-number--selected{border-radius:.3rem;background-color:#216ba5;color:#fff}.react-datepicker__week-number--selected:hover{background-color:#1d5d90}.react-datepicker__day-names{white-space:nowrap;margin-bottom:-8px}.react-datepicker__week{white-space:nowrap}.react-datepicker__day-name,.react-datepicker__day,.react-datepicker__time-name{color:#000;display:inline-block;width:1.7rem;line-height:1.7rem;text-align:center;margin:.166rem}.react-datepicker__day,.react-datepicker__month-text,.react-datepicker__quarter-text,.react-datepicker__year-text{cursor:pointer}.react-datepicker__day:not([aria-disabled=true]):hover,.react-datepicker__month-text:not([aria-disabled=true]):hover,.react-datepicker__quarter-text:not([aria-disabled=true]):hover,.react-datepicker__year-text:not([aria-disabled=true]):hover{border-radius:.3rem;background-color:#f0f0f0}.react-datepicker__day--today,.react-datepicker__month-text--today,.react-datepicker__quarter-text--today,.react-datepicker__year-text--today{font-weight:700}.react-datepicker__day--highlighted,.react-datepicker__month-text--highlighted,.react-datepicker__quarter-text--highlighted,.react-datepicker__year-text--highlighted{border-radius:.3rem;background-color:#3dcc4a;color:#fff}.react-datepicker__day--highlighted:not([aria-disabled=true]):hover,.react-datepicker__month-text--highlighted:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--highlighted:not([aria-disabled=true]):hover,.react-datepicker__year-text--highlighted:not([aria-disabled=true]):hover{background-color:#32be3f}.react-datepicker__day--highlighted-custom-1,.react-datepicker__month-text--highlighted-custom-1,.react-datepicker__quarter-text--highlighted-custom-1,.react-datepicker__year-text--highlighted-custom-1{color:#f0f}.react-datepicker__day--highlighted-custom-2,.react-datepicker__month-text--highlighted-custom-2,.react-datepicker__quarter-text--highlighted-custom-2,.react-datepicker__year-text--highlighted-custom-2{color:green}.react-datepicker__day--holidays,.react-datepicker__month-text--holidays,.react-datepicker__quarter-text--holidays,.react-datepicker__year-text--holidays{position:relative;border-radius:.3rem;background-color:#ff6803;color:#fff}.react-datepicker__day--holidays .overlay,.react-datepicker__month-text--holidays .overlay,.react-datepicker__quarter-text--holidays .overlay,.react-datepicker__year-text--holidays .overlay{position:absolute;bottom:100%;left:50%;transform:translate(-50%);background-color:#333;color:#fff;padding:4px;border-radius:4px;white-space:nowrap;visibility:hidden;opacity:0;transition:visibility 0s,opacity .3s ease-in-out}.react-datepicker__day--holidays:not([aria-disabled=true]):hover,.react-datepicker__month-text--holidays:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--holidays:not([aria-disabled=true]):hover,.react-datepicker__year-text--holidays:not([aria-disabled=true]):hover{background-color:#cf5300}.react-datepicker__day--holidays:hover .overlay,.react-datepicker__month-text--holidays:hover .overlay,.react-datepicker__quarter-text--holidays:hover .overlay,.react-datepicker__year-text--holidays:hover .overlay{visibility:visible;opacity:1}.react-datepicker__day--selected,.react-datepicker__day--in-selecting-range,.react-datepicker__day--in-range,.react-datepicker__month-text--selected,.react-datepicker__month-text--in-selecting-range,.react-datepicker__month-text--in-range,.react-datepicker__quarter-text--selected,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__quarter-text--in-range,.react-datepicker__year-text--selected,.react-datepicker__year-text--in-selecting-range,.react-datepicker__year-text--in-range{border-radius:.3rem;background-color:#216ba5;color:#fff}.react-datepicker__day--selected:not([aria-disabled=true]):hover,.react-datepicker__day--in-selecting-range:not([aria-disabled=true]):hover,.react-datepicker__day--in-range:not([aria-disabled=true]):hover,.react-datepicker__month-text--selected:not([aria-disabled=true]):hover,.react-datepicker__month-text--in-selecting-range:not([aria-disabled=true]):hover,.react-datepicker__month-text--in-range:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--selected:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--in-selecting-range:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--in-range:not([aria-disabled=true]):hover,.react-datepicker__year-text--selected:not([aria-disabled=true]):hover,.react-datepicker__year-text--in-selecting-range:not([aria-disabled=true]):hover,.react-datepicker__year-text--in-range:not([aria-disabled=true]):hover{background-color:#1d5d90}.react-datepicker__day--keyboard-selected,.react-datepicker__month-text--keyboard-selected,.react-datepicker__quarter-text--keyboard-selected,.react-datepicker__year-text--keyboard-selected{border-radius:.3rem;background-color:#bad9f1;color:#000}.react-datepicker__day--keyboard-selected:not([aria-disabled=true]):hover,.react-datepicker__month-text--keyboard-selected:not([aria-disabled=true]):hover,.react-datepicker__quarter-text--keyboard-selected:not([aria-disabled=true]):hover,.react-datepicker__year-text--keyboard-selected:not([aria-disabled=true]):hover{background-color:#1d5d90}.react-datepicker__day--in-selecting-range:not(.react-datepicker__day--in-range,.react-datepicker__month-text--in-range,.react-datepicker__quarter-text--in-range,.react-datepicker__year-text--in-range),.react-datepicker__month-text--in-selecting-range:not(.react-datepicker__day--in-range,.react-datepicker__month-text--in-range,.react-datepicker__quarter-text--in-range,.react-datepicker__year-text--in-range),.react-datepicker__quarter-text--in-selecting-range:not(.react-datepicker__day--in-range,.react-datepicker__month-text--in-range,.react-datepicker__quarter-text--in-range,.react-datepicker__year-text--in-range),.react-datepicker__year-text--in-selecting-range:not(.react-datepicker__day--in-range,.react-datepicker__month-text--in-range,.react-datepicker__quarter-text--in-range,.react-datepicker__year-text--in-range){background-color:#216ba580}.react-datepicker__month--selecting-range .react-datepicker__day--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__year--selecting-range .react-datepicker__day--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__month--selecting-range .react-datepicker__month-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__year--selecting-range .react-datepicker__month-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__month--selecting-range .react-datepicker__quarter-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__year--selecting-range .react-datepicker__quarter-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__month--selecting-range .react-datepicker__year-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range),.react-datepicker__year--selecting-range .react-datepicker__year-text--in-range:not(.react-datepicker__day--in-selecting-range,.react-datepicker__month-text--in-selecting-range,.react-datepicker__quarter-text--in-selecting-range,.react-datepicker__year-text--in-selecting-range){background-color:#f0f0f0;color:#000}.react-datepicker__day--disabled,.react-datepicker__month-text--disabled,.react-datepicker__quarter-text--disabled,.react-datepicker__year-text--disabled{cursor:default;color:#ccc}.react-datepicker__day--disabled .overlay,.react-datepicker__month-text--disabled .overlay,.react-datepicker__quarter-text--disabled .overlay,.react-datepicker__year-text--disabled .overlay{position:absolute;bottom:70%;left:50%;transform:translate(-50%);background-color:#333;color:#fff;padding:4px;border-radius:4px;white-space:nowrap;visibility:hidden;opacity:0;transition:visibility 0s,opacity .3s ease-in-out}.react-datepicker__input-container{position:relative;display:inline-block;width:100%}.react-datepicker__input-container .react-datepicker__calendar-icon{position:absolute;padding:.5rem;box-sizing:content-box}.react-datepicker__view-calendar-icon input{padding:6px 10px 5px 25px}.react-datepicker__year-read-view,.react-datepicker__month-read-view,.react-datepicker__month-year-read-view{border:1px solid transparent;border-radius:.3rem;position:relative}.react-datepicker__year-read-view:hover,.react-datepicker__month-read-view:hover,.react-datepicker__month-year-read-view:hover{cursor:pointer}.react-datepicker__year-read-view:hover .react-datepicker__year-read-view--down-arrow,.react-datepicker__year-read-view:hover .react-datepicker__month-read-view--down-arrow,.react-datepicker__month-read-view:hover .react-datepicker__year-read-view--down-arrow,.react-datepicker__month-read-view:hover .react-datepicker__month-read-view--down-arrow,.react-datepicker__month-year-read-view:hover .react-datepicker__year-read-view--down-arrow,.react-datepicker__month-year-read-view:hover .react-datepicker__month-read-view--down-arrow{border-top-color:#b3b3b3}.react-datepicker__year-read-view--down-arrow,.react-datepicker__month-read-view--down-arrow,.react-datepicker__month-year-read-view--down-arrow{transform:rotate(135deg);right:-16px;top:0}.react-datepicker__year-dropdown,.react-datepicker__month-dropdown,.react-datepicker__month-year-dropdown{background-color:#f0f0f0;position:absolute;width:50%;left:25%;top:30px;z-index:1;text-align:center;border-radius:.3rem;border:1px solid #aeaeae}.react-datepicker__year-dropdown:hover,.react-datepicker__month-dropdown:hover,.react-datepicker__month-year-dropdown:hover{cursor:pointer}.react-datepicker__year-dropdown--scrollable,.react-datepicker__month-dropdown--scrollable,.react-datepicker__month-year-dropdown--scrollable{height:150px;overflow-y:scroll}.react-datepicker__year-option,.react-datepicker__month-option,.react-datepicker__month-year-option{line-height:20px;width:100%;display:block;margin-left:auto;margin-right:auto}.react-datepicker__year-option:first-of-type,.react-datepicker__month-option:first-of-type,.react-datepicker__month-year-option:first-of-type{border-top-left-radius:.3rem;border-top-right-radius:.3rem}.react-datepicker__year-option:last-of-type,.react-datepicker__month-option:last-of-type,.react-datepicker__month-year-option:last-of-type{-webkit-user-select:none;-moz-user-select:none;user-select:none;border-bottom-left-radius:.3rem;border-bottom-right-radius:.3rem}.react-datepicker__year-option:hover,.react-datepicker__month-option:hover,.react-datepicker__month-year-option:hover{background-color:#ccc}.react-datepicker__year-option:hover .react-datepicker__navigation--years-upcoming,.react-datepicker__month-option:hover .react-datepicker__navigation--years-upcoming,.react-datepicker__month-year-option:hover .react-datepicker__navigation--years-upcoming{border-bottom-color:#b3b3b3}.react-datepicker__year-option:hover .react-datepicker__navigation--years-previous,.react-datepicker__month-option:hover .react-datepicker__navigation--years-previous,.react-datepicker__month-year-option:hover .react-datepicker__navigation--years-previous{border-top-color:#b3b3b3}.react-datepicker__year-option--selected,.react-datepicker__month-option--selected,.react-datepicker__month-year-option--selected{position:absolute;left:15px}.react-datepicker__close-icon{cursor:pointer;background-color:transparent;border:0;outline:0;padding:0 6px 0 0;position:absolute;top:0;right:0;height:100%;display:table-cell;vertical-align:middle}.react-datepicker__close-icon:after{cursor:pointer;background-color:#216ba5;color:#fff;border-radius:50%;height:16px;width:16px;padding:2px;font-size:12px;line-height:1;text-align:center;display:table-cell;vertical-align:middle;content:"×"}.react-datepicker__close-icon--disabled{cursor:default}.react-datepicker__close-icon--disabled:after{cursor:default;background-color:#ccc}.react-datepicker__today-button{background:#f0f0f0;border-top:1px solid #aeaeae;cursor:pointer;text-align:center;font-weight:700;padding:5px 0;clear:left}.react-datepicker__portal{position:fixed;width:100vw;height:100vh;background-color:#000c;left:0;top:0;justify-content:center;align-items:center;display:flex;z-index:2147483647}.react-datepicker__portal .react-datepicker__day-name,.react-datepicker__portal .react-datepicker__day,.react-datepicker__portal .react-datepicker__time-name{width:3rem;line-height:3rem}@media (max-width: 400px),(max-height: 550px){.react-datepicker__portal .react-datepicker__day-name,.react-datepicker__portal .react-datepicker__day,.react-datepicker__portal .react-datepicker__time-name{width:2rem;line-height:2rem}}.react-datepicker__portal .react-datepicker__current-month,.react-datepicker__portal .react-datepicker-time__header{font-size:1.44rem}.react-datepicker__children-container{width:13.8rem;margin:.4rem;padding-right:.2rem;padding-left:.2rem;height:auto}.react-datepicker__aria-live{position:absolute;clip-path:circle(0);border:0;height:1px;margin:-1px;overflow:hidden;padding:0;width:1px;white-space:nowrap}.react-datepicker__calendar-icon{width:1em;height:1em;vertical-align:-.125em}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{--background: 0 0% 100%;--foreground: 0 0% 3.9%;--muted: 0 0% 96.1%;--muted-foreground: 0 0% 45.1%;--popover: 0 0% 100%;--popover-foreground: 0 0% 3.9%;--border: 0 0% 89.8%;--input: 0 0% 89.8%;--card: 0 0% 100%;--card-foreground: 0 0% 3.9%;--primary: 0 0% 9%;--primary-foreground: 0 0% 98%;--secondary: 0 0% 96.1%;--secondary-foreground: 0 0% 9%;--accent: 0 0% 96.1%;--accent-foreground: 0 0% 9%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--ring: 0 0% 3.9%;--radius: .5rem;--chart-1: 12 76% 61%;--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;--chart-5: 27 87% 67%;--sidebar-background: 0 0% 98%;--sidebar-foreground: 240 5.3% 26.1%;--sidebar-primary: 240 5.9% 10%;--sidebar-primary-foreground: 0 0% 98%;--sidebar-accent: 240 4.8% 95.9%;--sidebar-accent-foreground: 240 5.9% 10%;--sidebar-border: 220 13% 91%;--sidebar-ring: 217.2 91.2% 59.8%}.dark{--background: 0 0% 7%;--foreground: 0 0% 90%;--card: 0 0% 9%;--card-foreground: 0 0% 90%;--popover: 0 0% 7%;--popover-foreground: 0 0% 90%;--primary: 199 87% 64%;--primary-foreground: 0 0% 7%;--secondary: 0 0% 11%;--secondary-foreground: 0 0% 90%;--muted: 0 0% 11%;--muted-foreground: 0 0% 63%;--accent: 0 0% 11%;--accent-foreground: 0 0% 90%;--destructive: 0 84% 60%;--destructive-foreground: 0 0% 90%;--border: 0 0% 13%;--input: 0 0% 13%;--ring: 0 0% 13%;--radius: .25rem;--chart-1: 199 87% 64%;--chart-2: 120 56% 49%;--chart-3: 40 100% 50%;--chart-4: 283 39% 53%;--chart-5: 13 75% 58%;--sidebar-background: 0 0% 7%;--sidebar-foreground: 0 0% 90%;--sidebar-primary: 199 87% 64%;--sidebar-primary-foreground: 0 0% 100%;--sidebar-accent: 0 0% 11%;--sidebar-accent-foreground: 0 0% 90%;--sidebar-border: 0 0% 13%;--sidebar-ring: 199 87% 64%}body{background-color:hsl(var(--background));font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";color:hsl(var(--foreground));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}.container{width:100%;margin-right:auto;margin-left:auto;padding-right:2rem;padding-left:2rem}@media (min-width: 1400px){.container{max-width:1400px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.-right-6{right:-1.5rem}.bottom-0{bottom:0}.bottom-8{bottom:2rem}.left-0{left:0}.left-2{left:.5rem}.left-\[50\%\]{left:50%}.right-0{right:0}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-8{right:2rem}.top-0{top:0}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-2\.5{top:.625rem}.top-3{top:.75rem}.top-3\.5{top:.875rem}.top-4{top:1rem}.top-\[50\%\]{top:50%}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-50{z-index:50}.z-\[100\]{z-index:100}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3\.5{margin-left:.875rem;margin-right:.875rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.-ml-3{margin-left:-.75rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-4{margin-right:1rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-auto{aspect-ratio:auto}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.size-4{width:1rem;height:1rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-24{height:6rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[1\.2rem\]{height:1.2rem}.h-\[120px\]{height:120px}.h-\[180px\]{height:180px}.h-\[1px\]{height:1px}.h-\[500px\]{height:500px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-svh{height:100svh}.max-h-96{max-height:24rem}.max-h-\[300px\]{max-height:300px}.max-h-screen{max-height:100vh}.min-h-0{min-height:0px}.min-h-\[32px\]{min-height:32px}.min-h-\[60px\]{min-height:60px}.min-h-\[80vh\]{min-height:80vh}.min-h-\[calc\(100vh-12rem\)\]{min-height:calc(100vh - 12rem)}.min-h-screen{min-height:100vh}.min-h-svh{min-height:100svh}.w-0{width:0px}.w-1{width:.25rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-80{width:20rem}.w-9{width:2.25rem}.w-\[--sidebar-width\]{width:var(--sidebar-width)}.w-\[1\.2rem\]{width:1.2rem}.w-\[100px\]{width:100px}.w-\[150px\]{width:150px}.w-\[160px\]{width:160px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[200px\]{width:200px}.w-\[250px\]{width:250px}.w-\[280px\]{width:280px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[50px\]{width:50px}.w-\[80px\]{width:80px}.w-auto{width:auto}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-10{min-width:2.5rem}.min-w-5{min-width:1.25rem}.min-w-8{min-width:2rem}.min-w-9{min-width:2.25rem}.min-w-\[120px\]{min-width:120px}.min-w-\[200px\]{min-width:200px}.min-w-\[300px\]{min-width:300px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-2xl{max-width:42rem}.max-w-\[--skeleton-width\]{max-width:var(--skeleton-width)}.max-w-\[450px\]{max-width:450px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.caption-bottom{caption-side:bottom}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-x-px{--tw-translate-x: -1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-2{--tw-translate-x: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-px{--tw-translate-x: 1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-0{--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-\[1fr_auto\]{grid-template-columns:1fr auto}.grid-cols-\[200px_1fr_80px\]{grid-template-columns:200px 1fr 80px}.grid-cols-\[auto_1fr_auto\]{grid-template-columns:auto 1fr auto}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-x-4{-moz-column-gap:1rem;column-gap:1rem}.gap-y-2{row-gap:.5rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-border>:not([hidden])~:not([hidden]){border-color:hsl(var(--border))}.self-end{align-self:flex-end}.justify-self-start{justify-self:start}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.rounded-t-lg{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-t-0{border-top-width:0px}.border-dashed{border-style:dashed}.border-\[--color-border\]{border-color:var(--color-border)}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-destructive{border-color:hsl(var(--destructive))}.border-destructive\/50{border-color:hsl(var(--destructive) / .5)}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-400{--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.border-sidebar-border{border-color:hsl(var(--sidebar-border))}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-accent{background-color:hsl(var(--accent))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-background{background-color:hsl(var(--background))}.bg-background\/50{background-color:hsl(var(--background) / .5)}.bg-black\/80{background-color:#000c}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-500\/20{background-color:#3b82f633}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-card\/50{background-color:hsl(var(--card) / .5)}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-destructive\/10{background-color:hsl(var(--destructive) / .1)}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-fuchsia-100{--tw-bg-opacity: 1;background-color:rgb(250 232 255 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-500\/20{background-color:#6b728033}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/20{background-color:#22c55e33}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-lime-100{--tw-bg-opacity: 1;background-color:rgb(236 252 203 / var(--tw-bg-opacity, 1))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/5{background-color:hsl(var(--muted) / .05)}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500\/20{background-color:#f9731633}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/10{background-color:hsl(var(--primary) / .1)}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-500\/20{background-color:#a855f733}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/20{background-color:#ef444433}.bg-rose-100{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-secondary\/50{background-color:hsl(var(--secondary) / .5)}.bg-sidebar{background-color:hsl(var(--sidebar-background))}.bg-sidebar-border{background-color:hsl(var(--sidebar-border))}.bg-sky-100{--tw-bg-opacity: 1;background-color:rgb(224 242 254 / var(--tw-bg-opacity, 1))}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/20{background-color:#eab30833}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-primary{--tw-gradient-from: hsl(var(--primary)) var(--tw-gradient-from-position);--tw-gradient-to: hsl(var(--primary) / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-primary\/50{--tw-gradient-to: hsl(var(--primary) / .5) var(--tw-gradient-to-position)}.bg-clip-text{-webkit-background-clip:text;background-clip:text}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-0{padding-bottom:0}.pb-1{padding-bottom:.25rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pb-8{padding-bottom:2rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pr-2{padding-right:.5rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.capitalize{text-transform:capitalize}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-current{color:currentColor}.text-cyan-600{--tw-text-opacity: 1;color:rgb(8 145 178 / var(--tw-text-opacity, 1))}.text-cyan-800{--tw-text-opacity: 1;color:rgb(21 94 117 / var(--tw-text-opacity, 1))}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-fuchsia-800{--tw-text-opacity: 1;color:rgb(134 25 143 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-600{--tw-text-opacity: 1;color:rgb(79 70 229 / var(--tw-text-opacity, 1))}.text-indigo-800{--tw-text-opacity: 1;color:rgb(55 48 163 / var(--tw-text-opacity, 1))}.text-lime-800{--tw-text-opacity: 1;color:rgb(63 98 18 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/70{color:hsl(var(--muted-foreground) / .7)}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-rose-800{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sidebar-foreground{color:hsl(var(--sidebar-foreground))}.text-sidebar-foreground\/70{color:hsl(var(--sidebar-foreground) / .7)}.text-sky-800{--tw-text-opacity: 1;color:rgb(7 89 133 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-transparent{color:transparent}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-border));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.\!ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color) !important;--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color) !important;box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)!important}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-sidebar-ring{--tw-ring-color: hsl(var(--sidebar-ring))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[margin\,opa\]{transition-property:margin,opa;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-150{transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{transition-timing-function:linear}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-50{--tw-enter-scale: .5}.zoom-in-95{--tw-enter-scale: .95}.duration-1000{animation-duration:1s}.duration-150{animation-duration:.15s}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{animation-timing-function:linear}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.file\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);top:-.5rem;right:-.5rem;bottom:-.5rem;left:-.5rem}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:bg-border\/40:after{content:var(--tw-content);background-color:hsl(var(--border) / .4)}.last\:mb-0:last-child{margin-bottom:0}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-accent\/50:hover{background-color:hsl(var(--accent) / .5)}.hover\:bg-blue-500\/30:hover{background-color:#3b82f64d}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-gray-500\/30:hover{background-color:#6b72804d}.hover\:bg-green-500\/30:hover{background-color:#22c55e4d}.hover\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-orange-500\/30:hover{background-color:#f973164d}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-purple-500\/30:hover{background-color:#a855f74d}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-sidebar-accent:hover{background-color:hsl(var(--sidebar-accent))}.hover\:bg-transparent:hover{background-color:transparent}.hover\:bg-yellow-500\/30:hover{background-color:#eab3084d}.hover\:bg-yellow-600:hover{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary:hover{color:hsl(var(--primary))}.hover\:text-red-900:hover{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.hover\:text-sidebar-accent-foreground:hover{color:hsl(var(--sidebar-accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-accent));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:ring-1:hover{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.hover\:ring-gray-300:hover{--tw-ring-opacity: 1;--tw-ring-color: rgb(209 213 219 / var(--tw-ring-opacity, 1))}.hover\:after\:bg-border:hover:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:hsl(var(--sidebar-border))}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-sidebar-ring:focus-visible{--tw-ring-color: hsl(var(--sidebar-ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.active\:bg-sidebar-accent:active{background-color:hsl(var(--sidebar-accent))}.active\:text-sidebar-accent-foreground:active{color:hsl(var(--sidebar-accent-foreground))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:hover\:bg-red-50:hover:disabled{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.group\/menu-item:focus-within .group-focus-within\/menu-item\:opacity-100{opacity:1}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.group:hover .group-hover\:animate-bounce{animation:bounce 1s infinite}@keyframes spin{to{transform:rotate(360deg)}}.group:hover .group-hover\:animate-spin{animation:spin 1s linear infinite}.group\/menu-item:hover .group-hover\/menu-item\:opacity-100,.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity, 1))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity, 1))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer\/menu-button:hover~.peer-hover\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.has-\[\[data-variant\=inset\]\]\:bg-sidebar:has([data-variant=inset]){background-color:hsl(var(--sidebar-background))}.group\/menu-item:has([data-sidebar=menu-action]) .group-has-\[\[data-sidebar\=menu-action\]\]\/menu-item\:pr-8{padding-right:2rem}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:.5}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true],.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:hsl(var(--sidebar-accent))}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:hsl(var(--accent))}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted\/50[data-state=open]{background-color:hsl(var(--muted) / .5)}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:hsl(var(--secondary))}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[active\=true\]\:font-medium[data-active=true]{font-weight:500}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:hsl(var(--sidebar-accent-foreground))}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:hsl(var(--accent-foreground))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\=true\]\:opacity-50[data-disabled=true],.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:1}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-300[data-state=closed]{transition-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{transition-duration:.5s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-300[data-state=closed]{animation-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{animation-duration:.5s}.data-\[state\=open\]\:hover\:bg-sidebar-accent:hover[data-state=open]{background-color:hsl(var(--sidebar-accent))}.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground:hover[data-state=open]{color:hsl(var(--sidebar-accent-foreground))}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]{left:calc(var(--sidebar-width) * -1)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]{right:calc(var(--sidebar-width) * -1)}.group[data-side=left] .group-data-\[side\=left\]\:-right-4{right:-1rem}.group[data-side=right] .group-data-\[side\=right\]\:left-0{left:0}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:-mt-8{margin-top:-2rem}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:hidden{display:none}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!size-8{width:2rem!important;height:2rem!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[--sidebar-width-icon\]{width:var(--sidebar-width-icon)}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)_\+_theme\(spacing\.4\)\)\]{width:calc(var(--sidebar-width-icon) + 1rem)}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)_\+_theme\(spacing\.4\)_\+2px\)\]{width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:w-0{width:0px}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-side=right] .group-data-\[side\=right\]\:rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:overflow-hidden{overflow:hidden}.group[data-variant=floating] .group-data-\[variant\=floating\]\:rounded-lg{border-radius:var(--radius)}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border{border-width:1px}.group[data-side=left] .group-data-\[side\=left\]\:border-r{border-right-width:1px}.group[data-side=right] .group-data-\[side\=right\]\:border-l{border-left-width:1px}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border-sidebar-border{border-color:hsl(var(--sidebar-border))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!p-0{padding:0!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!p-2{padding:.5rem!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:opacity-0{opacity:0}.group[data-variant=floating] .group-data-\[variant\=floating\]\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:after\:left-full:after{content:var(--tw-content);left:100%}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:hover\:bg-sidebar:hover{background-color:hsl(var(--sidebar-background))}.peer\/menu-button[data-size=default]~.peer-data-\[size\=default\]\/menu-button\:top-1\.5{top:.375rem}.peer\/menu-button[data-size=lg]~.peer-data-\[size\=lg\]\/menu-button\:top-2\.5{top:.625rem}.peer\/menu-button[data-size=sm]~.peer-data-\[size\=sm\]\/menu-button\:top-1{top:.25rem}.peer[data-variant=inset]~.peer-data-\[variant\=inset\]\:min-h-\[calc\(100svh-theme\(spacing\.4\)\)\]{min-height:calc(100svh - 1rem)}.peer\/menu-button[data-active=true]~.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.dark\:border-destructive:is(.dark *){border-color:hsl(var(--destructive))}.dark\:border-gray-500:is(.dark *){--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:bg-amber-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(120 53 15 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-500:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-500\/30:is(.dark *){background-color:#3b82f64d}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(23 37 84 / var(--tw-bg-opacity, 1))}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-cyan-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(8 51 68 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(2 44 34 / var(--tw-bg-opacity, 1))}.dark\:bg-fuchsia-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(112 26 117 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-500\/30:is(.dark *){background-color:#6b72804d}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-500\/30:is(.dark *){background-color:#22c55e4d}.dark\:bg-green-500\/80:is(.dark *){background-color:#22c55ecc}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-green-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(5 46 22 / var(--tw-bg-opacity, 1))}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(49 46 129 / var(--tw-bg-opacity, 1))}.dark\:bg-indigo-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 27 75 / var(--tw-bg-opacity, 1))}.dark\:bg-lime-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(54 83 20 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-500\/30:is(.dark *){background-color:#f973164d}.dark\:bg-orange-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(124 45 18 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(67 20 7 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-500\/30:is(.dark *){background-color:#a855f74d}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(59 7 100 / var(--tw-bg-opacity, 1))}.dark\:bg-red-500\/30:is(.dark *){background-color:#ef44444d}.dark\:bg-red-500\/80:is(.dark *){background-color:#ef4444cc}.dark\:bg-red-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:bg-red-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 10 10 / var(--tw-bg-opacity, 1))}.dark\:bg-rose-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(136 19 55 / var(--tw-bg-opacity, 1))}.dark\:bg-sky-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(12 74 110 / var(--tw-bg-opacity, 1))}.dark\:bg-teal-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(19 78 74 / var(--tw-bg-opacity, 1))}.dark\:bg-transparent:is(.dark *){background-color:transparent}.dark\:bg-yellow-500\/30:is(.dark *){background-color:#eab3084d}.dark\:bg-yellow-500\/80:is(.dark *){background-color:#eab308cc}.dark\:bg-yellow-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.dark\:bg-yellow-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(66 32 6 / var(--tw-bg-opacity, 1))}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.dark\:text-blue-200:is(.dark *){--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-cyan-200:is(.dark *){--tw-text-opacity: 1;color:rgb(165 243 252 / var(--tw-text-opacity, 1))}.dark\:text-cyan-300:is(.dark *){--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.dark\:text-cyan-400:is(.dark *){--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.dark\:text-emerald-400:is(.dark *){--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.dark\:text-fuchsia-200:is(.dark *){--tw-text-opacity: 1;color:rgb(245 208 254 / var(--tw-text-opacity, 1))}.dark\:text-gray-200:is(.dark *){--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-300:is(.dark *){--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-indigo-200:is(.dark *){--tw-text-opacity: 1;color:rgb(199 210 254 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-lime-200:is(.dark *){--tw-text-opacity: 1;color:rgb(217 249 157 / var(--tw-text-opacity, 1))}.dark\:text-orange-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 215 170 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-orange-400:is(.dark *){--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-purple-400:is(.dark *){--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-rose-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 205 211 / var(--tw-text-opacity, 1))}.dark\:text-rose-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.dark\:text-sky-300:is(.dark *){--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.dark\:text-teal-200:is(.dark *){--tw-text-opacity: 1;color:rgb(153 246 228 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-green-500:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-red-500:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-red-900:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-yellow-500:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.dark\:hover\:ring-gray-600:hover:is(.dark *){--tw-ring-opacity: 1;--tw-ring-color: rgb(75 85 99 / var(--tw-ring-opacity, 1))}.dark\:disabled\:hover\:bg-red-950:hover:disabled:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(69 10 10 / var(--tw-bg-opacity, 1))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:flex{display:flex}.sm\:h-24{height:6rem}.sm\:w-24{width:6rem}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:gap-2\.5{gap:.625rem}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:p-6{padding:1.5rem}.sm\:px-8{padding-left:2rem;padding-right:2rem}.sm\:py-6{padding-top:1.5rem;padding-bottom:1.5rem}.sm\:text-left{text-align:left}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}.sm\:text-7xl{font-size:4.5rem;line-height:1}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:block{display:block}.md\:flex{display:flex}.md\:max-w-\[420px\]{max-width:420px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:text-sm{font-size:.875rem;line-height:1.25rem}.md\:opacity-0{opacity:0}.after\:md\:hidden:after{content:var(--tw-content);display:none}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:m-2{margin:.5rem}.peer[data-state=collapsed][data-variant=inset]~.md\:peer-data-\[state\=collapsed\]\:peer-data-\[variant\=inset\]\:ml-2{margin-left:.5rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:ml-0{margin-left:0}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:rounded-xl{border-radius:.75rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y: 2px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:size-4>svg{width:1rem;height:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:h-3\.5>svg{height:.875rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:w-3\.5>svg{width:.875rem}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:text-destructive>svg{color:hsl(var(--destructive))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:hsl(var(--sidebar-accent-foreground))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:size-4 svg{width:1rem;height:1rem}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:-.5rem}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=left] .\[\[data-side\=left\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:-.5rem}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-side=right] .\[\[data-side\=right\]_\&\]\:cursor-e-resize{cursor:e-resize} diff --git a/pkg/ui/frontend/dist/assets/theme-utils-CNom64Sw.js b/pkg/ui/frontend/dist/assets/theme-utils-CNom64Sw.js new file mode 100644 index 0000000000000..1906165eb8da4 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/theme-utils-CNom64Sw.js @@ -0,0 +1 @@ +import{r as l}from"./react-core-D_V7s-9r.js";var v=(t,i,m,n,s,a,u,d)=>{let r=document.documentElement,h=["light","dark"];function o(e){(Array.isArray(t)?t:[t]).forEach(c=>{let p=c==="class",S=p&&a?s.map(f=>a[f]||f):s;p?(r.classList.remove(...S),r.classList.add(e)):r.setAttribute(c,e)}),y(e)}function y(e){d&&h.includes(e)&&(r.style.colorScheme=e)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(n)o(n);else try{let e=localStorage.getItem(i)||m,c=u&&e==="system"?g():e;o(c)}catch{}},E=l.createContext(void 0),b={setTheme:t=>{},themes:[]},w=()=>{var t;return(t=l.useContext(E))!=null?t:b};l.memo(({forcedTheme:t,storageKey:i,attribute:m,enableSystem:n,enableColorScheme:s,defaultTheme:a,value:u,themes:d,nonce:r,scriptProps:h})=>{let o=JSON.stringify([m,i,a,t,d,u,n,s]).slice(1,-1);return l.createElement("script",{...h,suppressHydrationWarning:!0,nonce:typeof window>"u"?r:"",dangerouslySetInnerHTML:{__html:`(${v.toString()})(${o})`}})});export{w as z}; diff --git a/pkg/ui/frontend/dist/assets/ui-icons-CFVjIJRk.js b/pkg/ui/frontend/dist/assets/ui-icons-CFVjIJRk.js new file mode 100644 index 0000000000000..df33ce94fd275 --- /dev/null +++ b/pkg/ui/frontend/dist/assets/ui-icons-CFVjIJRk.js @@ -0,0 +1,191 @@ +import{r as h,b as s}from"./react-core-D_V7s-9r.js";/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const g=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),m=(...e)=>e.filter((t,o,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===o).join(" ").trim();/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var x={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const b=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:o=2,absoluteStrokeWidth:r,className:a="",children:c,iconNode:p,...y},i)=>h.createElement("svg",{ref:i,...x,width:t,height:t,stroke:e,strokeWidth:r?Number(o)*24/Number(t):o,className:m("lucide",a),...y},[...p.map(([w,_])=>h.createElement(w,_)),...Array.isArray(c)?c:[c]]));/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const n=(e,t)=>{const o=h.forwardRef(({className:r,...a},c)=>h.createElement(b,{ref:c,iconNode:t,className:m(`lucide-${g(e)}`,r),...a}));return o.displayName=`${e}`,o};/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const C=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],le=n("ArrowDown",C);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const M=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],pe=n("ArrowUp",M);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const N=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],ue=n("BookOpen",N);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ke=n("Check",$);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],me=n("ChevronDown",j);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const O=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ve=n("ChevronRight",O);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const P=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],fe=n("ChevronUp",P);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const D=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],we=n("ChevronsUpDown",D);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],_e=n("CircleAlert",A);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const q=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]],ge=n("CircleArrowDown",q);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const z=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]],xe=n("CircleArrowRight",z);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]],be=n("CircleArrowUp",L);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const E=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Ce=n("CircleDot",E);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const R=[["path",{d:"M15.6 2.7a10 10 0 1 0 5.7 5.7",key:"1e0p6d"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M13.4 10.6 19 5",key:"1kr7tw"}]],Me=n("CircleGauge",R);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const S=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Ne=n("Circle",S);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const U=[["rect",{x:"2",y:"6",width:"20",height:"8",rx:"1",key:"1estib"}],["path",{d:"M17 14v7",key:"7m2elx"}],["path",{d:"M7 14v7",key:"1cm7wv"}],["path",{d:"M17 3v3",key:"1v4jwn"}],["path",{d:"M7 3v3",key:"7o6guu"}],["path",{d:"M10 14 2.3 6.3",key:"1023jk"}],["path",{d:"m14 6 7.7 7.7",key:"1s8pl2"}],["path",{d:"m8 6 8 8",key:"hl96qh"}]],$e=n("Construction",U);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const H=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],je=n("Copy",H);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const V=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Oe=n("Database",V);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const B=[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]],Pe=n("Download",B);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const I=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]],De=n("File",I);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const F=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Ae=n("Folder",F);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const G=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]],qe=n("House",G);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const W=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],ze=n("LayoutDashboard",W);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Z=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Le=n("LoaderCircle",Z);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],Ee=n("Moon",K);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const T=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Re=n("PanelLeft",T);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const X=[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]],Se=n("Pause",X);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const J=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ue=n("Plus",J);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Q=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],He=n("RefreshCw",Q);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Y=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Ve=n("RotateCcw",Y);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ee=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]],Be=n("Search",ee);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const te=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],Ie=n("Sun",te);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const oe=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]],Fe=n("Users",oe);/** + * @license lucide-react v0.474.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const re=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ge=n("X",re);var v={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},u=s.createContext&&s.createContext(v),ne=["attr","size","title"];function ae(e,t){if(e==null)return{};var o=ce(e,t),r,a;if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(a=0;a<c.length;a++)r=c[a],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function ce(e,t){if(e==null)return{};var o={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;o[r]=e[r]}return o}function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},d.apply(this,arguments)}function k(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),o.push.apply(o,r)}return o}function l(e){for(var t=1;t<arguments.length;t++){var o=arguments[t]!=null?arguments[t]:{};t%2?k(Object(o),!0).forEach(function(r){ie(e,r,o[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):k(Object(o)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))})}return e}function ie(e,t,o){return t=se(t),t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function se(e){var t=he(e,"string");return typeof t=="symbol"?t:t+""}function he(e,t){if(typeof e!="object"||!e)return e;var o=e[Symbol.toPrimitive];if(o!==void 0){var r=o.call(e,t||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function f(e){return e&&e.map((t,o)=>s.createElement(t.tag,l({key:o},t.attr),f(t.child)))}function We(e){return t=>s.createElement(ye,d({attr:l({},e.attr)},t),f(e.child))}function ye(e){var t=o=>{var{attr:r,size:a,title:c}=e,p=ae(e,ne),y=a||o.size||"1em",i;return o.className&&(i=o.className),e.className&&(i=(i?i+" ":"")+e.className),s.createElement("svg",d({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},o.attr,r,p,{className:i,style:l(l({color:e.color||o.color},o.style),e.style),height:y,width:y,xmlns:"http://www.w3.org/2000/svg"}),c&&s.createElement("title",null,c),e.children)};return u!==void 0?s.createElement(u.Consumer,null,o=>t(o)):t(v)}export{le as A,ue as B,ve as C,Pe as D,Ae as F,We as G,qe as H,Le as L,Ee as M,Se as P,Ve as R,Ie as S,Fe as U,Ge as X,ke as a,Ne as b,pe as c,we as d,xe as e,Be as f,_e as g,Ce as h,be as i,ge as j,me as k,fe as l,De as m,je as n,He as o,$e as p,Ue as q,Re as r,ze as s,Oe as t,Me as u}; diff --git a/pkg/ui/frontend/dist/assets/ui-utils-BNSC_Jv-.js b/pkg/ui/frontend/dist/assets/ui-utils-BNSC_Jv-.js new file mode 100644 index 0000000000000..33dde34c5d8df --- /dev/null +++ b/pkg/ui/frontend/dist/assets/ui-utils-BNSC_Jv-.js @@ -0,0 +1 @@ +function ee(e){var t,r,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var l=e.length;for(t=0;t<l;t++)e[t]&&(r=ee(e[t]))&&(o&&(o+=" "),o+=r)}else for(r in e)e[r]&&(o&&(o+=" "),o+=r);return o}function le(){for(var e,t,r=0,o="",l=arguments.length;r<l;r++)(e=arguments[r])&&(t=ee(e))&&(o&&(o+=" "),o+=t);return o}const H=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Q=le,Oe=(e,t)=>r=>{var o;if((t==null?void 0:t.variants)==null)return Q(e,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:l,defaultVariants:n}=t,a=Object.keys(l).map(c=>{const g=r==null?void 0:r[c],h=n==null?void 0:n[c];if(g===null)return null;const m=H(g)||H(h);return l[c][m]}),s=r&&Object.entries(r).reduce((c,g)=>{let[h,m]=g;return m===void 0||(c[h]=m),c},{}),b=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((c,g)=>{let{class:h,className:m,...v}=g;return Object.entries(v).every(x=>{let[f,d]=x;return Array.isArray(d)?d.includes({...n,...s}[f]):{...n,...s}[f]===d})?[...c,h,m]:c},[]);return Q(e,a,b,r==null?void 0:r.class,r==null?void 0:r.className)},U="-",ie=e=>{const t=ce(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:a=>{const s=a.split(U);return s[0]===""&&s.length!==1&&s.shift(),re(s,t)||ae(a)},getConflictingClassGroupIds:(a,s)=>{const b=r[a]||[];return s&&o[a]?[...b,...o[a]]:b}}},re=(e,t)=>{var a;if(e.length===0)return t.classGroupId;const r=e[0],o=t.nextPart.get(r),l=o?re(e.slice(1),o):void 0;if(l)return l;if(t.validators.length===0)return;const n=e.join(U);return(a=t.validators.find(({validator:s})=>s(n)))==null?void 0:a.classGroupId},Y=/^\[(.+)\]$/,ae=e=>{if(Y.test(e)){const t=Y.exec(e)[1],r=t==null?void 0:t.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},ce=e=>{const{theme:t,prefix:r}=e,o={nextPart:new Map,validators:[]};return ue(Object.entries(e.classGroups),r).forEach(([n,a])=>{$(a,o,n,t)}),o},$=(e,t,r,o)=>{e.forEach(l=>{if(typeof l=="string"){const n=l===""?t:D(t,l);n.classGroupId=r;return}if(typeof l=="function"){if(de(l)){$(l(o),t,r,o);return}t.validators.push({validator:l,classGroupId:r});return}Object.entries(l).forEach(([n,a])=>{$(a,D(t,n),r,o)})})},D=(e,t)=>{let r=e;return t.split(U).forEach(o=>{r.nextPart.has(o)||r.nextPart.set(o,{nextPart:new Map,validators:[]}),r=r.nextPart.get(o)}),r},de=e=>e.isThemeGetter,ue=(e,t)=>t?e.map(([r,o])=>{const l=o.map(n=>typeof n=="string"?t+n:typeof n=="object"?Object.fromEntries(Object.entries(n).map(([a,s])=>[t+a,s])):n);return[r,l]}):e,pe=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=new Map,o=new Map;const l=(n,a)=>{r.set(n,a),t++,t>e&&(t=0,o=r,r=new Map)};return{get(n){let a=r.get(n);if(a!==void 0)return a;if((a=o.get(n))!==void 0)return l(n,a),a},set(n,a){r.has(n)?r.set(n,a):l(n,a)}}},te="!",be=e=>{const{separator:t,experimentalParseClassName:r}=e,o=t.length===1,l=t[0],n=t.length,a=s=>{const b=[];let c=0,g=0,h;for(let d=0;d<s.length;d++){let y=s[d];if(c===0){if(y===l&&(o||s.slice(d,d+n)===t)){b.push(s.slice(g,d)),g=d+n;continue}if(y==="/"){h=d;continue}}y==="["?c++:y==="]"&&c--}const m=b.length===0?s:s.substring(g),v=m.startsWith(te),x=v?m.substring(1):m,f=h&&h>g?h-g:void 0;return{modifiers:b,hasImportantModifier:v,baseClassName:x,maybePostfixModifierPosition:f}};return r?s=>r({className:s,parseClassName:a}):a},ge=e=>{if(e.length<=1)return e;const t=[];let r=[];return e.forEach(o=>{o[0]==="["?(t.push(...r.sort(),o),r=[]):r.push(o)}),t.push(...r.sort()),t},fe=e=>({cache:pe(e.cacheSize),parseClassName:be(e),...ie(e)}),me=/\s+/,he=(e,t)=>{const{parseClassName:r,getClassGroupId:o,getConflictingClassGroupIds:l}=t,n=[],a=e.trim().split(me);let s="";for(let b=a.length-1;b>=0;b-=1){const c=a[b],{modifiers:g,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:v}=r(c);let x=!!v,f=o(x?m.substring(0,v):m);if(!f){if(!x){s=c+(s.length>0?" "+s:s);continue}if(f=o(m),!f){s=c+(s.length>0?" "+s:s);continue}x=!1}const d=ge(g).join(":"),y=h?d+te:d,w=y+f;if(n.includes(w))continue;n.push(w);const R=l(f,x);for(let S=0;S<R.length;++S){const j=R[S];n.push(y+j)}s=c+(s.length>0?" "+s:s)}return s};function ye(){let e=0,t,r,o="";for(;e<arguments.length;)(t=arguments[e++])&&(r=oe(t))&&(o&&(o+=" "),o+=r);return o}const oe=e=>{if(typeof e=="string")return e;let t,r="";for(let o=0;o<e.length;o++)e[o]&&(t=oe(e[o]))&&(r&&(r+=" "),r+=t);return r};function xe(e,...t){let r,o,l,n=a;function a(b){const c=t.reduce((g,h)=>h(g),e());return r=fe(c),o=r.cache.get,l=r.cache.set,n=s,s(b)}function s(b){const c=o(b);if(c)return c;const g=he(b,r);return l(b,g),g}return function(){return n(ye.apply(null,arguments))}}const u=e=>{const t=r=>r[e]||[];return t.isThemeGetter=!0,t},ne=/^\[(?:([a-z-]+):)?(.+)\]$/i,we=/^\d+\/\d+$/,ve=new Set(["px","full","screen"]),ke=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ce=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ze=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Ae=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Se=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,C=e=>M(e)||ve.has(e)||we.test(e),z=e=>G(e,"length",Ee),M=e=>!!e&&!Number.isNaN(Number(e)),_=e=>G(e,"number",M),I=e=>!!e&&Number.isInteger(Number(e)),Me=e=>e.endsWith("%")&&M(e.slice(0,-1)),i=e=>ne.test(e),A=e=>ke.test(e),Ge=new Set(["length","size","percentage"]),Re=e=>G(e,Ge,se),Pe=e=>G(e,"position",se),Ie=new Set(["image","url"]),Ne=e=>G(e,Ie,Ve),je=e=>G(e,"",Te),N=()=>!0,G=(e,t,r)=>{const o=ne.exec(e);return o?o[1]?typeof t=="string"?o[1]===t:t.has(o[1]):r(o[2]):!1},Ee=e=>Ce.test(e)&&!ze.test(e),se=()=>!1,Te=e=>Ae.test(e),Ve=e=>Se.test(e),Le=()=>{const e=u("colors"),t=u("spacing"),r=u("blur"),o=u("brightness"),l=u("borderColor"),n=u("borderRadius"),a=u("borderSpacing"),s=u("borderWidth"),b=u("contrast"),c=u("grayscale"),g=u("hueRotate"),h=u("invert"),m=u("gap"),v=u("gradientColorStops"),x=u("gradientColorStopPositions"),f=u("inset"),d=u("margin"),y=u("opacity"),w=u("padding"),R=u("saturate"),S=u("scale"),j=u("sepia"),B=u("skew"),F=u("space"),q=u("translate"),V=()=>["auto","contain","none"],L=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",i,t],p=()=>[i,t],J=()=>["",C,z],E=()=>["auto",M,i],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],T=()=>["solid","dashed","dotted","double","none"],X=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],W=()=>["start","end","center","between","around","evenly","stretch"],P=()=>["","0",i],Z=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>[M,i];return{cacheSize:500,separator:":",theme:{colors:[N],spacing:[C,z],blur:["none","",A,i],brightness:k(),borderColor:[e],borderRadius:["none","","full",A,i],borderSpacing:p(),borderWidth:J(),contrast:k(),grayscale:P(),hueRotate:k(),invert:P(),gap:p(),gradientColorStops:[e],gradientColorStopPositions:[Me,z],inset:O(),margin:O(),opacity:k(),padding:p(),saturate:k(),scale:k(),sepia:P(),skew:k(),space:p(),translate:p()},classGroups:{aspect:[{aspect:["auto","square","video",i]}],container:["container"],columns:[{columns:[A]}],"break-after":[{"break-after":Z()}],"break-before":[{"break-before":Z()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...K(),i]}],overflow:[{overflow:L()}],"overflow-x":[{"overflow-x":L()}],"overflow-y":[{"overflow-y":L()}],overscroll:[{overscroll:V()}],"overscroll-x":[{"overscroll-x":V()}],"overscroll-y":[{"overscroll-y":V()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",I,i]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",i]}],grow:[{grow:P()}],shrink:[{shrink:P()}],order:[{order:["first","last","none",I,i]}],"grid-cols":[{"grid-cols":[N]}],"col-start-end":[{col:["auto",{span:["full",I,i]},i]}],"col-start":[{"col-start":E()}],"col-end":[{"col-end":E()}],"grid-rows":[{"grid-rows":[N]}],"row-start-end":[{row:["auto",{span:[I,i]},i]}],"row-start":[{"row-start":E()}],"row-end":[{"row-end":E()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",i]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",i]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...W()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...W(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...W(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[w]}],px:[{px:[w]}],py:[{py:[w]}],ps:[{ps:[w]}],pe:[{pe:[w]}],pt:[{pt:[w]}],pr:[{pr:[w]}],pb:[{pb:[w]}],pl:[{pl:[w]}],m:[{m:[d]}],mx:[{mx:[d]}],my:[{my:[d]}],ms:[{ms:[d]}],me:[{me:[d]}],mt:[{mt:[d]}],mr:[{mr:[d]}],mb:[{mb:[d]}],ml:[{ml:[d]}],"space-x":[{"space-x":[F]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[F]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",i,t]}],"min-w":[{"min-w":[i,t,"min","max","fit"]}],"max-w":[{"max-w":[i,t,"none","full","min","max","fit","prose",{screen:[A]},A]}],h:[{h:[i,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[i,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[i,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[i,t,"auto","min","max","fit"]}],"font-size":[{text:["base",A,z]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",_]}],"font-family":[{font:[N]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",i]}],"line-clamp":[{"line-clamp":["none",M,_]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",C,i]}],"list-image":[{"list-image":["none",i]}],"list-style-type":[{list:["none","disc","decimal",i]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...T(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",C,z]}],"underline-offset":[{"underline-offset":["auto",C,i]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:p()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",i]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",i]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...K(),Pe]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Re]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Ne]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[v]}],"gradient-via":[{via:[v]}],"gradient-to":[{to:[v]}],rounded:[{rounded:[n]}],"rounded-s":[{"rounded-s":[n]}],"rounded-e":[{"rounded-e":[n]}],"rounded-t":[{"rounded-t":[n]}],"rounded-r":[{"rounded-r":[n]}],"rounded-b":[{"rounded-b":[n]}],"rounded-l":[{"rounded-l":[n]}],"rounded-ss":[{"rounded-ss":[n]}],"rounded-se":[{"rounded-se":[n]}],"rounded-ee":[{"rounded-ee":[n]}],"rounded-es":[{"rounded-es":[n]}],"rounded-tl":[{"rounded-tl":[n]}],"rounded-tr":[{"rounded-tr":[n]}],"rounded-br":[{"rounded-br":[n]}],"rounded-bl":[{"rounded-bl":[n]}],"border-w":[{border:[s]}],"border-w-x":[{"border-x":[s]}],"border-w-y":[{"border-y":[s]}],"border-w-s":[{"border-s":[s]}],"border-w-e":[{"border-e":[s]}],"border-w-t":[{"border-t":[s]}],"border-w-r":[{"border-r":[s]}],"border-w-b":[{"border-b":[s]}],"border-w-l":[{"border-l":[s]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...T(),"hidden"]}],"divide-x":[{"divide-x":[s]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[s]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:T()}],"border-color":[{border:[l]}],"border-color-x":[{"border-x":[l]}],"border-color-y":[{"border-y":[l]}],"border-color-s":[{"border-s":[l]}],"border-color-e":[{"border-e":[l]}],"border-color-t":[{"border-t":[l]}],"border-color-r":[{"border-r":[l]}],"border-color-b":[{"border-b":[l]}],"border-color-l":[{"border-l":[l]}],"divide-color":[{divide:[l]}],"outline-style":[{outline:["",...T()]}],"outline-offset":[{"outline-offset":[C,i]}],"outline-w":[{outline:[C,z]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[C,z]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",A,je]}],"shadow-color":[{shadow:[N]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...X(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":X()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[o]}],contrast:[{contrast:[b]}],"drop-shadow":[{"drop-shadow":["","none",A,i]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[g]}],invert:[{invert:[h]}],saturate:[{saturate:[R]}],sepia:[{sepia:[j]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[o]}],"backdrop-contrast":[{"backdrop-contrast":[b]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[g]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[R]}],"backdrop-sepia":[{"backdrop-sepia":[j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",i]}],duration:[{duration:k()}],ease:[{ease:["linear","in","out","in-out",i]}],delay:[{delay:k()}],animate:[{animate:["none","spin","ping","pulse","bounce",i]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[I,i]}],"translate-x":[{"translate-x":[q]}],"translate-y":[{"translate-y":[q]}],"skew-x":[{"skew-x":[B]}],"skew-y":[{"skew-y":[B]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",i]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",i]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":p()}],"scroll-mx":[{"scroll-mx":p()}],"scroll-my":[{"scroll-my":p()}],"scroll-ms":[{"scroll-ms":p()}],"scroll-me":[{"scroll-me":p()}],"scroll-mt":[{"scroll-mt":p()}],"scroll-mr":[{"scroll-mr":p()}],"scroll-mb":[{"scroll-mb":p()}],"scroll-ml":[{"scroll-ml":p()}],"scroll-p":[{"scroll-p":p()}],"scroll-px":[{"scroll-px":p()}],"scroll-py":[{"scroll-py":p()}],"scroll-ps":[{"scroll-ps":p()}],"scroll-pe":[{"scroll-pe":p()}],"scroll-pt":[{"scroll-pt":p()}],"scroll-pr":[{"scroll-pr":p()}],"scroll-pb":[{"scroll-pb":p()}],"scroll-pl":[{"scroll-pl":p()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",i]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[C,z,_]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},We=xe(Le);export{Oe as a,le as c,We as t}; diff --git a/pkg/ui/frontend/dist/index.html b/pkg/ui/frontend/dist/index.html new file mode 100644 index 0000000000000..9af5b6ebeea80 --- /dev/null +++ b/pkg/ui/frontend/dist/index.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Loki UI</title> + <script type="module" crossorigin src="/ui/assets/index-DqJzRHuy.js"></script> + <link rel="modulepreload" crossorigin href="/ui/assets/react-core-D_V7s-9r.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/radix-core-ByqQ8fsu.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/react-router-Bj-soKrx.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/ui-utils-BNSC_Jv-.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/ui-icons-CFVjIJRk.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/date-utils-B6syNIuD.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/radix-navigation-DYoR-lWZ.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/radix-inputs-D4_OLmm6.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/radix-layout-BqTpm3s4.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/data-viz-BuFFX-vG.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/query-management-DbWM5GrR.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/theme-utils-CNom64Sw.js"> + <link rel="modulepreload" crossorigin href="/ui/assets/form-libs-B6JBoFJD.js"> + <link rel="stylesheet" crossorigin href="/ui/assets/style-De_mcyPH.css"> +</head> + +<body> + <div id="root"></div> +</body> + +</html> diff --git a/pkg/dataobj/explorer/ui/index.html b/pkg/ui/frontend/index.html similarity index 87% rename from pkg/dataobj/explorer/ui/index.html rename to pkg/ui/frontend/index.html index f2fa33609beb3..fab4e5be42ebc 100644 --- a/pkg/dataobj/explorer/ui/index.html +++ b/pkg/ui/frontend/index.html @@ -4,7 +4,7 @@ <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>DataObj Explorer</title> + <title>Loki UI</title> </head> <body> diff --git a/pkg/ui/frontend/package-lock.json b/pkg/ui/frontend/package-lock.json new file mode 100644 index 0000000000000..b26bf58e31e46 --- /dev/null +++ b/pkg/ui/frontend/package-lock.json @@ -0,0 +1,6954 @@ +{ + "name": "@grafana/loki-ui", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@grafana/loki-ui", + "version": "0.0.0", + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@radix-ui/react-checkbox": "^1.1.3", + "@radix-ui/react-collapsible": "^1.1.2", + "@radix-ui/react-dialog": "^1.1.5", + "@radix-ui/react-dropdown-menu": "^2.1.5", + "@radix-ui/react-hover-card": "^1.1.5", + "@radix-ui/react-label": "^2.1.1", + "@radix-ui/react-popover": "^1.1.5", + "@radix-ui/react-progress": "^1.1.1", + "@radix-ui/react-scroll-area": "^1.2.2", + "@radix-ui/react-select": "^2.1.5", + "@radix-ui/react-separator": "^1.1.1", + "@radix-ui/react-slot": "^1.1.1", + "@radix-ui/react-switch": "^1.1.2", + "@radix-ui/react-tabs": "^1.1.2", + "@radix-ui/react-toast": "^1.2.5", + "@radix-ui/react-toggle": "^1.1.1", + "@radix-ui/react-toggle-group": "^1.1.1", + "@radix-ui/react-tooltip": "^1.1.7", + "@tanstack/react-query": "^5.66.0", + "@tanstack/react-query-devtools": "^5.66.0", + "@types/lodash": "^4.17.15", + "@types/react-datepicker": "^6.2.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cmdk": "^1.0.0", + "date-fns": "^3.3.1", + "lodash": "^4.17.21", + "lucide-react": "^0.474.0", + "next-themes": "^0.4.4", + "prism-react-renderer": "^2.4.1", + "react": "^18.2.0", + "react-code-block": "^1.1.1", + "react-datepicker": "^8.0.0", + "react-dom": "^18.2.0", + "react-hook-form": "^7.54.2", + "react-icons": "^5.4.0", + "react-router-dom": "^6.22.0", + "recharts": "^2.15.1", + "tailwind-merge": "^2.6.0", + "tailwindcss-animate": "^1.0.7", + "use-react-router-breadcrumbs": "^4.0.1", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^22.12.0", + "@types/react": "^18.2.0", + "@types/react-dom": "^18.2.0", + "@typescript-eslint/eslint-plugin": "^5.57.1", + "@typescript-eslint/parser": "^5.57.1", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.20", + "depcheck": "^1.4.7", + "eslint": "^8.38.0", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-react-refresh": "^0.4.5", + "postcss": "^8.5.1", + "tailwindcss": "^3.4.1", + "typescript": "^5.0.2", + "vite": "^5.1.0" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.26.2", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", + "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.5.tgz", + "integrity": "sha512-XvcZi1KWf88RVbF9wn8MN6tYFloU5qX8KjuF3E1PVBmJ9eypXfs4GRiJwLuTZL0iSnJUKn1BFPa5BPZZJyFzPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.7.tgz", + "integrity": "sha512-SRijHmF0PSPgLIBYlWnG0hyeJLwXE2CgpsXaMOrtt2yp9/86ALw6oUlj9KYuZ0JN07T4eBMVIW4li/9S1j2BGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.26.2", + "@babel/generator": "^7.26.5", + "@babel/helper-compilation-targets": "^7.26.5", + "@babel/helper-module-transforms": "^7.26.0", + "@babel/helpers": "^7.26.7", + "@babel/parser": "^7.26.7", + "@babel/template": "^7.25.9", + "@babel/traverse": "^7.26.7", + "@babel/types": "^7.26.7", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.5.tgz", + "integrity": "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.26.5", + "@babel/types": "^7.26.5", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.26.5.tgz", + "integrity": "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.26.5", + "@babel/helper-validator-option": "^7.25.9", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.25.9.tgz", + "integrity": "sha512-tnUA4RsrmflIM6W6RFTLFSXITtl0wKjgpnLgXyowocVPrbYrLUXSBXDgTs8BlbmIzIdlBySRQjINYs2BAkiLtw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.25.9", + "@babel/types": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.26.0.tgz", + "integrity": "sha512-xO+xu6B5K2czEnQye6BHA7DolFFmS3LB7stHZFaOLb1pAwO1HWLS8fXA+eh0A2yIvltPVmx3eNNDBJA2SLHXFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9", + "@babel/traverse": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.26.5", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.26.5.tgz", + "integrity": "sha512-RS+jZcRdZdRFzMyr+wcsaqOmld1/EqTghfaBGQQd/WnRdzdlvSZ//kF7U8VQTxf1ynZ4cjUcYgjVGx13ewNPMg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.25.9.tgz", + "integrity": "sha512-e/zv1co8pp55dNdEcCynfj9X7nyUKUXoUEwfXqaZt0omVOmDe9oOTdKStH4GmAw6zxMFs50ZayuMfHDKlO7Tfw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.7.tgz", + "integrity": "sha512-8NHiL98vsi0mbPQmYAGWwfcFaOy4j2HY49fXJCfuDcdE7fMIsH9a7GdaeXpIBsbT7307WU8KCMp5pUVDNL4f9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.25.9", + "@babel/types": "^7.26.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.7.tgz", + "integrity": "sha512-kEvgGGgEjRUutvdVvZhbn/BxVt+5VSpwXz1j3WYXQbXDo8KzFOPNG2GQbdAiNq8g6wn1yKk7C/qrke03a84V+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.26.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.25.9.tgz", + "integrity": "sha512-y8quW6p0WHkEhmErnfe58r7x0A70uKphQm8Sp8cV7tjNQwK56sNVK0M73LK3WuYmsuyrftut4xAkjjgU0twaMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.25.9.tgz", + "integrity": "sha512-+iqjT8xmXhhYv4/uiYd8FNQsraMFZIfxVSqxxVSZP0WbbSAWvBXAul0m/zu+7Vv4O/3WtApy9pmaTMiumEZgfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.7.tgz", + "integrity": "sha512-AOPI3D+a8dXnja+iwsUqGRjr1BbZIe771sXdapOtYI531gSqpi92vXivKcq2asu/DFpdl1ceFAKZyRzK2PCVcQ==", + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz", + "integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.25.9", + "@babel/parser": "^7.25.9", + "@babel/types": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.7.tgz", + "integrity": "sha512-1x1sgeyRLC3r5fQOM0/xtQKsYjyxmFjaOrLJNtZ81inNjyJHGIolTULPiSc/2qe1/qfpFLisLQYFnnZl7QoedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.26.2", + "@babel/generator": "^7.26.5", + "@babel/parser": "^7.26.7", + "@babel/template": "^7.25.9", + "@babel/types": "^7.26.7", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.26.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.7.tgz", + "integrity": "sha512-t8kDRGrKXyp6+tjUh7hw2RLyclsW4TRoRvRHtSyAX9Bb5ldlFh+90YAYY6awRXrlB4G5G2izNeGySpATlFzmOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", + "integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", + "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", + "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.6.9", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.9.tgz", + "integrity": "sha512-uMXCuQ3BItDUbAMhIXw7UPXRfAlOAvZzdK9BWpE60MCn+Svt3aLn9jsPTi/WNGlRUu2uI0v5S7JiIUsbsvh3fw==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.9" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.6.13", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.13.tgz", + "integrity": "sha512-umqzocjDgNRGTuO7Q8CU32dkHkECqI8ZdMZ5Swb6QAM0t5rnlrN3lGo1hdpscRd3WS8T6DKYK4ephgIH9iRh3w==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.6.0", + "@floating-ui/utils": "^0.2.9" + } + }, + "node_modules/@floating-ui/react": { + "version": "0.26.28", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.26.28.tgz", + "integrity": "sha512-yORQuuAtVpiRjpMhdc0wJj06b9JFjrYF4qp96j++v2NBpbi6SEGF7donUJ3TMieerQ6qVkAv1tgr7L4r5roTqw==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.1.2", + "@floating-ui/utils": "^0.2.8", + "tabbable": "^6.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz", + "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.9.tgz", + "integrity": "sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg==", + "license": "MIT" + }, + "node_modules/@hookform/resolvers": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz", + "integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.0.0" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", + "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", + "deprecated": "Use @eslint/config-array instead", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanwhocodes/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", + "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", + "deprecated": "Use @eslint/object-schema instead", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz", + "integrity": "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA==", + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@radix-ui/number": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.0.tgz", + "integrity": "sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==", + "license": "MIT" + }, + "node_modules/@radix-ui/primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.1.tgz", + "integrity": "sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.1.tgz", + "integrity": "sha512-NaVpZfmv8SKeZbn4ijN2V3jlHA9ngBG16VnIIm22nUR0Yk8KUALyBxT3KYEUnNuch9sTE8UTsS3whzBgKOL30w==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.1.3.tgz", + "integrity": "sha512-HD7/ocp8f1B3e6OHygH0n7ZKjONkhciy1Nh0yuBgObqThc3oyx+vuMfFHKAknXRHHWVE9XvXStxJFyjUmB8PIw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-use-size": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collapsible": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.2.tgz", + "integrity": "sha512-PliMB63vxz7vggcyq0IxNYk8vGDrLXVWw4+W4B8YnwI1s18x7YZYqlG9PLX7XxAJUi0g2DxP4XKJMFHh/iVh9A==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.1.tgz", + "integrity": "sha512-LwT3pSho9Dljg+wY2KN2mrrh6y3qELfftINERIzBUO9e0N+t0oMTyn3k9iv+ZqgrwGkRnLpNJrsMv9BZlt2yuA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.1.tgz", + "integrity": "sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz", + "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.5.tgz", + "integrity": "sha512-LaO3e5h/NOEL4OfXjxD43k9Dx+vn+8n+PCFt6uhX/BADFflllyv3WJG6rgvvSVBxpTch938Qq/LGc2MMxipXPw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.6.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz", + "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.4.tgz", + "integrity": "sha512-XDUI0IVYVSwjMXxM6P4Dfti7AH+Y4oS/TB+sglZ/EXc7cqLwGAmp1NlMrcUjj7ks6R5WTZuWKv44FBbLpwU3sA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-escape-keydown": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.5.tgz", + "integrity": "sha512-50ZmEFL1kOuLalPKHrLWvPFMons2fGx9TqQCWlPwDVpbAnaUJ1g4XNcKqFNMQymYU0kKWR4MDDi+9vUQBGFgcQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-menu": "2.1.5", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.1.tgz", + "integrity": "sha512-pSIwfrT1a6sIoDASCSpFwOasEwKTZWDw/iBdtnqKO7v6FeOzYJ7U53cPzYFVR3geGGXgVHaH+CdngrrAzqUGxg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.1.tgz", + "integrity": "sha512-01omzJAYRxXdG2/he/+xy+c8a8gCydoQ1yOxnWNcRhrrBW5W+RQJ22EK1SaO8tb3WoUsuEw7mJjBozPzihDFjA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-hover-card": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.5.tgz", + "integrity": "sha512-0jPlX3ZrUIhtMAY0m1SBn1koI4Yqsizq2UwdUiQF1GseSZLZBPa6b8tNS+m32K94Yb4wxtWFSQs85wujQvwahg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-popper": "1.2.1", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.0.tgz", + "integrity": "sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.1.tgz", + "integrity": "sha512-UUw5E4e/2+4kFMH7+YxORXGWggtY6sM8WIwh5RZchhLuUg2H1hc98Py+pr8HMz6rdaYrK2t296ZEjYLOCO5uUw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.5.tgz", + "integrity": "sha512-uH+3w5heoMJtqVCgYOtYVMECk1TOrkUn0OG0p5MqXC0W2ppcuVeESbou8PTHoqAjbdTEK19AGXBWcEtR5WpEQg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.1", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-roving-focus": "1.1.1", + "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.6.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.5.tgz", + "integrity": "sha512-YXkTAftOIW2Bt3qKH8vYr6n9gCkVrvyvfiTObVjoHVTHnNj26rmvO87IKa3VgtgCjb8FAQ6qOjNViwl+9iIzlg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.1", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.6.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.1.tgz", + "integrity": "sha512-3kn5Me69L+jv82EKRuQCXdYyf1DqHwD2U/sxoNgBGCB7K9TRc3bQamQ+5EPM9EvyPdli0W41sROd+ZU1dTCztw==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-rect": "1.1.0", + "@radix-ui/react-use-size": "1.1.0", + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.3.tgz", + "integrity": "sha512-NciRqhXnGojhT93RPyDaMPfLH3ZSl4jjIFbZQ1b/vxvZEdHsBZ49wP9w8L3HzUQwep01LcWtkUvm0OVB5JAHTw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.2.tgz", + "integrity": "sha512-18TFr80t5EVgL9x1SwF/YGtfG+l0BS0PRAlCWBDoBEiDQjeKgnNZRVJp/oVBl24sr3Gbfwc/Qpj4OcWTQMsAEg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.1.tgz", + "integrity": "sha512-sHCWTtxwNn3L3fH8qAfnF3WbUZycW93SM1j3NFDzXBiz8D6F5UTTy8G1+WFEaiCdvCVRJWj6N2R4Xq6HdiHmDg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-progress": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.1.1.tgz", + "integrity": "sha512-6diOawA84f/eMxFHcWut0aE1C2kyE9dOyCTQOMRR2C/qPiXz/X0SaiA/RLbapQaXUCmy0/hLMf9meSccD1N0pA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.1.tgz", + "integrity": "sha512-QE1RoxPGJ/Nm8Qmk0PxP8ojmoaS67i0s7hVssS7KuI2FQoc/uzVlZsqKfQvxPE6D8hICCPHJ4D88zNhT3OOmkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-scroll-area": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.2.tgz", + "integrity": "sha512-EFI1N/S3YxZEW/lJ/H1jY3njlvTd8tBmgKEn4GHi51+aMm94i6NmAJstsm5cu3yJwYqYc93gpCPm21FeAbFk6g==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.0", + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.1.5.tgz", + "integrity": "sha512-eVV7N8jBXAXnyrc+PsOF89O9AfVgGnbLxUtBb0clJ8y8ENMWLARGMI/1/SBRLz7u4HqxLgN71BJ17eono3wcjA==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.0", + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.1", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.1", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.6.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.1.tgz", + "integrity": "sha512-RRiNRSrD8iUiXriq/Y5n4/3iE8HzqgLHsusUSg5jVpU2+3tqcUFPJXHDymwEypunc2sWxDUS3UC+rkZRlHedsw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.1.tgz", + "integrity": "sha512-RApLLOcINYJA+dMVbOju7MYv1Mb2EBp2nH4HdDzXTSyaR5optlm6Otrz1euW3HbdOR8UmmFK06TD+A9frYWv+g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-switch": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.1.2.tgz", + "integrity": "sha512-zGukiWHjEdBCRyXvKR6iXAQG6qXm2esuAD6kDOi9Cn+1X6ev3ASo4+CsYaD6Fov9r/AQFekqnD/7+V0Cs6/98g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-use-size": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.2.tgz", + "integrity": "sha512-9u/tQJMcC2aGq7KXpGivMm1mgq7oRJKXphDwdypPd/j21j/2znamPU8WkXgnhUaTrSFNIt8XhOyCAupg8/GbwQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-roving-focus": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toast": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.5.tgz", + "integrity": "sha512-ZzUsAaOx8NdXZZKcFNDhbSlbsCUy8qQWmzTdgrlrhhZAOx2ofLtKrBDW9fkqhFvXgmtv560Uj16pkLkqML7SHA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.1.tgz", + "integrity": "sha512-i77tcgObYr743IonC1hrsnnPmszDRn8p+EGUsUt+5a/JFn28fxaM88Py6V2mc8J5kELMWishI0rLnuGLFD/nnQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle-group": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.1.tgz", + "integrity": "sha512-OgDLZEA30Ylyz8YSXvnGqIHtERqnUt1KUYTKdw/y8u7Ci6zGiJfXc02jahmcSNK3YcErqioj/9flWC9S1ihfwg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-roving-focus": "1.1.1", + "@radix-ui/react-toggle": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.1.7.tgz", + "integrity": "sha512-ss0s80BC0+g0+Zc53MvilcnTYSOi4mSuFWBPYPuTOFGjx+pUU+ZrmamMNwS56t8MTFlniA5ocjd4jYm/CdhbOg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.1", + "@radix-ui/react-portal": "1.1.3", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.0.tgz", + "integrity": "sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.1.0.tgz", + "integrity": "sha512-MtfMVJiSr2NjzS0Aa90NPTnvTSg6C/JLCV7ma0W6+OMV78vd8OyRpID+Ng9LxzsPbLeuBnWBA1Nq30AtBIDChw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz", + "integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.0.tgz", + "integrity": "sha512-+FPE0rOdziWSrH9athwI1R0HDVbWlEhd+FR+aSDk4uWGmSJ9Z54sdZVDQPZAinJhJXwfT+qnj969mCsT2gfm5w==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.0.tgz", + "integrity": "sha512-Z/e78qg2YFnnXcW88A4JmTtm4ADckLno6F7OXotmkQfeuCVaKuYzqAATPhVzl3delXE7CxIV8shofPn3jPc5Og==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.0.tgz", + "integrity": "sha512-0Fmkebhr6PiseyZlYAOtLS+nb7jLmpqTrJyv61Pe68MKYW6OWdRE2kI70TaYY27u7H0lajqM3hSMMLFq18Z7nQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.0.tgz", + "integrity": "sha512-XW3/vWuIXHa+2Uwcc2ABSfcCledmXhhQPlGbfcRXbiUQI5Icjcg19BGCZVKKInYbvUCut/ufbbLLPFC5cbb1hw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.1.1.tgz", + "integrity": "sha512-vVfA2IZ9q/J+gEamvj761Oq1FpWgCDaNOOIfbPVp2MVPLEomUr5+Vf7kJGwQ24YxZSlQVar7Bes8kyTo5Dshpg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.0.tgz", + "integrity": "sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==", + "license": "MIT" + }, + "node_modules/@remix-run/router": { + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.21.1.tgz", + "integrity": "sha512-KeBYSwohb8g4/wCcnksvKTYlg69O62sQeLynn2YE+5z7JWEj95if27kclW9QqbrlsQ2DINI8fjbV3zyuKfwjKg==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.32.1.tgz", + "integrity": "sha512-/pqA4DmqyCm8u5YIDzIdlLcEmuvxb0v8fZdFhVMszSpDTgbQKdw3/mB3eMUHIbubtJ6F9j+LtmyCnHTEqIHyzA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.32.1.tgz", + "integrity": "sha512-If3PDskT77q7zgqVqYuj7WG3WC08G1kwXGVFi9Jr8nY6eHucREHkfpX79c0ACAjLj3QIWKPJR7w4i+f5EdLH5Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.32.1.tgz", + "integrity": "sha512-zCpKHioQ9KgZToFp5Wvz6zaWbMzYQ2LJHQ+QixDKq52KKrF65ueu6Af4hLlLWHjX1Wf/0G5kSJM9PySW9IrvHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.32.1.tgz", + "integrity": "sha512-sFvF+t2+TyUo/ZQqUcifrJIgznx58oFZbdHS9TvHq3xhPVL9nOp+yZ6LKrO9GWTP+6DbFtoyLDbjTpR62Mbr3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.32.1.tgz", + "integrity": "sha512-NbOa+7InvMWRcY9RG+B6kKIMD/FsnQPH0MWUvDlQB1iXnF/UcKSudCXZtv4lW+C276g3w5AxPbfry5rSYvyeYA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.32.1.tgz", + "integrity": "sha512-JRBRmwvHPXR881j2xjry8HZ86wIPK2CcDw0EXchE1UgU0ubWp9nvlT7cZYKc6bkypBt745b4bglf3+xJ7hXWWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.32.1.tgz", + "integrity": "sha512-PKvszb+9o/vVdUzCCjL0sKHukEQV39tD3fepXxYrHE3sTKrRdCydI7uldRLbjLmDA3TFDmh418XH19NOsDRH8g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.32.1.tgz", + "integrity": "sha512-9WHEMV6Y89eL606ReYowXuGF1Yb2vwfKWKdD1A5h+OYnPZSJvxbEjxTRKPgi7tkP2DSnW0YLab1ooy+i/FQp/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.32.1.tgz", + "integrity": "sha512-tZWc9iEt5fGJ1CL2LRPw8OttkCBDs+D8D3oEM8mH8S1ICZCtFJhD7DZ3XMGM8kpqHvhGUTvNUYVDnmkj4BDXnw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.32.1.tgz", + "integrity": "sha512-FTYc2YoTWUsBz5GTTgGkRYYJ5NGJIi/rCY4oK/I8aKowx1ToXeoVVbIE4LGAjsauvlhjfl0MYacxClLld1VrOw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loongarch64-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.32.1.tgz", + "integrity": "sha512-F51qLdOtpS6P1zJVRzYM0v6MrBNypyPEN1GfMiz0gPu9jN8ScGaEFIZQwteSsGKg799oR5EaP7+B2jHgL+d+Kw==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.32.1.tgz", + "integrity": "sha512-wO0WkfSppfX4YFm5KhdCCpnpGbtgQNj/tgvYzrVYFKDpven8w2N6Gg5nB6w+wAMO3AIfSTWeTjfVe+uZ23zAlg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.32.1.tgz", + "integrity": "sha512-iWswS9cIXfJO1MFYtI/4jjlrGb/V58oMu4dYJIKnR5UIwbkzR0PJ09O0PDZT0oJ3LYWXBSWahNf/Mjo6i1E5/g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.32.1.tgz", + "integrity": "sha512-RKt8NI9tebzmEthMnfVgG3i/XeECkMPS+ibVZjZ6mNekpbbUmkNWuIN2yHsb/mBPyZke4nlI4YqIdFPgKuoyQQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.32.1.tgz", + "integrity": "sha512-WQFLZ9c42ECqEjwg/GHHsouij3pzLXkFdz0UxHa/0OM12LzvX7DzedlY0SIEly2v18YZLRhCRoHZDxbBSWoGYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.32.1.tgz", + "integrity": "sha512-BLoiyHDOWoS3uccNSADMza6V6vCNiphi94tQlVIL5de+r6r/CCQuNnerf+1g2mnk2b6edp5dk0nhdZ7aEjOBsA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.32.1.tgz", + "integrity": "sha512-w2l3UnlgYTNNU+Z6wOR8YdaioqfEnwPjIsJ66KxKAf0p+AuL2FHeTX6qvM+p/Ue3XPBVNyVSfCrfZiQh7vZHLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.32.1.tgz", + "integrity": "sha512-Am9H+TGLomPGkBnaPWie4F3x+yQ2rr4Bk2jpwy+iV+Gel9jLAu/KqT8k3X4jxFPW6Zf8OMnehyutsd+eHoq1WQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.32.1.tgz", + "integrity": "sha512-ar80GhdZb4DgmW3myIS9nRFYcpJRSME8iqWgzH2i44u+IdrzmiXVxeFnExQ5v4JYUSpg94bWjevMG8JHf1Da5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tanstack/query-core": { + "version": "5.66.0", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.66.0.tgz", + "integrity": "sha512-J+JeBtthiKxrpzUu7rfIPDzhscXF2p5zE/hVdrqkACBP8Yu0M96mwJ5m/8cPPYQE9aRNvXztXHlNwIh4FEeMZw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/query-devtools": { + "version": "5.65.0", + "resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.65.0.tgz", + "integrity": "sha512-g5y7zc07U9D3esMdqUfTEVu9kMHoIaVBsD0+M3LPdAdD710RpTcLiNvJY1JkYXqkq9+NV+CQoemVNpQPBXVsJg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.66.0", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.66.0.tgz", + "integrity": "sha512-z3sYixFQJe8hndFnXgWu7C79ctL+pI0KAelYyW+khaNJ1m22lWrhJU2QrsTcRKMuVPtoZvfBYrTStIdKo+x0Xw==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.66.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@tanstack/react-query-devtools": { + "version": "5.66.0", + "resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.66.0.tgz", + "integrity": "sha512-uB57wA2YZaQ2fPcFW0E9O1zAGDGSbRKRx84uMk/86VyU9jWVxvJ3Uzp+zNm+nZJYsuekCIo2opTdgNuvM3cKgA==", + "license": "MIT", + "dependencies": { + "@tanstack/query-devtools": "5.65.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@tanstack/react-query": "^5.66.0", + "react": "^18 || ^19" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.6.8", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", + "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.20.6", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", + "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.20.7" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz", + "integrity": "sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-P2dlU/q51fkOc/Gfl3Ul9kicV7l+ra934qBFXCFhrZMOL6du1TM0pm1ThYvENukyOn5h9v+yMJ9Fn5JK4QozrQ==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.8.tgz", + "integrity": "sha512-gkK1VVTr5iNiYJ7vWDI+yUFFlszhNMtVeneJ6lUTKPjprsvLLI9/tgEGiXJOnlINJA8FyA88gfnQsHbybVZrYQ==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz", + "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-w/P33JFeySuhN6JLkysYUK2gEmy9kHHFN7E8ro0tkfmlDOgxBDzWEZ/J8cWA+fHqFevpswDTFZnDx+R9lbL6xw==", + "license": "MIT" + }, + "node_modules/@types/minimatch": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.5.tgz", + "integrity": "sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.12.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.12.0.tgz", + "integrity": "sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.20.0" + } + }, + "node_modules/@types/parse-json": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", + "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/prismjs": { + "version": "1.26.5", + "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz", + "integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==", + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.14", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz", + "integrity": "sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ==", + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.18", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.18.tgz", + "integrity": "sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==", + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-datepicker": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/@types/react-datepicker/-/react-datepicker-6.2.0.tgz", + "integrity": "sha512-+JtO4Fm97WLkJTH8j8/v3Ldh7JCNRwjMYjRaKh4KHH0M3jJoXtwiD3JBCsdlg3tsFIw9eQSqyAPeVDN2H2oM9Q==", + "license": "MIT", + "dependencies": { + "@floating-ui/react": "^0.26.2", + "@types/react": "*", + "date-fns": "^3.3.1" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.5", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.5.tgz", + "integrity": "sha512-P4t6saawp+b/dFrUr2cvkVsfvPguwsxtH6dNIYRllMsefqFzkZk5UIjzyDOv5g1dXIPdG4Sp1yCR4Z6RCUsG/Q==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^18.0.0" + } + }, + "node_modules/@types/semver": { + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", + "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.4.0", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/type-utils": "5.62.0", + "@typescript-eslint/utils": "5.62.0", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "natural-compare-lite": "^1.4.0", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^5.0.0", + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", + "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/typescript-estree": "5.62.0", + "@typescript-eslint/utils": "5.62.0", + "debug": "^4.3.4", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/types": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", + "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@types/json-schema": "^7.0.9", + "@types/semver": "^7.3.12", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "eslint-scope": "^5.1.1", + "semver": "^7.3.7" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", + "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", + "dev": true, + "license": "ISC" + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.4.tgz", + "integrity": "sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.26.0", + "@babel/plugin-transform-react-jsx-self": "^7.25.9", + "@babel/plugin-transform-react-jsx-source": "^7.25.9", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.14.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.13.tgz", + "integrity": "sha512-oOdAkwqUfW1WqpwSYJce06wvt6HljgY3fGeM9NcVA1HaYOij3mZG9Rkysn0OHuyUAGMbEbARIpsG+LPVlBJ5/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.3", + "@vue/shared": "3.5.13", + "entities": "^4.5.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.0" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.13.tgz", + "integrity": "sha512-ZOJ46sMOKUjO3e94wPdCzQ6P1Lx/vhp2RSvfaab88Ajexs0AHeV0uasYhi99WPaogmBlRHNRuly8xV75cNTMDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.13", + "@vue/shared": "3.5.13" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.13.tgz", + "integrity": "sha512-6VdaljMpD82w6c2749Zhf5T9u5uLBWKnVue6XWxprDobftnletJ8+oel7sexFfM3qIxNmVE7LSFGTpv6obNyaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.3", + "@vue/compiler-core": "3.5.13", + "@vue/compiler-dom": "3.5.13", + "@vue/compiler-ssr": "3.5.13", + "@vue/shared": "3.5.13", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.11", + "postcss": "^8.4.48", + "source-map-js": "^1.2.0" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.13.tgz", + "integrity": "sha512-wMH6vrYHxQl/IybKJagqbquvxpWCuVYpoUJfCqFZwa/JY1GdATAQ+TgVtgrwwMZ0D07QhA99rs/EAAWfvG6KpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.13", + "@vue/shared": "3.5.13" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.13.tgz", + "integrity": "sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", + "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/aria-hidden": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.4.tgz", + "integrity": "sha512-y+CcFFwelSXpLZk/7fMB2mUbGtX9lKycf1MWJ7CaTIERyitVlyQx6C+sxcROU2BAJ24OiZyK+8wj2i8AlBoS3A==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/array-differ": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-3.0.0.tgz", + "integrity": "sha512-THtfYS6KtME/yIAhKjZ2ul7XI96lQGHRputJQHO80LAWQnuGP4iCIN8vdMRboGbIEYBwU33q8Tch1os2+X0kMg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/autoprefixer": { + "version": "10.4.20", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", + "integrity": "sha512-XY25y5xSv/wEoqzDyXXME4AFfkZI0P23z6Fs3YgymDnKJkCGOnkL0iTxCa85UTqaSgfcqyf3UA6+c7wUvx/16g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.3", + "caniuse-lite": "^1.0.30001646", + "fraction.js": "^4.3.7", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.24.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.4.tgz", + "integrity": "sha512-KDi1Ny1gSePi1vm0q4oxSF8b4DR44GF4BbmS2YdhPLOEqd8pDviZOGH/GsmRwoWJ2+5Lr085X7naowMwKHDG1A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001688", + "electron-to-chromium": "^1.5.73", + "node-releases": "^2.0.19", + "update-browserslist-db": "^1.1.1" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/callsite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", + "integrity": "sha512-0vdNRFXn5q+dtOqjfFtmtlI9N2eVZ7LMyEV2iKC5mEEFvSg/69Ml6b/WU2qF8W1nLRa0wiSrDT3Y5jOHZCwKPQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001696", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001696.tgz", + "integrity": "sha512-pDCPkvzfa39ehJtJ+OwGT/2yvT2SbjfHhiIW2LWOAcMQ7BzwxT/XuyUp4OTOd0XFWA6BKw0JalnBHgSi5DGJBQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cmdk": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.0.4.tgz", + "integrity": "sha512-AnsjfHyHpQ/EFeAnG216WY7A5LiYCoZzCSygiLvfXC3H3LFGCprErteUcszaVluGOhuOTbJS3jWHrSDYPBBygg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-dialog": "^1.1.2", + "@radix-ui/react-id": "^1.1.0", + "@radix-ui/react-primitive": "^2.0.0", + "use-sync-external-store": "^1.2.2" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "react-dom": "^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cosmiconfig": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cosmiconfig/node_modules/yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz", + "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/date-fns": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-3.6.0.tgz", + "integrity": "sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "license": "MIT" + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/depcheck": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/depcheck/-/depcheck-1.4.7.tgz", + "integrity": "sha512-1lklS/bV5chOxwNKA/2XUUk/hPORp8zihZsXflr8x0kLwmcZ9Y9BsS6Hs3ssvA+2wUVbG0U2Ciqvm1SokNjPkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.23.0", + "@babel/traverse": "^7.23.2", + "@vue/compiler-sfc": "^3.3.4", + "callsite": "^1.0.0", + "camelcase": "^6.3.0", + "cosmiconfig": "^7.1.0", + "debug": "^4.3.4", + "deps-regex": "^0.2.0", + "findup-sync": "^5.0.0", + "ignore": "^5.2.4", + "is-core-module": "^2.12.0", + "js-yaml": "^3.14.1", + "json5": "^2.2.3", + "lodash": "^4.17.21", + "minimatch": "^7.4.6", + "multimatch": "^5.0.0", + "please-upgrade-node": "^3.2.0", + "readdirp": "^3.6.0", + "require-package-name": "^2.0.1", + "resolve": "^1.22.3", + "resolve-from": "^5.0.0", + "semver": "^7.5.4", + "yargs": "^16.2.0" + }, + "bin": { + "depcheck": "bin/depcheck.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/depcheck/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/depcheck/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/depcheck/node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/depcheck/node_modules/minimatch": { + "version": "7.4.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-7.4.6.tgz", + "integrity": "sha512-sBz8G/YjVniEz6lKPNpKxXwazJe4c19fEfV2GDMX6AjFz+MX9uDWIZW8XreVhkFW3fkIdTv/gxWr/Kks5FFAVw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/depcheck/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/deps-regex": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/deps-regex/-/deps-regex-0.2.0.tgz", + "integrity": "sha512-PwuBojGMQAYbWkMXOY9Pd/NWCDNHVH12pnS7WHqZkTSeMESe4hwnKKRp0yR87g37113x4JPbo/oIvXY+s/f56Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "license": "Apache-2.0" + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "license": "MIT" + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.88", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.88.tgz", + "integrity": "sha512-K3C2qf1o+bGzbilTDCTBhTQcMS9KW60yTAaTeeXsfvQuTDDwlokLam/AdqlqcSy9u4UainDgsHV23ksXAOgamw==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", + "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.2.tgz", + "integrity": "sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.18.tgz", + "integrity": "sha512-IRGEoFn3OKalm3hjfolEWGqoF/jPqeEYFp+C8B0WMzwGwBMvlRDQd06kghDhF0C61uJ6WfSDhEZE/sAQjduKgw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": ">=8.40" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/eslint/node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esquery/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "homedir-polyfill": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-equals": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.2.2.tgz", + "integrity": "sha512-V7/RktU11J3I36Nwq2JnZEM7tNm17eBJz+u25qdxBZeCKiX6BkVSZQjwWIr+IobgnZy+ag73tTZgZi7tr0LrBw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.18.0.tgz", + "integrity": "sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/findup-sync": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-5.0.0.tgz", + "integrity": "sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.3", + "micromatch": "^4.0.4", + "resolve-dir": "^1.0.1" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/flat-cache": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.3", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flatted": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", + "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==", + "dev": true, + "license": "ISC" + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fraction.js": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", + "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse-passwd": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "0.474.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.474.0.tgz", + "integrity": "sha512-CmghgHkh0OJNmxGKWc0qfPJCYHASPMVSyGY8fj3xgk4v84ItqDg64JNKFZn5hC6E0vHi6gxnbCgwhyVB09wQtA==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.17", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", + "integrity": "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/multimatch": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-5.0.0.tgz", + "integrity": "sha512-ypMKuglUrZUD99Tk2bUQ+xNQj43lPEfAeX2o9cTteAmShXy2VHDJpuwu1o0xqoKCt9jLVAvwyFKdLTPXKAfJyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/minimatch": "^3.0.3", + "array-differ": "^3.0.0", + "array-union": "^2.1.0", + "arrify": "^2.0.1", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-compare-lite": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", + "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", + "dev": true, + "license": "MIT" + }, + "node_modules/next-themes": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.4.tgz", + "integrity": "sha512-LDQ2qIOJF0VnuVrrMSMLrWGjRMkq+0mpgl6e0juCLqdJ+oo8Q84JRWT6Wh11VDQKkMMe+dVzDKLWs5n87T+PkQ==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/node-releases": { + "version": "2.0.19", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", + "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/please-upgrade-node": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", + "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver-compare": "^1.0.0" + } + }, + "node_modules/postcss": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.1.tgz", + "integrity": "sha512-6oz2beyjc5VMn/KV1pPw8fliQkhBXrVn1Z3TVyqZxU8kZpzEKhBdmCFqI6ZbmGtamQvQGuU1sgPTk8ZrXDD7jQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.8", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", + "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", + "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prism-react-renderer": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/prism-react-renderer/-/prism-react-renderer-2.4.1.tgz", + "integrity": "sha512-ey8Ls/+Di31eqzUxC46h8MksNuGx/n0AAC8uKpwFau4RPDYLuE3EXTp8N8G2vX2N7UC/+IXeNUnlWBGGcAG+Ig==", + "license": "MIT", + "dependencies": { + "@types/prismjs": "^1.26.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.0.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/prop-types/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-code-block": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/react-code-block/-/react-code-block-1.1.1.tgz", + "integrity": "sha512-32FWIZe5YBN7if9VP4+R2IFOWCzko2/OBGoTZE3Wjn9G0W8kMhN2CvwXcCKjw6DCKLwtrVmoCQCywPAlV+P9pg==", + "license": "MIT", + "peerDependencies": { + "prism-react-renderer": "^2", + "react": "^18", + "react-dom": "^18" + } + }, + "node_modules/react-datepicker": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/react-datepicker/-/react-datepicker-8.0.0.tgz", + "integrity": "sha512-OmWkFx3BGPXQhBdhFCZyfqR6n2Z5T3WaEXQxz0tdTY6zNntklnIDkaDSYsbKwy7TcyBgeoneG5f4sCwmFPJ4eA==", + "license": "MIT", + "dependencies": { + "@floating-ui/react": "^0.27.3", + "clsx": "^2.1.1", + "date-fns": "^4.1.0" + }, + "peerDependencies": { + "react": "^16.9.0 || ^17 || ^18 || ^19 || ^19.0.0-rc", + "react-dom": "^16.9.0 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/react-datepicker/node_modules/@floating-ui/react": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.3.tgz", + "integrity": "sha512-CLHnes3ixIFFKVQDdICjel8muhFLOBdQH7fgtHNPY8UbCNqbeKZ262G7K66lGQOUQWWnYocf7ZbUsLJgGfsLHg==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.1.2", + "@floating-ui/utils": "^0.2.9", + "tabbable": "^6.0.0" + }, + "peerDependencies": { + "react": ">=17.0.0", + "react-dom": ">=17.0.0" + } + }, + "node_modules/react-datepicker/node_modules/date-fns": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", + "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-hook-form": { + "version": "7.54.2", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.54.2.tgz", + "integrity": "sha512-eHpAUgUjWbZocoQYUHposymRb4ZP6d0uwUnooL2uOybA9/3tPUvoAKqEWK1WaSiTxxOfTpffNZP7QwlnM3/gEg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/react-hook-form" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19" + } + }, + "node_modules/react-icons": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.4.0.tgz", + "integrity": "sha512-7eltJxgVt7X64oHh6wSWNwwbKTCtMfK35hcjvJS0yxEAhPM8oUKdS3+kqaW1vicIltw+kR2unHaa12S9pPALoQ==", + "license": "MIT", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, + "node_modules/react-refresh": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", + "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-remove-scroll": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.6.3.tgz", + "integrity": "sha512-pnAi91oOk8g8ABQKGF5/M9qxmmOPxaAnopyTHYfqYEwJhyFrbbBtHuSgtKEoH0jpcxx5o3hXqH1mNd9/Oi+8iQ==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.7", + "react-style-singleton": "^2.2.3", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.3", + "use-sidecar": "^1.1.3" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-router": { + "version": "6.28.2", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.28.2.tgz", + "integrity": "sha512-BgFY7+wEGVjHCiqaj2XiUBQ1kkzfg6UoKYwEe0wv+FF+HNPCxtS/MVPvLAPH++EsuCMReZl9RYVGqcHLk5ms3A==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.28.2", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.28.2.tgz", + "integrity": "sha512-O81EWqNJWqvlN/a7eTudAdQm0TbI7hw+WIi7OwwMcTn5JMyZ0ibTFNGz+t+Lju0df4LcqowCegcrK22lB1q9Kw==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.1", + "react-router": "6.28.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/react-smooth": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz", + "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==", + "license": "MIT", + "dependencies": { + "fast-equals": "^5.0.1", + "prop-types": "^15.8.1", + "react-transition-group": "^4.4.5" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/recharts": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.1.tgz", + "integrity": "sha512-v8PUTUlyiDe56qUj82w/EDVuzEFXwEHp9/xOowGAZwfLjB9uAy3GllQVIYMWF6nU+qibx85WF75zD7AjqoT54Q==", + "license": "MIT", + "dependencies": { + "clsx": "^2.0.0", + "eventemitter3": "^4.0.1", + "lodash": "^4.17.21", + "react-is": "^18.3.1", + "react-smooth": "^4.0.4", + "recharts-scale": "^0.4.4", + "tiny-invariant": "^1.3.1", + "victory-vendor": "^36.6.8" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/recharts-scale": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz", + "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==", + "license": "MIT", + "dependencies": { + "decimal.js-light": "^2.4.1" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==", + "license": "MIT" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-package-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/require-package-name/-/require-package-name-2.0.1.tgz", + "integrity": "sha512-uuoJ1hU/k6M0779t3VMVIYpb2VMJk05cehCaABFhXaibcbvfgR8wKiozLjVFSzJPmQMRqIcO0HMyTFqfV09V6Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.10", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", + "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rollup": { + "version": "4.32.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.32.1.tgz", + "integrity": "sha512-z+aeEsOeEa3mEbS1Tjl6sAZ8NE3+AalQz1RJGj81M+fizusbdDMoEJwdJNHfaB40Scr4qNu+welOfes7maKonA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.6" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.32.1", + "@rollup/rollup-android-arm64": "4.32.1", + "@rollup/rollup-darwin-arm64": "4.32.1", + "@rollup/rollup-darwin-x64": "4.32.1", + "@rollup/rollup-freebsd-arm64": "4.32.1", + "@rollup/rollup-freebsd-x64": "4.32.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.32.1", + "@rollup/rollup-linux-arm-musleabihf": "4.32.1", + "@rollup/rollup-linux-arm64-gnu": "4.32.1", + "@rollup/rollup-linux-arm64-musl": "4.32.1", + "@rollup/rollup-linux-loongarch64-gnu": "4.32.1", + "@rollup/rollup-linux-powerpc64le-gnu": "4.32.1", + "@rollup/rollup-linux-riscv64-gnu": "4.32.1", + "@rollup/rollup-linux-s390x-gnu": "4.32.1", + "@rollup/rollup-linux-x64-gnu": "4.32.1", + "@rollup/rollup-linux-x64-musl": "4.32.1", + "@rollup/rollup-win32-arm64-msvc": "4.32.1", + "@rollup/rollup-win32-ia32-msvc": "4.32.1", + "@rollup/rollup-win32-x64-msvc": "4.32.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.0.tgz", + "integrity": "sha512-DrfFnPzblFmNrIZzg5RzHegbiRWg7KMR7btwi2yjHwx06zsUbO5g613sVwEV7FTwmzJu+Io0lJe2GJ3LxqpvBQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "dev": true, + "license": "MIT" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sucrase": { + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", + "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "glob": "^10.3.10", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/sucrase/node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sucrase/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tabbable": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.2.0.tgz", + "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==", + "license": "MIT" + }, + "node_modules/tailwind-merge": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz", + "integrity": "sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", + "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.6", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss-animate": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/tailwindcss-animate/-/tailwindcss-animate-1.0.7.tgz", + "integrity": "sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==", + "license": "MIT", + "peerDependencies": { + "tailwindcss": ">=3.0.0 || insiders" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true, + "license": "MIT" + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsutils": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", + "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^1.8.1" + }, + "engines": { + "node": ">= 6" + }, + "peerDependencies": { + "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" + } + }, + "node_modules/tsutils/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true, + "license": "0BSD" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.2.tgz", + "integrity": "sha512-PPypAm5qvlD7XMZC3BujecnaOxwhrtoFR+Dqkk5Aa/6DssiH0ibKoketaj9w8LP7Bont1rYeoV5plxD7RTEPRg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-react-router-breadcrumbs": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/use-react-router-breadcrumbs/-/use-react-router-breadcrumbs-4.0.1.tgz", + "integrity": "sha512-Zbcy0KvWt1JePFcUHJAnTr7Z+AeO9WxmPs6A5Q/xqOVoi8edPKzpqHF87WB2opXwie/QjCxrEyTB7kFg7fgXvQ==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.8", + "react-router-dom": ">=6.0.0" + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sync-external-store": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.4.0.tgz", + "integrity": "sha512-9WXSPC5fMv61vaupRkCKCxsPxBocVnwakBEkMIHHpkTTg6icbJtg6jzgtLDm4bl3cSHAca52rYWih0k4K3PfHw==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/victory-vendor": { + "version": "36.9.2", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz", + "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, + "node_modules/vite": { + "version": "5.4.14", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.14.tgz", + "integrity": "sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.0.tgz", + "integrity": "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz", + "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/pkg/ui/frontend/package.json b/pkg/ui/frontend/package.json new file mode 100644 index 0000000000000..bbee7737429c9 --- /dev/null +++ b/pkg/ui/frontend/package.json @@ -0,0 +1,74 @@ +{ + "name": "@grafana/loki-ui", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "lint": "eslint src --ext ts,tsx --report-unused-disable-directives", + "preview": "vite preview" + }, + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@radix-ui/react-checkbox": "^1.1.3", + "@radix-ui/react-collapsible": "^1.1.2", + "@radix-ui/react-dialog": "^1.1.5", + "@radix-ui/react-dropdown-menu": "^2.1.5", + "@radix-ui/react-hover-card": "^1.1.5", + "@radix-ui/react-label": "^2.1.1", + "@radix-ui/react-popover": "^1.1.5", + "@radix-ui/react-progress": "^1.1.1", + "@radix-ui/react-scroll-area": "^1.2.2", + "@radix-ui/react-select": "^2.1.5", + "@radix-ui/react-separator": "^1.1.1", + "@radix-ui/react-slot": "^1.1.1", + "@radix-ui/react-switch": "^1.1.2", + "@radix-ui/react-tabs": "^1.1.2", + "@radix-ui/react-toast": "^1.2.5", + "@radix-ui/react-toggle": "^1.1.1", + "@radix-ui/react-toggle-group": "^1.1.1", + "@radix-ui/react-tooltip": "^1.1.7", + "@tanstack/react-query": "^5.66.0", + "@tanstack/react-query-devtools": "^5.66.0", + "@types/lodash": "^4.17.15", + "@types/react-datepicker": "^6.2.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cmdk": "^1.0.0", + "date-fns": "^3.3.1", + "lodash": "^4.17.21", + "lucide-react": "^0.474.0", + "next-themes": "^0.4.4", + "prism-react-renderer": "^2.4.1", + "react": "^18.2.0", + "react-code-block": "^1.1.1", + "react-datepicker": "^8.0.0", + "react-dom": "^18.2.0", + "react-hook-form": "^7.54.2", + "react-icons": "^5.4.0", + "react-router-dom": "^6.22.0", + "recharts": "^2.15.1", + "tailwind-merge": "^2.6.0", + "tailwindcss-animate": "^1.0.7", + "use-react-router-breadcrumbs": "^4.0.1", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^22.12.0", + "@types/react": "^18.2.0", + "@types/react-dom": "^18.2.0", + "@typescript-eslint/eslint-plugin": "^5.57.1", + "@typescript-eslint/parser": "^5.57.1", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.20", + "depcheck": "^1.4.7", + "eslint": "^8.38.0", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-react-refresh": "^0.4.5", + "postcss": "^8.5.1", + "tailwindcss": "^3.4.1", + "typescript": "^5.0.2", + "vite": "^5.1.0" + } +} diff --git a/pkg/dataobj/explorer/ui/postcss.config.js b/pkg/ui/frontend/postcss.config.js similarity index 96% rename from pkg/dataobj/explorer/ui/postcss.config.js rename to pkg/ui/frontend/postcss.config.js index 2e7af2b7f1a6f..2aa7205d4b402 100644 --- a/pkg/dataobj/explorer/ui/postcss.config.js +++ b/pkg/ui/frontend/postcss.config.js @@ -3,4 +3,4 @@ export default { tailwindcss: {}, autoprefixer: {}, }, -} +}; diff --git a/pkg/ui/frontend/src/App.tsx b/pkg/ui/frontend/src/App.tsx new file mode 100644 index 0000000000000..9b2551acbe0d5 --- /dev/null +++ b/pkg/ui/frontend/src/App.tsx @@ -0,0 +1,28 @@ +import { Routes, Route } from "react-router-dom"; +import { AppLayout } from "./layout/layout"; +import { ThemeProvider } from "./features/theme/components/theme-provider"; +import { QueryProvider } from "./providers/query-provider"; +import { ClusterProvider } from "./contexts/cluster-provider"; +import { routes } from "./config/routes"; + +export default function App() { + return ( + <QueryProvider> + <ThemeProvider defaultTheme="dark" storageKey="loki-ui-theme"> + <ClusterProvider> + <AppLayout> + <Routes> + {routes.map((route) => ( + <Route + key={route.path} + path={route.path} + element={route.element} + /> + ))} + </Routes> + </AppLayout> + </ClusterProvider> + </ThemeProvider> + </QueryProvider> + ); +} diff --git a/pkg/dataobj/explorer/ui/src/components/file-metadata/CompressionRatio.tsx b/pkg/ui/frontend/src/components/common/compression-ratio.tsx similarity index 100% rename from pkg/dataobj/explorer/ui/src/components/file-metadata/CompressionRatio.tsx rename to pkg/ui/frontend/src/components/common/compression-ratio.tsx diff --git a/pkg/ui/frontend/src/components/common/copy-button.tsx b/pkg/ui/frontend/src/components/common/copy-button.tsx new file mode 100644 index 0000000000000..4fdfd646302f6 --- /dev/null +++ b/pkg/ui/frontend/src/components/common/copy-button.tsx @@ -0,0 +1,43 @@ +import { Button } from "@/components/ui/button"; +import { Copy, Check } from "lucide-react"; +import { useState } from "react"; +import { cn } from "@/lib/utils"; + +interface CopyButtonProps { + text: string; + className?: string; + onCopy?: () => void; +} + +export function CopyButton({ text, className, onCopy }: CopyButtonProps) { + const [hasCopied, setHasCopied] = useState(false); + + const copyToClipboard = () => { + navigator.clipboard.writeText(text).then(() => { + setHasCopied(true); + onCopy?.(); + setTimeout(() => setHasCopied(false), 2000); + }); + }; + + return ( + <Button + variant="ghost" + size="sm" + onClick={copyToClipboard} + className={cn("h-8 px-2", className)} + > + {hasCopied ? ( + <> + <Check className="h-4 w-4 mr-1" /> + Copied + </> + ) : ( + <> + <Copy className="h-4 w-4 mr-1" /> + Copy + </> + )} + </Button> + ); +} diff --git a/pkg/ui/frontend/src/components/common/data-table-column-header.tsx b/pkg/ui/frontend/src/components/common/data-table-column-header.tsx new file mode 100644 index 0000000000000..de2b1b5c2ffcd --- /dev/null +++ b/pkg/ui/frontend/src/components/common/data-table-column-header.tsx @@ -0,0 +1,83 @@ +import { ChevronsUpDown, ArrowDown, ArrowUp } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "../ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "../ui/dropdown-menu"; + +interface DataTableColumnHeaderProps<TField extends string> { + title: string; + field: TField; + sortField: string; + sortDirection: "asc" | "desc"; + onSort: (field: TField) => void; +} + +export function DataTableColumnHeader<TField extends string>({ + title, + field, + sortField, + sortDirection, + onSort, +}: DataTableColumnHeaderProps<TField>) { + const isCurrentSort = sortField === field; + + const handleSort = (direction: "asc" | "desc") => { + if (sortField === field && sortDirection === direction) { + return; + } + onSort(field); + }; + + return ( + <div className="flex items-center space-x-2"> + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + variant="ghost" + size="sm" + className="-ml-3 h-8 hover:bg-muted/50 data-[state=open]:bg-muted/50" + > + <div className="flex items-center"> + <span>{title}</span> + {isCurrentSort ? ( + sortDirection === "desc" ? ( + <ArrowDown className="ml-2 h-4 w-4" /> + ) : ( + <ArrowUp className="ml-2 h-4 w-4" /> + ) + ) : ( + <ChevronsUpDown className="ml-2 h-4 w-4" /> + )} + </div> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="start"> + <DropdownMenuItem + onClick={() => handleSort("asc")} + className={cn( + "cursor-pointer", + isCurrentSort && sortDirection === "asc" && "bg-accent" + )} + > + <ArrowUp className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" /> + Asc + </DropdownMenuItem> + <DropdownMenuItem + onClick={() => handleSort("desc")} + className={cn( + "cursor-pointer", + isCurrentSort && sortDirection === "desc" && "bg-accent" + )} + > + <ArrowDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" /> + Desc + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/common/date-hover.tsx b/pkg/ui/frontend/src/components/common/date-hover.tsx new file mode 100644 index 0000000000000..297c54a8a29d6 --- /dev/null +++ b/pkg/ui/frontend/src/components/common/date-hover.tsx @@ -0,0 +1,47 @@ +import React from "react"; +import { formatDistanceToNow, format } from "date-fns"; +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; +interface DateHoverProps { + date: Date; + className?: string; +} + +export const DateHover: React.FC<DateHoverProps> = ({ + date, + className = "", +}) => { + const relativeTime = formatDistanceToNow(date, { addSuffix: true }); + const localTime = format(date, "yyyy-MM-dd HH:mm:ss"); + const utcTime = format( + new Date(date.getTime() + date.getTimezoneOffset() * 60000), + "yyyy-MM-dd HH:mm:ss" + ); + + return ( + <HoverCard> + <HoverCardTrigger> + <div className={`inline-block ${className}`}>{relativeTime}</div> + </HoverCardTrigger> + <HoverCardContent className="w-[280px]"> + <div className="space-y-2"> + <div className="flex items-center gap-3"> + <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> + UTC + </span> + <span className="font-mono">{utcTime}</span> + </div> + <div className="flex items-center gap-3"> + <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> + Local + </span> + <span className="font-mono">{localTime}</span> + </div> + </div> + </HoverCardContent> + </HoverCard> + ); +}; diff --git a/pkg/ui/frontend/src/components/common/index.ts b/pkg/ui/frontend/src/components/common/index.ts new file mode 100644 index 0000000000000..fdf5faa0e3a11 --- /dev/null +++ b/pkg/ui/frontend/src/components/common/index.ts @@ -0,0 +1 @@ +export * from "./multi-select"; diff --git a/pkg/ui/frontend/src/components/common/multi-select.tsx b/pkg/ui/frontend/src/components/common/multi-select.tsx new file mode 100644 index 0000000000000..ca2600d96a209 --- /dev/null +++ b/pkg/ui/frontend/src/components/common/multi-select.tsx @@ -0,0 +1,110 @@ +// src/components/multi-select.tsx + +import * as React from "react"; +import { ChevronsUpDown } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, +} from "@/components/ui/command"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { Checkbox } from "@/components/ui/checkbox"; + +export interface Option { + value: string; + label: string; +} + +interface MultiSelectProps { + options: Option[]; + selected: string[]; + onChange: (values: string[]) => void; + placeholder?: string; + emptyMessage?: string; + className?: string; +} + +export function MultiSelect({ + options = [], + selected = [], + onChange, + placeholder = "Select options...", + emptyMessage = "No options found.", + className, +}: MultiSelectProps) { + const [open, setOpen] = React.useState(false); + + const handleSelect = (value: string) => { + const newSelected = selected.includes(value) + ? selected.filter((item) => item !== value) + : [...selected, value]; + onChange(newSelected); + }; + + const handleSelectAll = () => { + if (selected.length === options.length) { + onChange([]); + } else { + onChange(options.map((option) => option.value)); + } + }; + + const selectedCount = selected.length; + const totalOptions = options.length; + + return ( + <Popover open={open} onOpenChange={setOpen}> + <PopoverTrigger asChild> + <Button + variant="outline" + role="combobox" + aria-expanded={open} + className={cn("justify-between", className)} + > + {selectedCount === 0 ? placeholder : `${selectedCount} selected`} + <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> + </Button> + </PopoverTrigger> + <PopoverContent className="w-[200px] p-0"> + <Command> + <CommandInput placeholder={placeholder} /> + <CommandEmpty>{emptyMessage}</CommandEmpty> + <CommandGroup> + {totalOptions > 0 && ( + <CommandItem onSelect={handleSelectAll}> + <div className="flex items-center space-x-2"> + <Checkbox + checked={ + selectedCount > 0 && selectedCount === totalOptions + } + aria-label="Select all" + /> + <span>Select all</span> + </div> + </CommandItem> + )} + {options.map((option) => ( + <CommandItem + key={option.value} + onSelect={() => handleSelect(option.value)} + > + <div className="flex items-center space-x-2"> + <Checkbox checked={selected.includes(option.value)} /> + <span>{option.label}</span> + </div> + </CommandItem> + ))} + </CommandGroup> + </Command> + </PopoverContent> + </Popover> + ); +} diff --git a/pkg/ui/frontend/src/components/common/refresh-loop.tsx b/pkg/ui/frontend/src/components/common/refresh-loop.tsx new file mode 100644 index 0000000000000..fab017a779acf --- /dev/null +++ b/pkg/ui/frontend/src/components/common/refresh-loop.tsx @@ -0,0 +1,66 @@ +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Loader2, Pause } from "lucide-react"; + +interface RefreshLoopProps { + onRefresh: () => void; + isPaused?: boolean; + isLoading: boolean; + className?: string; +} + +export function RefreshLoop({ + onRefresh, + isPaused = false, + isLoading, + className, +}: RefreshLoopProps) { + const [delayedLoading, setDelayedLoading] = useState(isLoading); + + useEffect(() => { + let timeoutId: NodeJS.Timeout; + if (isLoading) { + setDelayedLoading(true); + } else { + timeoutId = setTimeout(() => { + setDelayedLoading(false); + }, 1000); // Keep loading state for 1 second after isLoading becomes false + } + return () => { + if (timeoutId) clearTimeout(timeoutId); + }; + }, [isLoading]); + + return ( + <div + className={`flex items-center gap-2 text-sm text-muted-foreground ${className}`} + > + <Button + variant="secondary" + size="sm" + className="h-6 px-2 text-xs hover:bg-muted" + onClick={onRefresh} + > + Refresh now + </Button> + {isPaused ? ( + <Pause className="h-3 w-3 text-orange-500" /> + ) : ( + <Loader2 + className={`h-3 w-3 ${ + delayedLoading + ? "animate-spin text-emerald-500 " + : "opacity-0 transition-opacity duration-1000" + } `} + /> + )} + <span className="transition-opacity duration-1000"> + {isPaused + ? "Auto-refresh paused" + : delayedLoading + ? "Refreshing..." + : ``} + </span> + </div> + ); +} diff --git a/pkg/dataobj/explorer/ui/src/components/layout/Breadcrumb.tsx b/pkg/ui/frontend/src/components/explorer/breadcrumb.tsx similarity index 59% rename from pkg/dataobj/explorer/ui/src/components/layout/Breadcrumb.tsx rename to pkg/ui/frontend/src/components/explorer/breadcrumb.tsx index 076b806f17353..000e707dfd3b6 100644 --- a/pkg/dataobj/explorer/ui/src/components/layout/Breadcrumb.tsx +++ b/pkg/ui/frontend/src/components/explorer/breadcrumb.tsx @@ -1,11 +1,15 @@ -import React from "react"; +import { useSearchParams } from "react-router-dom"; +import React, { useMemo } from "react"; +import { findNodeName } from "@/lib/utils"; +import { useCluster } from "@/contexts/use-cluster"; +import { + BreadcrumbList, + BreadcrumbItem, + BreadcrumbLink, + Breadcrumb, + BreadcrumbSeparator, +} from "@/components/ui/breadcrumb"; import { Link } from "react-router-dom"; -import { useBasename } from "../../contexts/BasenameContext"; - -interface BreadcrumbProps { - parts: string[]; - isLastPartClickable?: boolean; -} const getProviderStyles = ( provider: string @@ -91,29 +95,36 @@ const getProviderStyles = ( } }; -export const Breadcrumb: React.FC<BreadcrumbProps> = ({ - parts, - isLastPartClickable = false, -}) => { +export function ExplorerBreadcrumb() { const [provider, setProvider] = React.useState<string>(""); - const basename = useBasename(); + // const basename = useBasename(); // TODO: use basename + const { cluster } = useCluster(); + + const nodeName = useMemo(() => { + return findNodeName(cluster?.members, "dataobj-explorer"); + }, [cluster?.members]); React.useEffect(() => { - fetch(`${basename}api/provider`) - .then((res) => res.json()) - .then((data) => setProvider(data.provider)) - .catch(console.error); - }, [basename]); + if (nodeName) { + fetch(`/ui/api/v1/proxy/${nodeName}/dataobj/api/v1/provider`) + .then((res) => res.json()) + .then((data) => setProvider(data.provider)) + .catch(console.error); + } + }, [nodeName]); + const [searchParams] = useSearchParams(); + const path = searchParams.get("path") || ""; + const segments = path.split("/").filter(Boolean); const providerStyles = getProviderStyles(provider); return ( - <nav className="flex mb-4" aria-label="Breadcrumb"> - <ol className="inline-flex items-center space-x-1 md:space-x-3"> - <li className="inline-flex items-center"> - {provider && ( + <Breadcrumb> + <BreadcrumbList> + <BreadcrumbItem> + <BreadcrumbLink asChild> <Link - to="/" - className={`inline-flex items-center h-7 gap-2 px-3 py-1 text-xs font-medium ${providerStyles.bg} ${providerStyles.text} ${providerStyles.darkBg} ${providerStyles.darkText} rounded-full hover:ring-2 hover:ring-gray-300 dark:hover:ring-gray-600 transition-all duration-200`} + to="/storage/dataobj" + className={`inline-flex items-center h-7 gap-2 px-3 py-1 text-xs font-medium ${providerStyles.bg} ${providerStyles.text} ${providerStyles.darkBg} ${providerStyles.darkText} rounded-full hover:ring-1 hover:ring-gray-300 dark:hover:ring-gray-600 transition-all duration-200`} > <svg xmlns="http://www.w3.org/2000/svg" @@ -123,46 +134,36 @@ export const Breadcrumb: React.FC<BreadcrumbProps> = ({ > <path d="M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z" /> </svg> - {provider} + {provider || ""} </Link> - )} - </li> - {parts.map((part, index, array) => ( - <li key={index}> - <div className="flex items-center"> - <svg - className="w-3 h-3 text-gray-400 mx-1" - aria-hidden="true" - xmlns="http://www.w3.org/2000/svg" - fill="none" - viewBox="0 0 6 10" - > - <path - stroke="currentColor" - strokeLinecap="round" - strokeLinejoin="round" - strokeWidth="2" - d="m1 9 4-4-4-4" - /> - </svg> - {!isLastPartClickable && index === array.length - 1 ? ( - <span className="ml-1 text-sm font-medium text-gray-500 md:ml-2"> - {part} - </span> - ) : ( - <Link - to={`/?path=${encodeURIComponent( - array.slice(0, index + 1).join("/") - )}`} - className="ml-1 text-sm font-medium text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 md:ml-2" - > - {part} - </Link> - )} - </div> - </li> - ))} - </ol> - </nav> + </BreadcrumbLink> + </BreadcrumbItem> + {segments.length > 0 && <BreadcrumbSeparator />} + {segments.map((segment, index) => { + const currentPath = segments.slice(0, index + 1).join("/"); + const isLastItem = index === segments.length - 1; + return ( + <React.Fragment key={currentPath}> + <BreadcrumbItem> + <BreadcrumbLink asChild> + {isLastItem ? ( + <span className="text-gray-500">{segment}</span> + ) : ( + <Link + to={`/storage/dataobj?path=${encodeURIComponent( + currentPath + )}`} + > + {segment} + </Link> + )} + </BreadcrumbLink> + </BreadcrumbItem> + {index < segments.length - 1 && <BreadcrumbSeparator />} + </React.Fragment> + ); + })} + </BreadcrumbList> + </Breadcrumb> ); -}; +} diff --git a/pkg/ui/frontend/src/components/explorer/file-list.tsx b/pkg/ui/frontend/src/components/explorer/file-list.tsx new file mode 100644 index 0000000000000..243efaef296c0 --- /dev/null +++ b/pkg/ui/frontend/src/components/explorer/file-list.tsx @@ -0,0 +1,144 @@ +import { useNavigate, useSearchParams, Link } from "react-router-dom"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { FolderIcon, FileIcon, DownloadIcon } from "lucide-react"; +import { ExplorerFile } from "@/types/explorer"; +import { formatBytes } from "@/lib/utils"; +import { DateHover } from "../common/date-hover"; +import { Button } from "../ui/button"; + +interface FileListProps { + current: string; + parent: string | null; + files: ExplorerFile[]; + folders: string[]; +} + +export function FileList({ current, parent, files, folders }: FileListProps) { + const navigate = useNavigate(); + const [, setSearchParams] = useSearchParams(); + + const handleNavigate = (path: string) => { + setSearchParams({ path }); + }; + + const handleFileClick = (file: ExplorerFile) => { + navigate( + `/storage/dataobj/metadata?path=${encodeURIComponent( + current + "/" + file.name + )}` + ); + }; + + return ( + <div className="space-y-4"> + <Table> + <TableHeader> + <TableRow className="h-12"> + <TableHead>Name</TableHead> + <TableHead>Modified</TableHead> + <TableHead>Size</TableHead> + <TableHead></TableHead> + </TableRow> + </TableHeader> + <TableBody> + {parent !== current && ( + <TableRow + key="parent" + className="h-12 cursor-pointer hover:bg-muted/50" + onClick={() => handleNavigate(parent || "")} + > + <TableCell className="font-medium"> + <div className="flex items-center"> + <svg + className="w-5 h-5 mr-2" + fill="none" + stroke="currentColor" + viewBox="0 0 24 24" + > + <path + strokeLinecap="round" + strokeLinejoin="round" + strokeWidth="2" + d="M15 19l-7-7 7-7" + /> + </svg> + .. + </div> + </TableCell> + <TableCell>-</TableCell> + <TableCell>-</TableCell> + <TableCell></TableCell> + </TableRow> + )} + {folders.map((folder) => ( + <TableRow + key={folder} + className="h-12 cursor-pointer hover:bg-muted/50" + onClick={() => + handleNavigate(current ? `${current}/${folder}` : folder) + } + > + <TableCell className="font-medium"> + <div className="flex items-center"> + <FolderIcon className="mr-2 h-4 w-4" /> + {folder} + </div> + </TableCell> + <TableCell>-</TableCell> + <TableCell>-</TableCell> + <TableCell></TableCell> + </TableRow> + ))} + + {files.map((file) => ( + <TableRow + key={file.name} + className="h-12 cursor-pointer hover:bg-muted/50" + onClick={(e) => { + if ((e.target as HTMLElement).closest("a[download]")) { + return; + } + handleFileClick(file); + }} + > + <TableCell className="font-medium"> + <div className="flex items-center"> + <FileIcon className="mr-2 h-4 w-4" /> + {file.name} + </div> + </TableCell> + <TableCell> + <DateHover date={new Date(file.lastModified)} /> + </TableCell> + <TableCell>{formatBytes(file.size)}</TableCell> + <TableCell> + <Button + variant="outline" + size="icon" + asChild + className="h-8 w-8" + > + <Link + to={file.downloadUrl} + target="_blank" + download + onClick={(e) => e.stopPropagation()} + > + <DownloadIcon className="h-4 w-4" /> + </Link> + </Button> + </TableCell> + </TableRow> + ))} + </TableBody> + </Table> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/explorer/file-metadata.tsx b/pkg/ui/frontend/src/components/explorer/file-metadata.tsx new file mode 100644 index 0000000000000..914d5681b57c9 --- /dev/null +++ b/pkg/ui/frontend/src/components/explorer/file-metadata.tsx @@ -0,0 +1,549 @@ +import { Link } from "react-router-dom"; +import { DownloadIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { formatBytes } from "@/lib/utils"; +import { FileMetadataResponse } from "@/types/explorer"; +import { DateHover } from "@/components/common/date-hover"; +import { CopyButton } from "../common/copy-button"; +import { CompressionRatio } from "../common/compression-ratio"; +import { useState } from "react"; + +// Value type to badge styling mapping +const getValueTypeBadgeStyle = (valueType: string): string => { + switch (valueType) { + case "INT64": + return "bg-blue-500/20 text-blue-700 dark:bg-blue-500/30 dark:text-blue-300 hover:bg-blue-500/30"; + case "BYTES": + return "bg-red-500/20 text-red-700 dark:bg-red-500/30 dark:text-red-300 hover:bg-red-500/30"; + case "FLOAT64": + return "bg-purple-500/20 text-purple-700 dark:bg-purple-500/30 dark:text-purple-300 hover:bg-purple-500/30"; + case "BOOL": + return "bg-yellow-500/20 text-yellow-700 dark:bg-yellow-500/30 dark:text-yellow-300 hover:bg-yellow-500/30"; + case "STRING": + return "bg-green-500/20 text-green-700 dark:bg-green-500/30 dark:text-green-300 hover:bg-green-500/30"; + case "TIMESTAMP": + return "bg-orange-500/20 text-orange-700 dark:bg-orange-500/30 dark:text-orange-300 hover:bg-orange-500/30"; + default: + return "bg-gray-500/20 text-gray-700 dark:bg-gray-500/30 dark:text-gray-300 hover:bg-gray-500/30"; + } +}; + +interface FileMetadataViewProps { + metadata: FileMetadataResponse; + filename: string; + downloadUrl: string; +} + +export function FileMetadataView({ + metadata, + filename, + downloadUrl, +}: FileMetadataViewProps) { + const [expandedSectionIndex, setExpandedSectionIndex] = useState< + number | null + >(null); + const [expandedColumns, setExpandedColumns] = useState< + Record<string, boolean> + >({}); + + const toggleSection = (sectionIndex: number) => { + setExpandedSectionIndex( + expandedSectionIndex === sectionIndex ? null : sectionIndex + ); + }; + + const toggleColumn = (sectionIndex: number, columnIndex: number) => { + const key = `${sectionIndex}-${columnIndex}`; + setExpandedColumns((prev) => ({ + ...prev, + [key]: !prev[key], + })); + }; + + // Calculate file-level stats + const totalCompressed = metadata.sections.reduce( + (sum, section) => sum + section.totalCompressedSize, + 0 + ); + const totalUncompressed = metadata.sections.reduce( + (sum, section) => sum + section.totalUncompressedSize, + 0 + ); + + // Get stream and log counts from first column of each section + const streamSection = metadata.sections.filter( + (s) => s.type === "SECTION_TYPE_STREAMS" + ); + const logSection = metadata.sections.filter( + (s) => s.type === "SECTION_TYPE_LOGS" + ); + const streamCount = streamSection?.reduce( + (sum, sec) => sum + (sec.columns[0].rows_count || 0), + 0 + ); + const logCount = logSection?.reduce( + (sum, sec) => sum + (sec.columns[0].rows_count || 0), + 0 + ); + + return ( + <Card className="w-full"> + <FileHeader + filename={filename} + downloadUrl={downloadUrl} + lastModified={metadata.lastModified} + /> + <CardContent className="space-y-8"> + <HeadlineStats + totalCompressed={totalCompressed} + totalUncompressed={totalUncompressed} + sections={metadata.sections} + streamCount={streamCount} + logCount={logCount} + /> + <SectionsList + sections={metadata.sections} + expandedSectionIndex={expandedSectionIndex} + expandedColumns={expandedColumns} + onToggleSection={toggleSection} + onToggleColumn={toggleColumn} + /> + </CardContent> + </Card> + ); +} + +// Sub-components + +interface FileHeaderProps { + filename: string; + downloadUrl: string; + lastModified: string; +} + +function FileHeader({ filename, downloadUrl, lastModified }: FileHeaderProps) { + return ( + <CardHeader className="space-y-4"> + <div className="flex items-center justify-between"> + <CardTitle className="text-2xl font-semibold tracking-tight"> + Thor Dataobj File + </CardTitle> + <Button asChild variant="outline"> + <Link to={downloadUrl} target="_blank" download> + <DownloadIcon className="h-4 w-4 mr-2" /> + Download + </Link> + </Button> + </div> + <CardDescription className="space-y-2"> + <div className="flex items-center justify-between"> + <div className="space-y-2"> + <div className="flex items-center gap-2"> + <span className="font-mono text-sm text-foreground"> + {filename} + </span> + <CopyButton text={filename} /> + </div> + <div className="flex items-center gap-2 text-sm text-muted-foreground"> + <span>Last Modified:</span> + <DateHover date={new Date(lastModified)} /> + </div> + </div> + </div> + </CardDescription> + </CardHeader> + ); +} + +interface HeadlineStatsProps { + totalCompressed: number; + totalUncompressed: number; + sections: FileMetadataResponse["sections"]; + streamCount?: number; + logCount?: number; +} + +function HeadlineStats({ + totalCompressed, + totalUncompressed, + sections, + streamCount, + logCount, +}: HeadlineStatsProps) { + return ( + <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"> + <div className="rounded-lg bg-muted/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Compression</div> + <CompressionRatio + compressed={totalCompressed} + uncompressed={totalUncompressed} + showVisualization + /> + <div className="text-xs text-muted-foreground mt-2"> + {formatBytes(totalCompressed)} → {formatBytes(totalUncompressed)} + </div> + </div> + <div className="rounded-lg bg-muted/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Sections</div> + <div className="font-medium text-lg">{sections.length}</div> + <div className="text-xs text-muted-foreground mt-2"> + {sections.map((s) => s.type).join(", ")} + </div> + </div> + {streamCount && ( + <div className="rounded-lg bg-muted/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Stream Count</div> + <div className="font-medium text-lg"> + {streamCount.toLocaleString()} + </div> + </div> + )} + {logCount && ( + <div className="rounded-lg bg-muted/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Log Count</div> + <div className="font-medium text-lg">{logCount.toLocaleString()}</div> + </div> + )} + </div> + ); +} + +interface SectionsListProps { + sections: FileMetadataResponse["sections"]; + expandedSectionIndex: number | null; + expandedColumns: Record<string, boolean>; + onToggleSection: (index: number) => void; + onToggleColumn: (sectionIndex: number, columnIndex: number) => void; +} + +function SectionsList({ + sections, + expandedSectionIndex, + expandedColumns, + onToggleSection, + onToggleColumn, +}: SectionsListProps) { + return ( + <div className="divide-y divide-border"> + {sections.map((section, sectionIndex) => ( + <Section + key={sectionIndex} + section={section} + sectionIndex={sectionIndex} + isExpanded={expandedSectionIndex === sectionIndex} + expandedColumns={expandedColumns} + onToggle={() => onToggleSection(sectionIndex)} + onToggleColumn={(columnIndex) => + onToggleColumn(sectionIndex, columnIndex) + } + /> + ))} + </div> + ); +} + +interface SectionProps { + section: FileMetadataResponse["sections"][0]; + sectionIndex: number; + isExpanded: boolean; + expandedColumns: Record<string, boolean>; + onToggle: () => void; + onToggleColumn: (columnIndex: number) => void; +} + +function Section({ + section, + sectionIndex, + isExpanded, + expandedColumns, + onToggle, + onToggleColumn, +}: SectionProps) { + return ( + <div className="py-4"> + <button + className="w-full flex justify-between items-center py-4 px-6 rounded-lg hover:bg-accent/50 transition-colors" + onClick={onToggle} + > + <h3 className="text-lg font-semibold"> + Section #{sectionIndex + 1}: {section.type} + </h3> + <svg + className={`w-5 h-5 transform transition-transform duration-300 ${ + isExpanded ? "rotate-180" : "" + }`} + fill="none" + stroke="currentColor" + viewBox="0 0 24 24" + > + <path + strokeLinecap="round" + strokeLinejoin="round" + strokeWidth="2" + d="M19 9l-7 7-7-7" + /> + </svg> + </button> + + {isExpanded && ( + <div className="mt-6 px-6"> + <SectionStats section={section} /> + <ColumnsList + columns={section.columns} + sectionIndex={sectionIndex} + expandedColumns={expandedColumns} + onToggleColumn={onToggleColumn} + /> + </div> + )} + </div> + ); +} + +interface SectionStatsProps { + section: FileMetadataResponse["sections"][0]; +} + +function SectionStats({ section }: SectionStatsProps) { + return ( + <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8"> + <div className="rounded-lg bg-secondary/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Compression</div> + <CompressionRatio + compressed={section.totalCompressedSize} + uncompressed={section.totalUncompressedSize} + showVisualization + /> + <div className="text-xs text-muted-foreground mt-2"> + {formatBytes(section.totalCompressedSize)} →{" "} + {formatBytes(section.totalUncompressedSize)} + </div> + </div> + <div className="rounded-lg bg-secondary/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Column Count</div> + <div className="font-medium text-lg">{section.columnCount}</div> + </div> + <div className="rounded-lg bg-secondary/50 p-6 shadow-sm"> + <div className="text-sm text-muted-foreground mb-2">Type</div> + <div className="font-medium text-lg flex items-center gap-2"> + <Badge variant="outline" className="font-mono"> + {section.type} + </Badge> + </div> + </div> + </div> + ); +} + +interface ColumnsListProps { + columns: FileMetadataResponse["sections"][0]["columns"]; + sectionIndex: number; + expandedColumns: Record<string, boolean>; + onToggleColumn: (columnIndex: number) => void; +} + +function ColumnsList({ + columns, + sectionIndex, + expandedColumns, + onToggleColumn, +}: ColumnsListProps) { + return ( + <div className="space-y-6"> + <h4 className="text-lg font-medium">Columns ({columns.length})</h4> + <div className="space-y-4"> + {columns.map((column, columnIndex) => ( + <Column + key={columnIndex} + column={column} + isExpanded={expandedColumns[`${sectionIndex}-${columnIndex}`]} + onToggle={() => onToggleColumn(columnIndex)} + /> + ))} + </div> + </div> + ); +} + +interface ColumnProps { + column: FileMetadataResponse["sections"][0]["columns"][0]; + isExpanded: boolean; + onToggle: () => void; +} + +function Column({ column, isExpanded, onToggle }: ColumnProps) { + return ( + <Card className="bg-card/50"> + <button + className="w-full flex justify-between items-center p-6 hover:bg-accent/50 transition-colors rounded-t-lg" + onClick={onToggle} + > + <div> + <h5 className="font-medium text-lg"> + {column.name ? `${column.name} (${column.type})` : column.type} + </h5> + <div className="text-sm text-muted-foreground mt-1 flex items-center gap-2"> + <Badge + variant="secondary" + className={cn( + "font-mono text-xs", + getValueTypeBadgeStyle(column.value_type) + )} + > + {column.value_type} + </Badge> + </div> + </div> + <div className="flex items-center gap-4"> + <div className="text-sm font-medium flex items-center gap-2"> + Compression: + <Badge variant="outline" className="font-mono"> + {column.compression || "NONE"} + </Badge> + </div> + <svg + className={`w-4 h-4 transform transition-transform ${ + isExpanded ? "rotate-180" : "" + }`} + fill="none" + stroke="currentColor" + viewBox="0 0 24 24" + > + <path + strokeLinecap="round" + strokeLinejoin="round" + strokeWidth="2" + d="M19 9l-7 7-7-7" + /> + </svg> + </div> + </button> + + {isExpanded && ( + <CardContent className="pt-6"> + <ColumnStats column={column} /> + {column.pages.length > 0 && <ColumnPages pages={column.pages} />} + </CardContent> + )} + </Card> + ); +} + +interface ColumnStatsProps { + column: FileMetadataResponse["sections"][0]["columns"][0]; +} + +function ColumnStats({ column }: ColumnStatsProps) { + return ( + <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8"> + <div className="rounded-lg bg-muted p-6"> + <div className="text-sm text-muted-foreground mb-2 flex items-center gap-2"> + <Badge variant="outline" className="font-mono"> + {column.compression || "NONE"} + </Badge> + </div> + <div className="font-medium"> + <CompressionRatio + compressed={column.compressed_size} + uncompressed={column.uncompressed_size} + /> + </div> + <div className="text-xs text-muted-foreground mt-2"> + {formatBytes(column.compressed_size)} →{" "} + {formatBytes(column.uncompressed_size)} + </div> + </div> + <div className="rounded-lg bg-muted p-6"> + <div className="text-sm text-muted-foreground mb-2">Rows</div> + <div className="font-medium text-lg"> + {column.rows_count.toLocaleString()} + </div> + </div> + <div className="rounded-lg bg-muted p-6"> + <div className="text-sm text-muted-foreground mb-2">Values Count</div> + <div className="font-medium text-lg"> + {column.values_count.toLocaleString()} + </div> + </div> + <div className="rounded-lg bg-muted p-6"> + <div className="text-sm text-muted-foreground mb-2">Offset</div> + <div className="font-medium text-lg"> + {formatBytes(column.metadata_offset)} + </div> + </div> + </div> + ); +} + +interface ColumnPagesProps { + pages: FileMetadataResponse["sections"][0]["columns"][0]["pages"]; +} + +function ColumnPages({ pages }: ColumnPagesProps) { + return ( + <div className="mt-8"> + <h6 className="text-base font-medium mb-4">Pages ({pages.length})</h6> + <div className="rounded-lg border border-border overflow-hidden bg-background"> + <table className="w-full"> + <thead> + <tr className="bg-secondary/50 border-b border-border"> + <th className="text-left p-4 font-medium text-muted-foreground"> + # + </th> + <th className="text-left p-4 font-medium text-muted-foreground"> + Rows + </th> + <th className="text-left p-4 font-medium text-muted-foreground"> + Values + </th> + <th className="text-left p-4 font-medium text-muted-foreground"> + Encoding + </th> + <th className="text-left p-4 font-medium text-muted-foreground"> + Compression + </th> + </tr> + </thead> + <tbody> + {pages.map((page, pageIndex) => ( + <tr + key={pageIndex} + className="border-t border-border hover:bg-accent/50 transition-colors" + > + <td className="p-4">{pageIndex + 1}</td> + <td className="p-4">{page.rows_count.toLocaleString()}</td> + <td className="p-4">{page.values_count.toLocaleString()}</td> + <td className="p-4"> + <Badge variant="outline" className="font-mono"> + {page.encoding} + </Badge> + </td> + <td className="p-4"> + <div className="flex items-center gap-2"> + <CompressionRatio + compressed={page.compressed_size} + uncompressed={page.uncompressed_size} + /> + <span className="text-xs text-muted-foreground"> + ({formatBytes(page.compressed_size)} →{" "} + {formatBytes(page.uncompressed_size)}) + </span> + </div> + </td> + </tr> + ))} + </tbody> + </table> + </div> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/index.ts b/pkg/ui/frontend/src/components/index.ts new file mode 100644 index 0000000000000..109feb5c18844 --- /dev/null +++ b/pkg/ui/frontend/src/components/index.ts @@ -0,0 +1,5 @@ +export * from "./ui"; +export * from "./shared"; +export * from "./nodes"; +export * from "./common"; +export * from "./version-display"; diff --git a/pkg/ui/frontend/src/components/nodes/data-table-column-header.tsx b/pkg/ui/frontend/src/components/nodes/data-table-column-header.tsx new file mode 100644 index 0000000000000..339a7dd2db22f --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/data-table-column-header.tsx @@ -0,0 +1,83 @@ +import { ChevronsUpDown, ArrowDown, ArrowUp } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "../ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "../ui/dropdown-menu"; + +interface DataTableColumnHeaderProps { + title: string; + field: "name" | "target" | "version" | "buildDate"; + sortField: string; + sortDirection: "asc" | "desc"; + onSort: (field: "name" | "target" | "version" | "buildDate") => void; +} + +export function DataTableColumnHeader({ + title, + field, + sortField, + sortDirection, + onSort, +}: DataTableColumnHeaderProps) { + const isCurrentSort = sortField === field; + + const handleSort = (direction: "asc" | "desc") => { + if (sortField === field && sortDirection === direction) { + return; + } + onSort(field); + }; + + return ( + <div className="flex items-center space-x-2"> + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + variant="ghost" + size="sm" + className="-ml-3 h-8 hover:bg-muted/50 data-[state=open]:bg-muted/50" + > + <div className="flex items-center"> + <span>{title}</span> + {isCurrentSort ? ( + sortDirection === "desc" ? ( + <ArrowDown className="ml-2 h-4 w-4" /> + ) : ( + <ArrowUp className="ml-2 h-4 w-4" /> + ) + ) : ( + <ChevronsUpDown className="ml-2 h-4 w-4" /> + )} + </div> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="start"> + <DropdownMenuItem + onClick={() => handleSort("asc")} + className={cn( + "cursor-pointer", + isCurrentSort && sortDirection === "asc" && "bg-accent" + )} + > + <ArrowUp className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" /> + Asc + </DropdownMenuItem> + <DropdownMenuItem + onClick={() => handleSort("desc")} + className={cn( + "cursor-pointer", + isCurrentSort && sortDirection === "desc" && "bg-accent" + )} + > + <ArrowDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" /> + Desc + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/index.ts b/pkg/ui/frontend/src/components/nodes/index.ts new file mode 100644 index 0000000000000..801a69cc881f4 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/index.ts @@ -0,0 +1,12 @@ +export * from "./data-table-column-header"; +export * from "./log-level-select"; +export * from "./node-filters"; +export * from "./node-list"; +export * from "./node-status-indicator"; +export * from "./pprof-controls"; +export * from "./service-state-distribution"; +export * from "./service-table"; +export * from "./status-badge"; +export * from "./storage-type-indicator"; +export * from "./target-distribution-chart"; +export * from "./version-information"; diff --git a/pkg/ui/frontend/src/components/nodes/log-level-select.tsx b/pkg/ui/frontend/src/components/nodes/log-level-select.tsx new file mode 100644 index 0000000000000..7349bea551179 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/log-level-select.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { Check, AlertCircle } from "lucide-react"; +import { useLogLevel } from "@/hooks/use-log-level"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { cn } from "@/lib/utils"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; + +const LOG_LEVELS = ["debug", "info", "warn", "error"] as const; + +interface LogLevelSelectProps { + nodeName: string; + className?: string; +} + +export function LogLevelSelect({ nodeName, className }: LogLevelSelectProps) { + const { logLevel, isLoading, error, success, setLogLevel } = + useLogLevel(nodeName); + + const handleValueChange = (value: string) => { + setLogLevel(value); + }; + + return ( + <div className="relative flex items-center gap-2"> + <Select + value={logLevel} + onValueChange={handleValueChange} + disabled={isLoading} + > + <SelectTrigger + className={cn( + "w-[180px]", + className, + isLoading && "opacity-50 cursor-not-allowed" + )} + > + <SelectValue placeholder="Select log level" /> + </SelectTrigger> + <SelectContent> + {LOG_LEVELS.map((level) => ( + <SelectItem key={level} value={level}> + {level} + </SelectItem> + ))} + </SelectContent> + </Select> + + {/* Success/Error Indicator with Tooltip */} + <TooltipProvider> + <Tooltip> + <TooltipTrigger asChild> + <div + className={cn( + "absolute -right-6 transition-all duration-300 ease-in-out", + success || error + ? "opacity-100 translate-x-0" + : "opacity-0 translate-x-2" + )} + > + {success && ( + <Check className="h-4 w-4 text-green-500 animate-in zoom-in-50 duration-300" /> + )} + {error && ( + <AlertCircle className="h-4 w-4 text-red-500 animate-in zoom-in-50 duration-300" /> + )} + </div> + </TooltipTrigger> + <TooltipContent side="right" className="text-xs"> + {success && "Log level updated successfully"} + {error && error} + </TooltipContent> + </Tooltip> + </TooltipProvider> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/node-filters.tsx b/pkg/ui/frontend/src/components/nodes/node-filters.tsx new file mode 100644 index 0000000000000..2390354e308d7 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/node-filters.tsx @@ -0,0 +1,92 @@ +import React from "react"; +import { NodeState, ALL_NODE_STATES } from "../../types/cluster"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { MultiSelect } from "@/components/common/multi-select"; +import { RefreshCw } from "lucide-react"; + +interface NodeFiltersProps { + nameFilter: string; + targetFilter: string[]; + selectedStates: NodeState[]; + onNameFilterChange: (value: string) => void; + onTargetFilterChange: (value: string[]) => void; + onStatesChange: (states: NodeState[]) => void; + onRefresh: () => void; + availableTargets: string[]; + isLoading?: boolean; +} + +const NodeFilters: React.FC<NodeFiltersProps> = ({ + nameFilter, + targetFilter, + selectedStates, + onNameFilterChange, + onTargetFilterChange, + onStatesChange, + onRefresh, + availableTargets, +}) => { + const stateOptions = ALL_NODE_STATES.map((state) => ({ + label: state, + value: state, + })); + + const handleStateChange = (values: string[]) => { + onStatesChange(values as NodeState[]); + }; + + return ( + <div className="grid grid-cols-[auto_1fr_auto] gap-x-4 gap-y-2"> + <div className="space-y-2"> + <div className="space-y-1.5"> + <label className="text-sm font-medium text-muted-foreground"> + Node filters + </label> + <Input + value={nameFilter} + onChange={(e: React.ChangeEvent<HTMLInputElement>) => + onNameFilterChange(e.target.value) + } + placeholder="Filter by node name..." + className="w-[300px]" + /> + <MultiSelect + options={availableTargets.map((target) => ({ + value: target, + label: target, + }))} + selected={targetFilter} + onChange={onTargetFilterChange} + placeholder="All Targets" + className="w-[300px]" + /> + </div> + </div> + <div className="space-y-1.5 self-end"> + <label className="text-sm font-medium text-muted-foreground"> + Service states + </label> + <MultiSelect + options={stateOptions} + selected={selectedStates} + onChange={handleStateChange} + placeholder="Filter nodes by service states..." + className="w-full min-w-[300px]" + /> + </div> + <div className="self-end"> + <Button + onClick={onRefresh} + size="sm" + variant="outline" + className="h-9 w-9" + > + <RefreshCw className="h-4 w-4" /> + </Button> + </div> + </div> + ); +}; + +export default NodeFilters; diff --git a/pkg/ui/frontend/src/components/nodes/node-list.tsx b/pkg/ui/frontend/src/components/nodes/node-list.tsx new file mode 100644 index 0000000000000..d9a3f2d93c488 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/node-list.tsx @@ -0,0 +1,193 @@ +import React from "react"; +import { formatDistanceToNow, parseISO, isValid } from "date-fns"; +import { Member } from "@/types/cluster"; +import StatusBadge from "@/components/nodes/status-badge"; +import { ReadinessIndicator } from "@/components/nodes/readiness-indicator"; +import { DataTableColumnHeader } from "@/components/common/data-table-column-header"; +import { Button } from "@/components/ui/button"; +import { ArrowRightCircle } from "lucide-react"; +import { useNavigate } from "react-router-dom"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; + +type NodeSortField = "name" | "target" | "version" | "buildDate"; + +interface NodeListProps { + nodes: { [key: string]: Member }; + sortField: NodeSortField; + sortDirection: "asc" | "desc"; + onSort: (field: NodeSortField) => void; +} + +interface NodeRowProps { + name: string; + node: Member; + onNavigate: (name: string) => void; +} + +const formatBuildDate = (dateStr: string) => { + try { + const date = parseISO(dateStr); + if (!isValid(date)) { + return "Invalid date"; + } + return formatDistanceToNow(date, { addSuffix: true }); + } catch (error) { + console.warn("Error parsing date:", dateStr, error); + return "Invalid date"; + } +}; + +const NodeRow: React.FC<NodeRowProps> = ({ name, node, onNavigate }) => { + return ( + <TableRow + key={name} + className="hover:bg-muted/50 cursor-pointer" + onClick={() => onNavigate(name)} + > + <TableCell className="font-medium">{name}</TableCell> + <TableCell>{node.target}</TableCell> + <TableCell className="font-mono text-sm">{node.build.version}</TableCell> + <TableCell>{formatBuildDate(node.build.buildDate)}</TableCell> + <TableCell> + <StatusBadge services={node.services} error={node.error} /> + </TableCell> + <TableCell> + <ReadinessIndicator + isReady={node.ready?.isReady} + message={node.ready?.message} + /> + </TableCell> + <TableCell> + <Button + variant="ghost" + size="sm" + className="h-8 w-8 p-0" + onClick={(e) => { + e.stopPropagation(); + onNavigate(name); + }} + > + <ArrowRightCircle className="h-4 w-4" /> + <span className="sr-only">View details</span> + </Button> + </TableCell> + </TableRow> + ); +}; + +const NodeList: React.FC<NodeListProps> = ({ + nodes, + sortField, + sortDirection, + onSort, +}) => { + const navigate = useNavigate(); + + const compareDates = (dateStrA: string, dateStrB: string) => { + const dateA = parseISO(dateStrA); + const dateB = parseISO(dateStrB); + if (!isValid(dateA) && !isValid(dateB)) return 0; + if (!isValid(dateA)) return 1; + if (!isValid(dateB)) return -1; + return dateA.getTime() - dateB.getTime(); + }; + + const sortedNodes = Object.entries(nodes).sort(([aKey, a], [bKey, b]) => { + let comparison = 0; + switch (sortField) { + case "name": + comparison = aKey.localeCompare(bKey); + break; + case "target": + comparison = a.target.localeCompare(b.target); + break; + case "version": + comparison = a.build.version.localeCompare(b.build.version); + break; + case "buildDate": + comparison = compareDates(a.build.buildDate, b.build.buildDate); + break; + } + return sortDirection === "asc" ? comparison : -comparison; + }); + + const handleNavigate = (name: string) => { + navigate(`/nodes/${name}`); + }; + + return ( + <div className="rounded-md border bg-card"> + <Table> + <TableHeader> + <TableRow className="hover:bg-transparent"> + <TableHead className="w-[300px]"> + <DataTableColumnHeader<NodeSortField> + title="Node Name" + field="name" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<NodeSortField> + title="Target" + field="target" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<NodeSortField> + title="Version" + field="version" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<NodeSortField> + title="Build Date" + field="buildDate" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]">Status</TableHead> + <TableHead className="w-[50px]">Ready</TableHead> + <TableHead className="w-[100px]">Actions</TableHead> + </TableRow> + </TableHeader> + <TableBody> + {sortedNodes.map(([name, node]) => ( + <NodeRow + key={name} + name={name} + node={node} + onNavigate={handleNavigate} + /> + ))} + {sortedNodes.length === 0 && ( + <TableRow> + <TableCell colSpan={7} className="h-24 text-center"> + <div className="text-muted-foreground">No nodes found</div> + </TableCell> + </TableRow> + )} + </TableBody> + </Table> + </div> + ); +}; + +export default NodeList; diff --git a/pkg/ui/frontend/src/components/nodes/node-status-indicator.tsx b/pkg/ui/frontend/src/components/nodes/node-status-indicator.tsx new file mode 100644 index 0000000000000..41c76b853ae40 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/node-status-indicator.tsx @@ -0,0 +1,79 @@ +import { useEffect, useState } from "react"; +import { cn } from "@/lib/utils"; + +interface NodeStatusIndicatorProps { + nodeName: string; + className?: string; +} + +interface NodeStatus { + isReady: boolean; + message: string; +} + +export function NodeStatusIndicator({ + nodeName, + className, +}: NodeStatusIndicatorProps) { + const [status, setStatus] = useState<NodeStatus>({ + isReady: false, + message: "Checking status...", + }); + const [isVisible, setIsVisible] = useState(true); + + useEffect(() => { + const checkStatus = async () => { + try { + const response = await fetch(`/ui/api/v1/proxy/${nodeName}/ready`); + const text = await response.text(); + setStatus({ + isReady: response.ok && text.includes("ready"), + message: response.ok ? "Ready" : text, + }); + } catch (error) { + setStatus({ + isReady: false, + message: + error instanceof Error ? error.message : "Failed to check status", + }); + } + }; + + // Initial check + checkStatus(); + + // Set up the status check interval + const statusInterval = setInterval(checkStatus, 3000); + + // Set up the blink interval + const blinkInterval = setInterval(() => { + setIsVisible((prev) => !prev); + }, 1000); + + // Cleanup intervals on unmount + return () => { + clearInterval(statusInterval); + clearInterval(blinkInterval); + }; + }, [nodeName]); + + return ( + <div className={cn("flex items-center gap-2", className)}> + <span + className={cn( + "text-sm", + status.isReady ? "text-muted-foreground" : "text-red-500" + )} + > + {status.message} + </span> + <div + className={cn( + "h-2.5 w-2.5 rounded-full transition-opacity duration-150", + status.isReady ? "bg-green-500" : "bg-red-500", + isVisible ? "opacity-100" : "opacity-30" + )} + /> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/pprof-controls.tsx b/pkg/ui/frontend/src/components/nodes/pprof-controls.tsx new file mode 100644 index 0000000000000..d8d13ef9a6c9a --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/pprof-controls.tsx @@ -0,0 +1,124 @@ +import { Button } from "@/components/ui/button"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; + +interface PprofControlsProps { + nodeName: string; +} + +const pprofTypes = [ + { + name: "allocs", + description: "A sampling of all past memory allocations", + }, + { + name: "block", + description: + "Stack traces that led to blocking on synchronization primitives", + }, + { + name: "heap", + description: "A sampling of memory allocations of live objects", + }, + { + name: "mutex", + description: "Stack traces of holders of contended mutexes", + }, + { + name: "profile", + urlSuffix: "?seconds=15", + description: "CPU profile (15 seconds)", + displayName: "profile", + }, + { + name: "goroutine", + description: "Stack traces of all current goroutines (debug=1)", + variants: [ + { + suffix: "?debug=0", + label: "Basic", + description: "Basic goroutine info", + }, + { + suffix: "?debug=1", + label: "Standard", + description: "Standard goroutine stack traces", + }, + { + suffix: "?debug=2", + label: "Full", + description: "Full goroutine stack dump with additional info", + }, + ], + }, + { + name: "threadcreate", + description: "Stack traces that led to the creation of new OS threads", + urlSuffix: "?debug=1", + displayName: "threadcreate", + }, + { + name: "trace", + description: "A trace of execution of the current program", + urlSuffix: "?debug=1", + displayName: "trace", + }, +]; + +export function PprofControls({ nodeName }: PprofControlsProps) { + const downloadPprof = (type: string) => { + window.open(`/ui/api/v1/proxy/${nodeName}/debug/pprof/${type}`, "_blank"); + }; + + return ( + <div className="flex items-center gap-2"> + <span className="text-sm font-medium">Profiling Tools:</span> + <div className="flex flex-wrap gap-2"> + {pprofTypes.map((type) => { + if (type.variants) { + return type.variants.map((variant) => ( + <Tooltip key={`${type.name}${variant.suffix}`}> + <TooltipTrigger asChild> + <Button + variant="outline" + size="sm" + onClick={() => + downloadPprof(`${type.name}${variant.suffix}`) + } + > + {`${type.name} (${variant.label})`} + </Button> + </TooltipTrigger> + <TooltipContent> + <p>{variant.description}</p> + </TooltipContent> + </Tooltip> + )); + } + + return ( + <Tooltip key={type.name}> + <TooltipTrigger asChild> + <Button + variant="outline" + size="sm" + onClick={() => + downloadPprof(`${type.name}${type.urlSuffix || ""}`) + } + > + {type.displayName || type.name} + </Button> + </TooltipTrigger> + <TooltipContent> + <p>{type.description}</p> + </TooltipContent> + </Tooltip> + ); + })} + </div> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/readiness-indicator.tsx b/pkg/ui/frontend/src/components/nodes/readiness-indicator.tsx new file mode 100644 index 0000000000000..570aba6b97a2c --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/readiness-indicator.tsx @@ -0,0 +1,41 @@ +import { cn } from "@/lib/utils"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; + +interface ReadinessIndicatorProps { + isReady?: boolean; + message?: string; + className?: string; +} + +export function ReadinessIndicator({ + isReady, + message, + className, +}: ReadinessIndicatorProps) { + return ( + <TooltipProvider> + <Tooltip> + <TooltipTrigger asChild> + <div className={cn("flex items-center gap-2", className)}> + <div + className={cn( + "h-2.5 w-2.5 rounded-full", + isReady ? "bg-green-500" : "bg-red-500" + )} + /> + </div> + </TooltipTrigger> + <TooltipContent> + <p className="text-sm"> + {message || (isReady ? "Ready" : "Not Ready")} + </p> + </TooltipContent> + </Tooltip> + </TooltipProvider> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/service-state-distribution.tsx b/pkg/ui/frontend/src/components/nodes/service-state-distribution.tsx new file mode 100644 index 0000000000000..760d971dd5ca7 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/service-state-distribution.tsx @@ -0,0 +1,109 @@ +import { useMemo } from "react"; +import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts"; +import { NodeState } from "@/types/cluster"; + +const STATE_COLORS: Record<NodeState, string> = { + Running: "#10B981", // emerald-500 + Starting: "#F59E0B", // amber-500 + New: "#3B82F6", // blue-500 + Stopping: "#F59E0B", // amber-500 + Terminated: "#6B7280", // gray-500 + Failed: "#EF4444", // red-500 +}; + +interface ServiceStateDistributionProps { + services: Array<{ service: string; status: string }>; +} + +export function ServiceStateDistribution({ + services, +}: ServiceStateDistributionProps) { + const data = useMemo(() => { + const stateCounts = services.reduce((acc, { status }) => { + const state = status as NodeState; + acc.set(state, (acc.get(state) || 0) + 1); + return acc; + }, new Map<NodeState, number>()); + + return Array.from(stateCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([state, count]) => ({ + name: state, + value: count, + color: STATE_COLORS[state], + })); + }, [services]); + + const total = useMemo(() => services.length, [services]); + + if (data.length === 0) { + return null; + } + + return ( + <div className="h-[180px] w-full flex items-center"> + <div className="flex-1 relative"> + <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none z-10"> + <div className="text-2xl font-bold">{total}</div> + <div className="text-xs text-muted-foreground">Services</div> + </div> + <ResponsiveContainer width="100%" height={180}> + <PieChart margin={{ top: 0, right: 0, bottom: 0, left: 0 }}> + <Pie + data={data} + cx="50%" + cy="50%" + labelLine={false} + outerRadius={70} + innerRadius={50} + dataKey="value" + paddingAngle={2} + strokeWidth={2} + > + {data.map((entry) => ( + <Cell + key={`cell-${entry.name}`} + fill={entry.color} + stroke="hsl(var(--background))" + /> + ))} + </Pie> + <Tooltip + content={({ active, payload }) => { + if (!active || !payload || !payload[0]) return null; + const data = payload[0].payload; + return ( + <div className="bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2"> + <div + className="w-2.5 h-2.5 rounded-sm" + style={{ backgroundColor: data.color }} + /> + <span className="text-sm font-medium">{data.name}</span> + <span className="text-sm font-semibold">{data.value}</span> + </div> + ); + }} + /> + </PieChart> + </ResponsiveContainer> + </div> + <div className="flex flex-col gap-1.5 min-w-[120px] pl-4"> + {data.map((item) => ( + <div + key={item.name} + className="flex items-center justify-between gap-2 text-sm" + > + <div className="flex items-center gap-2"> + <div + className="w-2 h-2 rounded-full shrink-0" + style={{ backgroundColor: item.color }} + /> + <span className="text-muted-foreground">{item.name}</span> + </div> + <span className="font-medium tabular-nums">{item.value}</span> + </div> + ))} + </div> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/service-table.tsx b/pkg/ui/frontend/src/components/nodes/service-table.tsx new file mode 100644 index 0000000000000..b9f8b1e0aa6f6 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/service-table.tsx @@ -0,0 +1,64 @@ +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { ScrollArea } from "@/components/ui/scroll-area"; + +interface Service { + service: string; + status: string; +} + +interface ServiceTableProps { + services: Service[]; +} + +const getStatusColor = (status: string) => { + switch (status) { + case "Running": + return "text-green-600 dark:text-green-400"; + case "Starting": + return "text-yellow-600 dark:text-yellow-400"; + case "Failed": + return "text-red-600 dark:text-red-400"; + case "New": + return "text-blue-600 dark:text-blue-400"; + case "Terminated": + return "text-gray-600 dark:text-gray-400"; + default: + return "text-gray-600 dark:text-gray-400"; + } +}; + +export function ServiceTable({ services }: ServiceTableProps) { + return ( + <ScrollArea className="h-[180px] rounded-md border"> + <Table> + <TableHeader> + <TableRow> + <TableHead>Service</TableHead> + <TableHead className="text-right">Status</TableHead> + </TableRow> + </TableHeader> + <TableBody> + {services.map((service) => ( + <TableRow key={service.service} className="hover:bg-muted/50"> + <TableCell className="font-medium">{service.service}</TableCell> + <TableCell + className={`text-right ${getStatusColor( + service.status + )} font-medium`} + > + {service.status} + </TableCell> + </TableRow> + ))} + </TableBody> + </Table> + </ScrollArea> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/status-badge.tsx b/pkg/ui/frontend/src/components/nodes/status-badge.tsx new file mode 100644 index 0000000000000..46e9907c3747c --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/status-badge.tsx @@ -0,0 +1,109 @@ +import React from "react"; +import { ServiceState } from "../../types/cluster"; +import { Badge } from "@/components/ui/badge"; +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; + +interface StatusBadgeProps { + services: ServiceState[]; + error?: string; +} + +const StatusBadge: React.FC<StatusBadgeProps> = ({ services, error }) => { + const getStatusInfo = () => { + if (error) { + return { + className: + "bg-red-500 dark:bg-red-500/80 hover:bg-red-600 dark:hover:bg-red-500 text-white border-transparent", + tooltip: `Error: ${error}`, + status: "error", + }; + } + + const allRunning = services.every((s) => s.status === "Running"); + const onlyStartingOrRunning = services.every( + (s) => s.status === "Starting" || s.status === "Running" + ); + + if (allRunning) { + return { + className: + "bg-green-500 dark:bg-green-500/80 hover:bg-green-600 dark:hover:bg-green-500 text-white border-transparent", + status: "healthy", + }; + } else if (onlyStartingOrRunning) { + return { + className: + "bg-yellow-500 dark:bg-yellow-500/80 hover:bg-yellow-600 dark:hover:bg-yellow-500 text-white border-transparent", + status: "pending", + }; + } else { + return { + className: + "bg-red-500 dark:bg-red-500/80 hover:bg-red-600 dark:hover:bg-red-500 text-white border-transparent", + status: "unhealthy", + }; + } + }; + + const getStatusColor = (status: string) => { + switch (status) { + case "Running": + return "text-green-600 dark:text-green-400"; + case "Starting": + return "text-yellow-600 dark:text-yellow-400"; + case "Failed": + return "text-red-600 dark:text-red-400"; + case "Terminated": + return "text-gray-600 dark:text-gray-400"; + case "Stopping": + return "text-orange-600 dark:text-orange-400"; + case "New": + return "text-blue-600 dark:text-blue-400"; + default: + return "text-gray-600 dark:text-gray-400"; + } + }; + + const { className } = getStatusInfo(); + + return ( + <HoverCard> + <HoverCardTrigger> + <button type="button"> + <Badge className={className}>{services.length} services</Badge> + </button> + </HoverCardTrigger> + <HoverCardContent + className="w-80 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2" + sideOffset={5} + > + <div className="space-y-2"> + <div className="font-medium border-b border-gray-200 dark:border-gray-700 pb-1"> + Service Status + </div> + <div className="space-y-1"> + {services.map((service, idx) => ( + <div key={idx} className="flex justify-between items-center"> + <span className="mr-4 font-medium">{service.service}</span> + <span className={`${getStatusColor(service.status)}`}> + {service.status} + </span> + </div> + ))} + </div> + {error && ( + <div className="mt-2 pt-2 border-t border-gray-200 dark:border-gray-700 text-red-600 dark:text-red-400"> + {error} + </div> + )} + </div> + </HoverCardContent> + </HoverCard> + ); +}; + +export default StatusBadge; diff --git a/pkg/ui/frontend/src/components/nodes/storage-type-indicator.tsx b/pkg/ui/frontend/src/components/nodes/storage-type-indicator.tsx new file mode 100644 index 0000000000000..d5853413b76e5 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/storage-type-indicator.tsx @@ -0,0 +1,73 @@ +import { cn } from "@/lib/utils"; + +interface StorageTypeIndicatorProps { + type: string; + className?: string; +} + +const storageTypeColors: Record<string, string> = { + // AWS related + aws: "text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400", + "aws-dynamo": + "text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400", + s3: "text-yellow-600 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-400", + + // Azure + azure: "text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400", + + // GCP related + gcp: "text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400", + "gcp-columnkey": + "text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400", + gcs: "text-blue-600 bg-blue-100 dark:bg-blue-950 dark:text-blue-400", + + // Alibaba Cloud + alibabacloud: + "text-orange-600 bg-orange-100 dark:bg-orange-950 dark:text-orange-400", + + // Local storage types + filesystem: "text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400", + local: "text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400", + + // Database types + boltdb: + "text-emerald-600 bg-emerald-100 dark:bg-emerald-950 dark:text-emerald-400", + cassandra: "text-blue-700 bg-blue-100 dark:bg-blue-950 dark:text-blue-400", + bigtable: "text-red-600 bg-red-100 dark:bg-red-950 dark:text-red-400", + "bigtable-hashed": + "text-red-600 bg-red-100 dark:bg-red-950 dark:text-red-400", + + // Other cloud providers + bos: "text-cyan-600 bg-cyan-100 dark:bg-cyan-950 dark:text-cyan-400", + cos: "text-green-600 bg-green-100 dark:bg-green-950 dark:text-green-400", + swift: + "text-orange-600 bg-orange-100 dark:bg-orange-950 dark:text-orange-400", + + // Special types + inmemory: + "text-purple-600 bg-purple-100 dark:bg-purple-950 dark:text-purple-400", + "grpc-store": + "text-indigo-600 bg-indigo-100 dark:bg-indigo-950 dark:text-indigo-400", +}; + +export function StorageTypeIndicator({ + type, + className, +}: StorageTypeIndicatorProps) { + const normalizedType = type.toLowerCase(); + const colorClasses = + storageTypeColors[normalizedType] || + "text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-400"; + + return ( + <span + className={cn( + "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium", + colorClasses, + className + )} + > + {normalizedType} + </span> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/target-distribution-chart.tsx b/pkg/ui/frontend/src/components/nodes/target-distribution-chart.tsx new file mode 100644 index 0000000000000..59b5a3d66d5d5 --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/target-distribution-chart.tsx @@ -0,0 +1,90 @@ +import { useMemo } from "react"; +import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts"; +import { Member } from "@/types/cluster"; + +// Use theme chart colors directly +const getChartColor = (index: number): string => { + return `hsl(var(--chart-${(index % 6) + 1}))`; +}; + +interface TargetDistributionChartProps { + nodes: { [key: string]: Member }; +} + +export function TargetDistributionChart({ + nodes, +}: TargetDistributionChartProps) { + const data = useMemo(() => { + const targetCounts = new Map<string, number>(); + + Object.values(nodes).forEach((node) => { + const target = node.target || "unknown"; + targetCounts.set(target, (targetCounts.get(target) || 0) + 1); + }); + + return Array.from(targetCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([name, value], index) => ({ + name, + value, + color: getChartColor(index), + })); + }, [nodes]); + + const totalNodes = useMemo(() => { + return Object.keys(nodes).length; + }, [nodes]); + + if (data.length === 0) { + return null; + } + + return ( + <div className="w-full h-[120px] relative"> + <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"> + <div className="text-xl font-bold">{totalNodes}</div> + <div className="text-xs text-muted-foreground">Nodes</div> + </div> + <ResponsiveContainer width="100%" height="100%"> + <PieChart> + <Pie + data={data} + cx="50%" + cy="50%" + labelLine={false} + outerRadius={60} + innerRadius={42} + fill="hsl(var(--chart-1))" + dataKey="value" + paddingAngle={1} + strokeWidth={1} + > + {data.map((entry, index) => ( + <Cell + key={`cell-${entry.name}`} + fill={getChartColor(index)} + stroke="hsl(var(--background))" + /> + ))} + </Pie> + <Tooltip + content={({ active, payload }) => { + if (!active || !payload || !payload[0]) return null; + const data = payload[0].payload; + return ( + <div className="bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2"> + <div + className="w-2.5 h-2.5 rounded-sm" + style={{ backgroundColor: data.color }} + /> + <span className="text-sm font-medium">{data.name}</span> + <span className="text-sm font-semibold">{data.value}</span> + </div> + ); + }} + /> + </PieChart> + </ResponsiveContainer> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/nodes/version-information.tsx b/pkg/ui/frontend/src/components/nodes/version-information.tsx new file mode 100644 index 0000000000000..7e166891685bc --- /dev/null +++ b/pkg/ui/frontend/src/components/nodes/version-information.tsx @@ -0,0 +1,97 @@ +import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card"; +import { Label } from "@/components/ui/label"; +import { FaApple, FaLinux, FaWindows } from "react-icons/fa"; +import { Badge } from "@/components/ui/badge"; + +interface VersionInformationProps { + build: { + version: string; + branch?: string; + goVersion: string; + }; + edition: string; + os: string; + arch: string; +} + +const getOSIcon = (os: string) => { + const osLower = os.toLowerCase(); + if (osLower.includes("darwin") || osLower.includes("mac")) { + return <FaApple className="h-4 w-4" />; + } + if (osLower.includes("linux")) { + return <FaLinux className="h-4 w-4" />; + } + if (osLower.includes("windows")) { + return <FaWindows className="h-4 w-4" />; + } + return null; +}; + +const getEditionBadgeStyle = (edition: string): string => { + const editionLower = edition.toLowerCase(); + + if (editionLower === "oss") { + return "bg-blue-500/20 text-blue-700 dark:bg-blue-500/30 dark:text-blue-300 hover:bg-blue-500/30"; + } + if (editionLower === "enterprise") { + return "bg-yellow-500/20 text-yellow-700 dark:bg-yellow-500/30 dark:text-yellow-300 hover:bg-yellow-500/30"; + } + return ""; // default badge style +}; + +export function VersionInformation({ + build, + edition, + os, + arch, +}: VersionInformationProps) { + const osIcon = getOSIcon(os); + + return ( + <Card> + <CardHeader> + <CardTitle>Version Information</CardTitle> + </CardHeader> + <CardContent> + <div className="grid grid-cols-2 gap-4"> + <div className="space-y-2"> + <div className="space-y-2"> + <Label>Version</Label> + <p className="text-sm">{build.version}</p> + </div> + <div className="space-y-2"> + <Label>Branch</Label> + <p className="text-sm">{build.branch}</p> + </div> + <div className="space-y-2"> + <Label>Go Version</Label> + <p className="text-sm">{build.goVersion}</p> + </div> + </div> + <div className="space-y-2"> + <div className="space-y-2"> + <Label>Edition</Label> + <div> + <Badge className={getEditionBadgeStyle(edition)}> + {edition.toUpperCase()} + </Badge> + </div> + </div> + <div className="space-y-2"> + <Label>Architecture</Label> + <p className="text-sm">{arch}</p> + </div> + <div className="space-y-2"> + <Label>OS</Label> + <div className="flex items-center gap-2"> + {osIcon} + <p className="text-sm">{os}</p> + </div> + </div> + </div> + </div> + </CardContent> + </Card> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/partition-ring-filters.tsx b/pkg/ui/frontend/src/components/ring/partition-ring-filters.tsx new file mode 100644 index 0000000000000..c31802c2ff7c0 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/partition-ring-filters.tsx @@ -0,0 +1,97 @@ +import { Input } from "@/components/ui/input"; +import { MultiSelect, Option } from "@/components/common/multi-select"; +import { PartitionInstance, PartitionStates } from "@/types/ring"; +import { parseZoneFromOwner } from "@/lib/ring-utils"; + +interface PartitionRingFiltersProps { + idFilter: string[]; + onIdFilterChange: (value: string[]) => void; + stateFilter: string[]; + onStateFilterChange: (value: string[]) => void; + zoneFilter: string[]; + onZoneFilterChange: (value: string[]) => void; + ownerFilter: string; + onOwnerFilterChange: (value: string) => void; + uniqueStates: string[]; + uniqueZones: string[]; + partitions: PartitionInstance[]; +} + +export function PartitionRingFilters({ + idFilter, + onIdFilterChange, + stateFilter, + onStateFilterChange, + zoneFilter, + onZoneFilterChange, + ownerFilter, + onOwnerFilterChange, + uniqueStates, + partitions, +}: PartitionRingFiltersProps) { + // Create options for each filter type + const stateOptions: Option[] = uniqueStates.map((state) => ({ + value: state, + label: PartitionStates[parseInt(state) as keyof typeof PartitionStates], + })); + + // Get unique zones from all owners + const allZones = new Set<string>(); + partitions.forEach((partition) => { + partition.owner_ids.forEach((owner) => { + const zone = parseZoneFromOwner(owner); + if (zone) allZones.add(zone); + }); + }); + + const zoneOptions: Option[] = Array.from(allZones) + .sort() + .map((zone) => ({ + value: zone, + label: zone, + })); + + // Get unique partition IDs + const uniquePartitions = Array.from( + new Set(partitions.map((p) => p.id.toString())) + ).sort((a, b) => parseInt(a) - parseInt(b)); + + const partitionOptions: Option[] = uniquePartitions.map((id) => ({ + value: id, + label: `Partition ${id}`, + })); + + return ( + <div className="flex flex-wrap gap-4"> + <div className="flex-1 min-w-[200px]"> + <Input + placeholder="Filter by owner name..." + value={ownerFilter} + onChange={(e) => onOwnerFilterChange(e.target.value)} + className="max-w-sm" + /> + </div> + <MultiSelect + options={stateOptions} + selected={stateFilter} + onChange={onStateFilterChange} + placeholder="Filter by state" + className="w-[200px]" + /> + <MultiSelect + options={zoneOptions} + selected={zoneFilter} + onChange={onZoneFilterChange} + placeholder="Filter by zone" + className="w-[200px]" + /> + <MultiSelect + options={partitionOptions} + selected={idFilter} + onChange={onIdFilterChange} + placeholder="Filter by partition ID" + className="w-[200px]" + /> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/partition-ring-table.tsx b/pkg/ui/frontend/src/components/ring/partition-ring-table.tsx new file mode 100644 index 0000000000000..fe5d8f3d0c62a --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/partition-ring-table.tsx @@ -0,0 +1,335 @@ +import { useMemo } from "react"; +import { Link } from "react-router-dom"; +import { PartitionInstance } from "@/types/ring"; +import { + formatTimestamp, + formatRelativeTime, + getZoneColors, +} from "@/lib/ring-utils"; +import { cn } from "@/lib/utils"; +import { Checkbox } from "@/components/ui/checkbox"; +import { ArrowRightCircle } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { DataTableColumnHeader } from "@/components/common/data-table-column-header"; +import { RateWithTrend } from "./rate-with-trend"; + +export type SortField = + | "id" + | "state" + | "owner" + | "timestamp" + | "zone" + | "uncompressed_rate" + | "compressed_rate"; + +interface SelectAllCheckboxProps { + allPartitions: PartitionInstance[]; + selectedIds: Set<number>; + onChange: (selectedIds: Set<number>) => void; +} + +function SelectAllCheckbox({ + allPartitions, + selectedIds, + onChange, +}: SelectAllCheckboxProps) { + // Get unique partition IDs from all partitions + const uniquePartitionIds = useMemo(() => { + return Array.from(new Set(allPartitions.map((p) => p.id))); + }, [allPartitions]); + + const allSelected = uniquePartitionIds.every((id) => selectedIds.has(id)); + + const handleChange = () => { + if (allSelected) { + // Unselect all partitions + onChange(new Set()); + } else { + // Select all unique partitions + onChange(new Set(uniquePartitionIds)); + } + }; + + return ( + <Checkbox + checked={uniquePartitionIds.length > 0 && allSelected} + onCheckedChange={handleChange} + aria-label="Select all partitions" + /> + ); +} + +function getStateColors(state: number): string { + switch (state) { + case 2: // Active + return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"; + case 1: // Pending + return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"; + case 3: // Inactive + return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"; + case 4: // Deleted + return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"; + default: // Unknown + return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"; + } +} + +interface PartitionRingTableProps { + partitions: PartitionInstance[]; + selectedPartitions: Set<number>; + onSelectPartition: (id: number) => void; + sortField: SortField; + sortDirection: "asc" | "desc"; + onSort: (field: SortField) => void; + onStateChange: (partitionIds: number[], newState: number) => void; + previousPartitions?: PartitionInstance[]; +} + +const STATE_OPTIONS = [ + { value: 1, label: "Pending" }, + { value: 2, label: "Active" }, + { value: 3, label: "Inactive" }, + { value: 4, label: "Deleted" }, +]; + +export function PartitionRingTable({ + partitions, + selectedPartitions, + onSelectPartition, + sortField, + sortDirection, + onSort, +}: PartitionRingTableProps) { + // Sort partitions according to the current sort field + const sortedPartitions = useMemo(() => { + return [...partitions].sort((a, b) => { + let comparison = 0; + switch (sortField) { + case "uncompressed_rate": { + comparison = (a.uncompressedRate || 0) - (b.uncompressedRate || 0); + break; + } + case "compressed_rate": { + comparison = (a.compressedRate || 0) - (b.compressedRate || 0); + break; + } + case "id": + comparison = a.id - b.id; + break; + case "state": + comparison = a.state - b.state; + break; + case "owner": + comparison = a.owner_id?.localeCompare(b.owner_id || "") || 0; + break; + case "zone": + comparison = (a.zone || "").localeCompare(b.zone || ""); + break; + case "timestamp": + comparison = + new Date(a.state_timestamp).getTime() - + new Date(b.state_timestamp).getTime(); + break; + } + return sortDirection === "asc" ? comparison : -comparison; + }); + }, [partitions, sortField, sortDirection]); + + return ( + <> + <Table> + <TableHeader> + <TableRow className="hover:bg-transparent"> + <TableHead className="w-[50px]"> + <SelectAllCheckbox + allPartitions={partitions} + selectedIds={selectedPartitions} + onChange={(newSelection) => { + const uniqueIds = new Set(partitions.map((p) => p.id)); + uniqueIds.forEach((id) => { + if (newSelection.has(id) !== selectedPartitions.has(id)) { + onSelectPartition(id); + } + }); + }} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<SortField> + title="Owner" + field="owner" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="Zone" + field="zone" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[100px]"> + <DataTableColumnHeader<SortField> + title="Partition ID" + field="id" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="State" + field="state" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<SortField> + title="Last Update" + field="timestamp" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="Uncompressed Rate" + field="uncompressed_rate" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="Compressed Rate" + field="compressed_rate" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[100px]" /> + </TableRow> + </TableHeader> + <TableBody> + {sortedPartitions.map((partition) => { + return ( + <TableRow key={`${partition.owner_id}-${partition.id}`}> + <TableCell> + <Checkbox + checked={selectedPartitions.has(partition.id)} + onCheckedChange={() => onSelectPartition(partition.id)} + aria-label={`Select partition ${partition.id}`} + /> + </TableCell> + <TableCell className="font-medium"> + <Link + to={`/nodes/${partition.owner_id}`} + className="hover:underline" + > + {partition.owner_id} + </Link> + </TableCell> + <TableCell> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium", + getZoneColors(partition.zone || "") + )} + > + {partition.zone || "-"} + </span> + </TableCell> + <TableCell> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium", + partition.corrupted + ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200" + : "bg-muted" + )} + title={partition.corrupted ? "Corrupted" : undefined} + > + {partition.id} + </span> + </TableCell> + <TableCell> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium", + getStateColors(partition.state) + )} + > + {STATE_OPTIONS.find((opt) => opt.value === partition.state) + ?.label || "Unknown"} + </span> + </TableCell> + <TableCell> + <span + title={formatTimestamp(partition.state_timestamp)} + className="text-muted-foreground" + > + {formatRelativeTime(partition.state_timestamp)} + </span> + </TableCell> + <TableCell> + <RateWithTrend + currentRate={partition.uncompressedRate || 0} + className="text-muted-foreground inline-flex items-center" + /> + </TableCell> + <TableCell> + <RateWithTrend + currentRate={partition.compressedRate || 0} + className="text-muted-foreground inline-flex items-center" + /> + </TableCell> + <TableCell> + <div className="flex items-center gap-2"> + <Link + to={`/nodes/${partition.owner_id}`} + className="hover:underline" + > + <Button + variant="ghost" + size="icon" + className="h-8 w-8" + title="View instance details" + > + <ArrowRightCircle className="h-4 w-4" /> + </Button> + </Link> + </div> + </TableCell> + </TableRow> + ); + })} + {sortedPartitions.length === 0 && ( + <TableRow> + <TableCell colSpan={7} className="h-24 text-center"> + <div className="text-muted-foreground">No partitions found</div> + </TableCell> + </TableRow> + )} + </TableBody> + </Table> + </> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/partition-state-distribution-chart.tsx b/pkg/ui/frontend/src/components/ring/partition-state-distribution-chart.tsx new file mode 100644 index 0000000000000..ef6d53e56da16 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/partition-state-distribution-chart.tsx @@ -0,0 +1,100 @@ +import { useMemo } from "react"; +import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts"; +import { PartitionInstance, PartitionStates } from "@/types/ring"; + +// Map states to their corresponding hex colors +const getStateColor = (state: number): string => { + switch (state) { + case 2: // Active + return "#22c55e"; // green-500 + case 1: // Pending + return "#3b82f6"; // blue-500 + case 3: // Inactive + return "#eab308"; // yellow-500 + case 4: // Deleted + return "#ef4444"; // red-500 + default: // Unknown + return "#6b7280"; // gray-500 + } +}; + +interface PartitionStateDistributionChartProps { + partitions: PartitionInstance[]; +} + +export function PartitionStateDistributionChart({ + partitions, +}: PartitionStateDistributionChartProps) { + const data = useMemo(() => { + const stateCounts = new Map<number, number>(); + + partitions.forEach((partition) => { + const state = partition.state; + stateCounts.set(state, (stateCounts.get(state) || 0) + 1); + }); + + return Array.from(stateCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([state, value]) => ({ + name: PartitionStates[state as keyof typeof PartitionStates], + value, + color: getStateColor(state), + })); + }, [partitions]); + + const totalPartitions = useMemo(() => { + return partitions.length; + }, [partitions]); + + if (data.length === 0) { + return null; + } + + return ( + <div className="w-full h-[120px] relative"> + <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"> + <div className="text-xl font-bold">{totalPartitions}</div> + <div className="text-xs text-muted-foreground">Partitions</div> + </div> + <ResponsiveContainer width="100%" height="100%"> + <PieChart> + <Pie + data={data} + cx="50%" + cy="50%" + labelLine={false} + outerRadius={60} + innerRadius={42} + dataKey="value" + paddingAngle={1} + strokeWidth={1} + > + {data.map((entry) => ( + <Cell + key={`cell-${entry.name}`} + fill={entry.color} + stroke="hsl(var(--background))" + /> + ))} + </Pie> + <Tooltip + content={({ active, payload }) => { + if (!active || !payload || !payload[0]) return null; + const data = payload[0].payload; + return ( + <div className="bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2"> + <div + className="w-2.5 h-2.5 rounded-sm" + style={{ backgroundColor: data.color }} + /> + <span className="text-sm font-medium">{data.name}</span> + <span className="text-sm font-semibold">{data.value}</span> + </div> + ); + }} + /> + </PieChart> + </ResponsiveContainer> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/rate-with-trend.tsx b/pkg/ui/frontend/src/components/ring/rate-with-trend.tsx new file mode 100644 index 0000000000000..4266e521a8eda --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/rate-with-trend.tsx @@ -0,0 +1,62 @@ +import { useMemo, useRef, useEffect } from "react"; +import { ArrowUpCircle, ArrowDownCircle } from "lucide-react"; +import { formatBytes } from "@/lib/ring-utils"; + +interface RateWithTrendProps { + currentRate: number; + label?: string; + className?: string; +} + +function getRateTrend(current: number, previous: number): "up" | "down" | null { + if (current === undefined || previous === undefined) { + return null; + } + + // Add a small threshold to avoid showing changes for tiny fluctuations + const threshold = 0.1; // 10% threshold + const percentChange = Math.abs((current - previous) / previous); + + if (percentChange < threshold) { + return null; + } + + return current > previous ? "up" : "down"; +} + +function TrendIndicator({ trend }: { trend: "up" | "down" | null }) { + if (!trend) return null; + + return trend === "up" ? ( + <ArrowUpCircle className="inline h-4 w-4 text-green-500 ml-1" /> + ) : ( + <ArrowDownCircle className="inline h-4 w-4 text-red-500 ml-1" /> + ); +} + +export function RateWithTrend({ + currentRate, + label, + className, +}: RateWithTrendProps) { + const previousRateRef = useRef(currentRate); + const trend = useMemo( + () => getRateTrend(currentRate, previousRateRef.current), + [currentRate] + ); + + useEffect(() => { + const timeoutId = setTimeout(() => { + previousRateRef.current = currentRate; + }, 2000); // Update previous rate after a delay to show trend + + return () => clearTimeout(timeoutId); + }, [currentRate]); + + return ( + <span className={className}> + {formatBytes(currentRate)}/s{label && ` ${label}`} + <TrendIndicator trend={trend} /> + </span> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/ring-filters.tsx b/pkg/ui/frontend/src/components/ring/ring-filters.tsx new file mode 100644 index 0000000000000..efac975ebfd87 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/ring-filters.tsx @@ -0,0 +1,63 @@ +import { Search } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { MultiSelect } from "../common/multi-select"; + +interface RingFiltersProps { + idFilter: string; + onIdFilterChange: (value: string) => void; + stateFilter: string[]; + onStateFilterChange: (value: string[]) => void; + zoneFilter: string[]; + onZoneFilterChange: (value: string[]) => void; + uniqueStates: string[]; + uniqueZones: string[]; +} + +export function RingFilters({ + idFilter, + onIdFilterChange, + stateFilter, + onStateFilterChange, + zoneFilter, + onZoneFilterChange, + uniqueStates, + uniqueZones, +}: RingFiltersProps) { + return ( + <div className="flex items-center gap-4"> + <div className="relative flex-1"> + <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" /> + <Input + placeholder="Filter by ID..." + value={idFilter} + onChange={(e) => onIdFilterChange(e.target.value)} + className="pl-8" + /> + </div> + {uniqueStates.length > 0 && ( + <MultiSelect + options={uniqueStates.map((state) => ({ + value: state, + label: state, + }))} + selected={stateFilter} + onChange={onStateFilterChange} + placeholder="Filter by State" + className="w-[180px]" + /> + )} + {uniqueZones.length > 0 && ( + <MultiSelect + options={uniqueZones.map((zone) => ({ + value: zone, + label: zone, + }))} + selected={zoneFilter} + onChange={onZoneFilterChange} + placeholder="Filter by Zone" + className="w-[180px]" + /> + )} + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/ring-instance-table.tsx b/pkg/ui/frontend/src/components/ring/ring-instance-table.tsx new file mode 100644 index 0000000000000..194748d58a087 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/ring-instance-table.tsx @@ -0,0 +1,262 @@ +import { Link } from "react-router-dom"; +import { RingInstance } from "@/types/ring"; +import { + formatRelativeTime, + formatTimestamp, + getStateColors, + getZoneColors, +} from "@/lib/ring-utils"; +import { cn } from "@/lib/utils"; +import { Checkbox } from "@/components/ui/checkbox"; +import { ArrowRightCircle } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { DataTableColumnHeader } from "@/components/common/data-table-column-header"; +import { Progress } from "@/components/ui/progress"; + +export type SortField = + | "id" + | "state" + | "address" + | "zone" + | "timestamp" + | "ownership" + | "tokens"; + +interface SelectAllCheckboxProps { + visibleIds: string[]; + selectedIds: Set<string>; + onChange: (selectedIds: Set<string>) => void; +} + +function SelectAllCheckbox({ + visibleIds, + selectedIds, + onChange, +}: SelectAllCheckboxProps) { + const allVisibleSelected = visibleIds.every((id) => selectedIds.has(id)); + + const handleChange = () => { + const visibleIdsSet = new Set(visibleIds); + if (allVisibleSelected) { + // Keep only the instances that are not currently visible + onChange( + new Set([...selectedIds].filter((id) => !visibleIdsSet.has(id))) + ); + } else { + // Add all visible instances to the current selection + onChange(new Set([...selectedIds, ...visibleIds])); + } + }; + + return ( + <Checkbox + checked={visibleIds.length > 0 && allVisibleSelected} + onCheckedChange={handleChange} + aria-label="Select all visible instances" + /> + ); +} + +interface RingInstanceTableProps { + instances: RingInstance[]; + selectedInstances: Set<string>; + onSelectInstance: (instanceId: string) => void; + sortField: SortField; + sortDirection: "asc" | "desc"; + onSort: (field: SortField) => void; + showTokens?: boolean; +} + +export function RingInstanceTable({ + instances, + selectedInstances, + onSelectInstance, + sortField, + sortDirection, + onSort, + showTokens = false, +}: RingInstanceTableProps) { + return ( + <Table> + <TableHeader> + <TableRow className="hover:bg-transparent"> + <TableHead className="w-[50px]"> + <SelectAllCheckbox + visibleIds={instances.map((instance) => instance.id)} + selectedIds={selectedInstances} + onChange={(newSelection) => { + instances.forEach((instance) => { + if ( + newSelection.has(instance.id) !== + selectedInstances.has(instance.id) + ) { + onSelectInstance(instance.id); + } + }); + }} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<SortField> + title="ID" + field="id" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="State" + field="state" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead> + <DataTableColumnHeader<SortField> + title="Address" + field="address" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + {showTokens && ( + <TableHead className="w-[200px]"> + <DataTableColumnHeader<SortField> + title="Ownership" + field="ownership" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + )} + <TableHead className="w-[150px]"> + <DataTableColumnHeader<SortField> + title="Zone" + field="zone" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<SortField> + title="Last Heartbeat" + field="timestamp" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[50px]" /> + </TableRow> + </TableHeader> + <TableBody> + {instances.map((instance) => { + const ownership = showTokens ? instance.ownership : 0; + return ( + <TableRow key={instance.id}> + <TableCell> + <Checkbox + checked={selectedInstances.has(instance.id)} + onCheckedChange={() => onSelectInstance(instance.id)} + aria-label={`Select instance ${instance.id}`} + /> + </TableCell> + <TableCell className="font-medium"> + <Link to={`/nodes/${instance.id}`} className="hover:underline"> + {instance.id} + </Link> + </TableCell> + <TableCell> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium", + getStateColors(instance.state) + )} + > + {instance.state} + </span> + </TableCell> + <TableCell>{instance.address}</TableCell> + {showTokens && ( + <TableCell> + <div className="space-y-1"> + <div className="flex justify-between text-xs"> + <span>{ownership}</span> + <span className="text-muted-foreground"> + {instance.tokens.length} tokens + </span> + </div> + <Progress + value={ + typeof ownership === "number" + ? ownership + : Number(ownership.slice(0, -1)) + } + className="h-2" + /> + </div> + </TableCell> + )} + <TableCell> + {instance.zone ? ( + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium", + getZoneColors(instance.zone) + )} + > + {instance.zone} + </span> + ) : ( + <span className="text-muted-foreground">-</span> + )} + </TableCell> + <TableCell> + <span + title={formatTimestamp(instance.timestamp)} + className="text-muted-foreground" + > + {formatRelativeTime(instance.timestamp)} + </span> + </TableCell> + <TableCell> + <Button + variant="ghost" + size="icon" + asChild + className="h-8 w-8" + title="View instance details" + > + <Link to={`/nodes/${instance.id}`}> + <ArrowRightCircle className="h-4 w-4" /> + </Link> + </Button> + </TableCell> + </TableRow> + ); + })} + {instances.length === 0 && ( + <TableRow> + <TableCell colSpan={7} className="h-24 text-center"> + <div className="text-muted-foreground">No instances found</div> + </TableCell> + </TableRow> + )} + </TableBody> + </Table> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/ring-state-distribution-chart.tsx b/pkg/ui/frontend/src/components/ring/ring-state-distribution-chart.tsx new file mode 100644 index 0000000000000..9687f234faf70 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/ring-state-distribution-chart.tsx @@ -0,0 +1,102 @@ +import { useMemo } from "react"; +import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts"; +import { RingInstance } from "@/types/ring"; + +// Map states to their corresponding hex colors +const getStateColor = (state: string): string => { + switch (state) { + case "ACTIVE": + return "#22c55e"; // green-500 + case "LEAVING": + return "#eab308"; // yellow-500 + case "PENDING": + return "#3b82f6"; // blue-500 + case "JOINING": + return "#a855f7"; // purple-500 + case "LEFT": + return "#ef4444"; // red-500 + default: + return "#6b7280"; // gray-500 + } +}; + +interface RingStateDistributionChartProps { + instances: RingInstance[]; +} + +export function RingStateDistributionChart({ + instances, +}: RingStateDistributionChartProps) { + const data = useMemo(() => { + const stateCounts = new Map<string, number>(); + + instances.forEach((instance) => { + const state = instance.state || "unknown"; + stateCounts.set(state, (stateCounts.get(state) || 0) + 1); + }); + + return Array.from(stateCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([name, value]) => ({ + name, + value, + color: getStateColor(name), + })); + }, [instances]); + + const totalInstances = useMemo(() => { + return instances.length; + }, [instances]); + + if (data.length === 0) { + return null; + } + + return ( + <div className="w-full h-[120px] relative"> + <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"> + <div className="text-xl font-bold">{totalInstances}</div> + <div className="text-xs text-muted-foreground">Instances</div> + </div> + <ResponsiveContainer width="100%" height="100%"> + <PieChart> + <Pie + data={data} + cx="50%" + cy="50%" + labelLine={false} + outerRadius={60} + innerRadius={42} + dataKey="value" + paddingAngle={1} + strokeWidth={1} + > + {data.map((entry) => ( + <Cell + key={`cell-${entry.name}`} + fill={entry.color} + stroke="hsl(var(--background))" + /> + ))} + </Pie> + <Tooltip + content={({ active, payload }) => { + if (!active || !payload || !payload[0]) return null; + const data = payload[0].payload; + return ( + <div className="bg-background border rounded-lg shadow-lg px-3 py-2 flex items-center gap-2"> + <div + className="w-2.5 h-2.5 rounded-sm" + style={{ backgroundColor: data.color }} + /> + <span className="text-sm font-medium">{data.name}</span> + <span className="text-sm font-semibold">{data.value}</span> + </div> + ); + }} + /> + </PieChart> + </ResponsiveContainer> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/ring/ring-stats.tsx b/pkg/ui/frontend/src/components/ring/ring-stats.tsx new file mode 100644 index 0000000000000..0739d7a3b6109 --- /dev/null +++ b/pkg/ui/frontend/src/components/ring/ring-stats.tsx @@ -0,0 +1,87 @@ +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Loader2, Pause } from "lucide-react"; +import { cn } from "@/lib/utils"; + +interface RingStatsProps { + nextRefresh: number; + isPaused: boolean; + onRefresh: () => void; + instancesByState: Record<string, number>; +} + +export function RingStats({ + nextRefresh, + isPaused, + onRefresh, + instancesByState, +}: RingStatsProps) { + const activeInstances = instancesByState["ACTIVE"] || 0; + const inactiveInstances = Object.entries(instancesByState) + .filter(([state]) => state !== "ACTIVE") + .reduce((sum, [_, count]) => sum + count, 0); + + return ( + <div className="grid grid-cols-1 md:grid-cols-3 gap-4"> + <Card> + <CardHeader className="pb-2"> + <div className="flex items-center justify-between"> + <CardTitle className="text-sm font-medium text-muted-foreground"> + Next Ring Update + </CardTitle> + <Button + variant="ghost" + size="sm" + onClick={onRefresh} + className="h-8 w-8 p-0" + title={isPaused ? "Auto-refresh paused" : "Refresh ring data"} + > + {isPaused ? ( + <Pause className="h-4 w-4 text-orange-500" /> + ) : ( + <Loader2 className="h-4 w-4 text-green-500 animate-spin" /> + )} + <span className="sr-only"> + {isPaused ? "Auto-refresh paused" : "Refresh ring data"} + </span> + </Button> + </div> + </CardHeader> + <CardContent> + <div + className={cn( + "text-2xl font-bold", + isPaused ? "text-orange-500" : "" + )} + > + {isPaused ? "Paused" : `${nextRefresh}s`} + </div> + </CardContent> + </Card> + <Card> + <CardHeader className="pb-2"> + <CardTitle className="text-sm font-medium text-muted-foreground"> + Active Instances + </CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-green-600 dark:text-green-400"> + {activeInstances} + </div> + </CardContent> + </Card> + <Card> + <CardHeader className="pb-2"> + <CardTitle className="text-sm font-medium text-muted-foreground"> + Inactive Instances + </CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-red-600 dark:text-red-400"> + {inactiveInstances} + </div> + </CardContent> + </Card> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/shared/breadcrumb-nav.tsx b/pkg/ui/frontend/src/components/shared/breadcrumb-nav.tsx new file mode 100644 index 0000000000000..22a13fdf5f0f8 --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/breadcrumb-nav.tsx @@ -0,0 +1,43 @@ +import * as React from "react"; +import useBreadcrumbs from "use-react-router-breadcrumbs"; +import { Link } from "react-router-dom"; +import { + Breadcrumb, + BreadcrumbItem, + BreadcrumbLink, + BreadcrumbList, + BreadcrumbPage, + BreadcrumbSeparator, +} from "@/components/ui/breadcrumb"; +import { routes } from "@/config/routes"; + +export function BreadcrumbNav() { + const breadcrumbs = useBreadcrumbs(routes, { + disableDefaults: true, + }); + + return ( + <Breadcrumb> + <BreadcrumbList> + {breadcrumbs.map(({ match, breadcrumb }, index) => ( + <React.Fragment key={match.pathname}> + <BreadcrumbItem className={index === 0 ? "hidden md:block" : ""}> + {index === breadcrumbs.length - 1 ? ( + <BreadcrumbPage>{breadcrumb}</BreadcrumbPage> + ) : ( + <BreadcrumbLink asChild> + <Link to={match.pathname}>{breadcrumb}</Link> + </BreadcrumbLink> + )} + </BreadcrumbItem> + {index < breadcrumbs.length - 1 && ( + <BreadcrumbSeparator + className={index === 0 ? "hidden md:block" : ""} + /> + )} + </React.Fragment> + ))} + </BreadcrumbList> + </Breadcrumb> + ); +} diff --git a/pkg/ui/frontend/src/components/shared/errors/error-boundary.tsx b/pkg/ui/frontend/src/components/shared/errors/error-boundary.tsx new file mode 100644 index 0000000000000..4b2031674365b --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/errors/error-boundary.tsx @@ -0,0 +1,51 @@ +import React from "react"; + +interface Props { + children: React.ReactNode; +} + +interface State { + hasError: boolean; + error?: Error; +} + +export class ErrorBoundary extends React.Component<Props, State> { + constructor(props: Props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error: Error): State { + return { + hasError: true, + error, + }; + } + + render() { + if (this.state.hasError) { + return ( + <div className="min-h-screen flex items-center justify-center p-4"> + <div className="bg-destructive/10 p-6 rounded-lg max-w-2xl w-full"> + <h2 className="text-xl font-semibold text-destructive mb-4"> + Something went wrong + </h2> + <div className="bg-background/50 p-4 rounded-md"> + <pre className="text-sm overflow-auto"> + {this.state.error?.message} + </pre> + </div> + <button + className="mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90" + onClick={() => window.location.reload()} + > + Reload Page + </button> + </div> + </div> + ); + } + + return this.props.children; + } +} diff --git a/pkg/ui/frontend/src/components/shared/errors/index.ts b/pkg/ui/frontend/src/components/shared/errors/index.ts new file mode 100644 index 0000000000000..90e954fb2ee32 --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/errors/index.ts @@ -0,0 +1 @@ +export * from "./error-boundary"; diff --git a/pkg/ui/frontend/src/components/shared/errors/not-found.tsx b/pkg/ui/frontend/src/components/shared/errors/not-found.tsx new file mode 100644 index 0000000000000..f26db2102d05e --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/errors/not-found.tsx @@ -0,0 +1,99 @@ +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Home, RotateCcw } from "lucide-react"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { cn } from "@/lib/utils"; + +export function NotFound() { + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const pathToShow = searchParams.get("path") || window.location.pathname; + + return ( + <div className="flex min-h-[calc(100vh-12rem)] items-center justify-center bg-dot-pattern px-4"> + <Card className="w-full max-w-[450px] overflow-hidden"> + <CardHeader className="text-center pb-0"> + <div className="relative mb-8"> + <div className="absolute inset-0 flex items-center justify-center"></div> + <div className="relative flex justify-center py-4"> + <div className="bg-white dark:bg-transparent p-2 rounded-full"> + <img + src="https://grafana.com/media/docs/loki/logo-grafana-loki.png" + alt="Loki Logo" + className={cn( + "h-16 w-16 sm:h-24 sm:w-24", + "rotate-180 animate-swing hover:animate-shake cursor-pointer transition-all duration-300" + )} + /> + </div> + </div> + </div> + <CardTitle className="text-5xl sm:text-7xl font-bold bg-gradient-to-r from-primary to-primary/50 bg-clip-text text-transparent"> + 404 + </CardTitle> + </CardHeader> + <CardContent className="text-center space-y-3 pb-8"> + <h2 className="text-xl sm:text-2xl font-semibold tracking-tight"> + Oops! Page Not Found + </h2> + <p className="text-sm sm:text-base text-muted-foreground"> + Even with our powerful log aggregation, we couldn't find this page + in any of our streams! + </p> + <p className="text-xs sm:text-sm text-muted-foreground italic"> + Error: LogQL query returned 0 results for label{" "} + {`{path="${pathToShow}"}`} + </p> + </CardContent> + <CardFooter className="flex justify-center gap-4 pb-8"> + <Button + variant="outline" + onClick={() => navigate(-1)} + className="gap-2 group" + size="sm" + > + <RotateCcw className="h-4 w-4 group-hover:animate-spin" /> + Go Back + </Button> + <Button + onClick={() => navigate(`/`)} + className="gap-2 group" + size="sm" + > + <Home className="h-4 w-4 group-hover:animate-bounce" /> + Go Home + </Button> + </CardFooter> + </Card> + <style> + {` + .bg-dot-pattern { + background-image: radial-gradient(circle at 1px 1px, hsl(var(--muted-foreground) / 0.1) 1px, transparent 0); + background-size: 32px 32px; + } + @keyframes shake { + 0%, 100% { transform: rotate(180deg); } + 25% { transform: rotate(170deg); } + 75% { transform: rotate(190deg); } + } + @keyframes swing { + 0%, 100% { transform: rotate(180deg); } + 50% { transform: rotate(190deg); } + } + .animate-swing { + animation: swing 1s ease-in-out infinite; + } + .animate-shake { + animation: shake 0.3s ease-in-out; + } + `} + </style> + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/shared/index.ts b/pkg/ui/frontend/src/components/shared/index.ts new file mode 100644 index 0000000000000..afd7f76866eaa --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/index.ts @@ -0,0 +1,3 @@ +export * from "./errors"; +export * from "./breadcrumb-nav"; +export * from "./route-breadcrumbs"; diff --git a/pkg/ui/frontend/src/components/shared/route-breadcrumbs.tsx b/pkg/ui/frontend/src/components/shared/route-breadcrumbs.tsx new file mode 100644 index 0000000000000..9a43d521315d6 --- /dev/null +++ b/pkg/ui/frontend/src/components/shared/route-breadcrumbs.tsx @@ -0,0 +1,11 @@ +import type { BreadcrumbComponentType } from "use-react-router-breadcrumbs"; + +export const NodeBreadcrumb: BreadcrumbComponentType = ({ match }) => { + const nodeName = match.params.nodeName; + return <span>{nodeName}</span>; +}; + +export const RingBreadcrumb: BreadcrumbComponentType = ({ match }) => { + const ringName = match.params.ringName; + return <span>{ringName}</span>; +}; diff --git a/pkg/ui/frontend/src/components/ui/alert.tsx b/pkg/ui/frontend/src/components/ui/alert.tsx new file mode 100644 index 0000000000000..5afd41d142c95 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/alert.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const alertVariants = cva( + "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7", + { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: + "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +const Alert = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants> +>(({ className, variant, ...props }, ref) => ( + <div + ref={ref} + role="alert" + className={cn(alertVariants({ variant }), className)} + {...props} + /> +)) +Alert.displayName = "Alert" + +const AlertTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLHeadingElement> +>(({ className, ...props }, ref) => ( + <h5 + ref={ref} + className={cn("mb-1 font-medium leading-none tracking-tight", className)} + {...props} + /> +)) +AlertTitle.displayName = "AlertTitle" + +const AlertDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLParagraphElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("text-sm [&_p]:leading-relaxed", className)} + {...props} + /> +)) +AlertDescription.displayName = "AlertDescription" + +export { Alert, AlertTitle, AlertDescription } diff --git a/pkg/ui/frontend/src/components/ui/badge.tsx b/pkg/ui/frontend/src/components/ui/badge.tsx new file mode 100644 index 0000000000000..e87d62bf1a2b2 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/badge.tsx @@ -0,0 +1,36 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", + { + variants: { + variant: { + default: + "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", + secondary: + "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", + destructive: + "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", + outline: "text-foreground", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +export interface BadgeProps + extends React.HTMLAttributes<HTMLDivElement>, + VariantProps<typeof badgeVariants> {} + +function Badge({ className, variant, ...props }: BadgeProps) { + return ( + <div className={cn(badgeVariants({ variant }), className)} {...props} /> + ) +} + +export { Badge, badgeVariants } diff --git a/pkg/ui/frontend/src/components/ui/breadcrumb.tsx b/pkg/ui/frontend/src/components/ui/breadcrumb.tsx new file mode 100644 index 0000000000000..60e6c96f72f03 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/breadcrumb.tsx @@ -0,0 +1,115 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { ChevronRight, MoreHorizontal } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Breadcrumb = React.forwardRef< + HTMLElement, + React.ComponentPropsWithoutRef<"nav"> & { + separator?: React.ReactNode + } +>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />) +Breadcrumb.displayName = "Breadcrumb" + +const BreadcrumbList = React.forwardRef< + HTMLOListElement, + React.ComponentPropsWithoutRef<"ol"> +>(({ className, ...props }, ref) => ( + <ol + ref={ref} + className={cn( + "flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5", + className + )} + {...props} + /> +)) +BreadcrumbList.displayName = "BreadcrumbList" + +const BreadcrumbItem = React.forwardRef< + HTMLLIElement, + React.ComponentPropsWithoutRef<"li"> +>(({ className, ...props }, ref) => ( + <li + ref={ref} + className={cn("inline-flex items-center gap-1.5", className)} + {...props} + /> +)) +BreadcrumbItem.displayName = "BreadcrumbItem" + +const BreadcrumbLink = React.forwardRef< + HTMLAnchorElement, + React.ComponentPropsWithoutRef<"a"> & { + asChild?: boolean + } +>(({ asChild, className, ...props }, ref) => { + const Comp = asChild ? Slot : "a" + + return ( + <Comp + ref={ref} + className={cn("transition-colors hover:text-foreground", className)} + {...props} + /> + ) +}) +BreadcrumbLink.displayName = "BreadcrumbLink" + +const BreadcrumbPage = React.forwardRef< + HTMLSpanElement, + React.ComponentPropsWithoutRef<"span"> +>(({ className, ...props }, ref) => ( + <span + ref={ref} + role="link" + aria-disabled="true" + aria-current="page" + className={cn("font-normal text-foreground", className)} + {...props} + /> +)) +BreadcrumbPage.displayName = "BreadcrumbPage" + +const BreadcrumbSeparator = ({ + children, + className, + ...props +}: React.ComponentProps<"li">) => ( + <li + role="presentation" + aria-hidden="true" + className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)} + {...props} + > + {children ?? <ChevronRight />} + </li> +) +BreadcrumbSeparator.displayName = "BreadcrumbSeparator" + +const BreadcrumbEllipsis = ({ + className, + ...props +}: React.ComponentProps<"span">) => ( + <span + role="presentation" + aria-hidden="true" + className={cn("flex h-9 w-9 items-center justify-center", className)} + {...props} + > + <MoreHorizontal className="h-4 w-4" /> + <span className="sr-only">More</span> + </span> +) +BreadcrumbEllipsis.displayName = "BreadcrumbElipssis" + +export { + Breadcrumb, + BreadcrumbList, + BreadcrumbItem, + BreadcrumbLink, + BreadcrumbPage, + BreadcrumbSeparator, + BreadcrumbEllipsis, +} diff --git a/pkg/ui/frontend/src/components/ui/button.tsx b/pkg/ui/frontend/src/components/ui/button.tsx new file mode 100644 index 0000000000000..65d4fcd9ca742 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/button.tsx @@ -0,0 +1,57 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", + { + variants: { + variant: { + default: + "bg-primary text-primary-foreground shadow hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", + outline: + "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2", + sm: "h-8 rounded-md px-3 text-xs", + lg: "h-10 rounded-md px-8", + icon: "h-9 w-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes<HTMLButtonElement>, + VariantProps<typeof buttonVariants> { + asChild?: boolean +} + +const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + <Comp + className={cn(buttonVariants({ variant, size, className }))} + ref={ref} + {...props} + /> + ) + } +) +Button.displayName = "Button" + +export { Button, buttonVariants } diff --git a/pkg/ui/frontend/src/components/ui/card.tsx b/pkg/ui/frontend/src/components/ui/card.tsx new file mode 100644 index 0000000000000..cabfbfc59d955 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/card.tsx @@ -0,0 +1,76 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn( + "rounded-xl border bg-card text-card-foreground shadow", + className + )} + {...props} + /> +)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("flex flex-col space-y-1.5 p-6", className)} + {...props} + /> +)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("font-semibold leading-none tracking-tight", className)} + {...props} + /> +)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("text-sm text-muted-foreground", className)} + {...props} + /> +)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div ref={ref} className={cn("p-6 pt-0", className)} {...props} /> +)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("flex items-center p-6 pt-0", className)} + {...props} + /> +)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } diff --git a/pkg/ui/frontend/src/components/ui/chart.tsx b/pkg/ui/frontend/src/components/ui/chart.tsx new file mode 100644 index 0000000000000..aedf2b2a1e971 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/chart.tsx @@ -0,0 +1,363 @@ +import * as React from "react" +import * as RechartsPrimitive from "recharts" + +import { cn } from "@/lib/utils" + +// Format: { THEME_NAME: CSS_SELECTOR } +const THEMES = { light: "", dark: ".dark" } as const + +export type ChartConfig = { + [k in string]: { + label?: React.ReactNode + icon?: React.ComponentType + } & ( + | { color?: string; theme?: never } + | { color?: never; theme: Record<keyof typeof THEMES, string> } + ) +} + +type ChartContextProps = { + config: ChartConfig +} + +const ChartContext = React.createContext<ChartContextProps | null>(null) + +function useChart() { + const context = React.useContext(ChartContext) + + if (!context) { + throw new Error("useChart must be used within a <ChartContainer />") + } + + return context +} + +const ChartContainer = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { + config: ChartConfig + children: React.ComponentProps< + typeof RechartsPrimitive.ResponsiveContainer + >["children"] + } +>(({ id, className, children, config, ...props }, ref) => { + const uniqueId = React.useId() + const chartId = `chart-${id || uniqueId.replace(/:/g, "")}` + + return ( + <ChartContext.Provider value={{ config }}> + <div + data-chart={chartId} + ref={ref} + className={cn( + "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none", + className + )} + {...props} + > + <ChartStyle id={chartId} config={config} /> + <RechartsPrimitive.ResponsiveContainer> + {children} + </RechartsPrimitive.ResponsiveContainer> + </div> + </ChartContext.Provider> + ) +}) +ChartContainer.displayName = "Chart" + +const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { + const colorConfig = Object.entries(config).filter( + ([, config]) => config.theme || config.color + ) + + if (!colorConfig.length) { + return null + } + + return ( + <style + dangerouslySetInnerHTML={{ + __html: Object.entries(THEMES) + .map( + ([theme, prefix]) => ` +${prefix} [data-chart=${id}] { +${colorConfig + .map(([key, itemConfig]) => { + const color = + itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || + itemConfig.color + return color ? ` --color-${key}: ${color};` : null + }) + .join("\n")} +} +` + ) + .join("\n"), + }} + /> + ) +} + +const ChartTooltip = RechartsPrimitive.Tooltip + +const ChartTooltipContent = React.forwardRef< + HTMLDivElement, + React.ComponentProps<typeof RechartsPrimitive.Tooltip> & + React.ComponentProps<"div"> & { + hideLabel?: boolean + hideIndicator?: boolean + indicator?: "line" | "dot" | "dashed" + nameKey?: string + labelKey?: string + } +>( + ( + { + active, + payload, + className, + indicator = "dot", + hideLabel = false, + hideIndicator = false, + label, + labelFormatter, + labelClassName, + formatter, + color, + nameKey, + labelKey, + }, + ref + ) => { + const { config } = useChart() + + const tooltipLabel = React.useMemo(() => { + if (hideLabel || !payload?.length) { + return null + } + + const [item] = payload + const key = `${labelKey || item.dataKey || item.name || "value"}` + const itemConfig = getPayloadConfigFromPayload(config, item, key) + const value = + !labelKey && typeof label === "string" + ? config[label as keyof typeof config]?.label || label + : itemConfig?.label + + if (labelFormatter) { + return ( + <div className={cn("font-medium", labelClassName)}> + {labelFormatter(value, payload)} + </div> + ) + } + + if (!value) { + return null + } + + return <div className={cn("font-medium", labelClassName)}>{value}</div> + }, [ + label, + labelFormatter, + payload, + hideLabel, + labelClassName, + config, + labelKey, + ]) + + if (!active || !payload?.length) { + return null + } + + const nestLabel = payload.length === 1 && indicator !== "dot" + + return ( + <div + ref={ref} + className={cn( + "grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl", + className + )} + > + {!nestLabel ? tooltipLabel : null} + <div className="grid gap-1.5"> + {payload.map((item, index) => { + const key = `${nameKey || item.name || item.dataKey || "value"}` + const itemConfig = getPayloadConfigFromPayload(config, item, key) + const indicatorColor = color || item.payload.fill || item.color + + return ( + <div + key={item.dataKey} + className={cn( + "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground", + indicator === "dot" && "items-center" + )} + > + {formatter && item?.value !== undefined && item.name ? ( + formatter(item.value, item.name, item, index, item.payload) + ) : ( + <> + {itemConfig?.icon ? ( + <itemConfig.icon /> + ) : ( + !hideIndicator && ( + <div + className={cn( + "shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]", + { + "h-2.5 w-2.5": indicator === "dot", + "w-1": indicator === "line", + "w-0 border-[1.5px] border-dashed bg-transparent": + indicator === "dashed", + "my-0.5": nestLabel && indicator === "dashed", + } + )} + style={ + { + "--color-bg": indicatorColor, + "--color-border": indicatorColor, + } as React.CSSProperties + } + /> + ) + )} + <div + className={cn( + "flex flex-1 justify-between leading-none", + nestLabel ? "items-end" : "items-center" + )} + > + <div className="grid gap-1.5"> + {nestLabel ? tooltipLabel : null} + <span className="text-muted-foreground"> + {itemConfig?.label || item.name} + </span> + </div> + {item.value && ( + <span className="font-mono font-medium tabular-nums text-foreground"> + {item.value.toLocaleString()} + </span> + )} + </div> + </> + )} + </div> + ) + })} + </div> + </div> + ) + } +) +ChartTooltipContent.displayName = "ChartTooltip" + +const ChartLegend = RechartsPrimitive.Legend + +const ChartLegendContent = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & + Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & { + hideIcon?: boolean + nameKey?: string + } +>( + ( + { className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, + ref + ) => { + const { config } = useChart() + + if (!payload?.length) { + return null + } + + return ( + <div + ref={ref} + className={cn( + "flex items-center justify-center gap-4", + verticalAlign === "top" ? "pb-3" : "pt-3", + className + )} + > + {payload.map((item) => { + const key = `${nameKey || item.dataKey || "value"}` + const itemConfig = getPayloadConfigFromPayload(config, item, key) + + return ( + <div + key={item.value} + className={cn( + "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground" + )} + > + {itemConfig?.icon && !hideIcon ? ( + <itemConfig.icon /> + ) : ( + <div + className="h-2 w-2 shrink-0 rounded-[2px]" + style={{ + backgroundColor: item.color, + }} + /> + )} + {itemConfig?.label} + </div> + ) + })} + </div> + ) + } +) +ChartLegendContent.displayName = "ChartLegend" + +// Helper to extract item config from a payload. +function getPayloadConfigFromPayload( + config: ChartConfig, + payload: unknown, + key: string +) { + if (typeof payload !== "object" || payload === null) { + return undefined + } + + const payloadPayload = + "payload" in payload && + typeof payload.payload === "object" && + payload.payload !== null + ? payload.payload + : undefined + + let configLabelKey: string = key + + if ( + key in payload && + typeof payload[key as keyof typeof payload] === "string" + ) { + configLabelKey = payload[key as keyof typeof payload] as string + } else if ( + payloadPayload && + key in payloadPayload && + typeof payloadPayload[key as keyof typeof payloadPayload] === "string" + ) { + configLabelKey = payloadPayload[ + key as keyof typeof payloadPayload + ] as string + } + + return configLabelKey in config + ? config[configLabelKey] + : config[key as keyof typeof config] +} + +export { + ChartContainer, + ChartTooltip, + ChartTooltipContent, + ChartLegend, + ChartLegendContent, + ChartStyle, +} diff --git a/pkg/ui/frontend/src/components/ui/checkbox.tsx b/pkg/ui/frontend/src/components/ui/checkbox.tsx new file mode 100644 index 0000000000000..88fa63d95c5cb --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/checkbox.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import * as CheckboxPrimitive from "@radix-ui/react-checkbox"; +import { Check } from "lucide-react"; + +import { cn } from "@/lib/utils"; + +const Checkbox = React.forwardRef< + React.ElementRef<typeof CheckboxPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> +>(({ className, ...props }, ref) => ( + <CheckboxPrimitive.Root + ref={ref} + className={cn( + "peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", + className + )} + {...props} + > + <CheckboxPrimitive.Indicator + className={cn("flex items-center justify-center text-current")} + > + <Check className="h-4 w-4" /> + </CheckboxPrimitive.Indicator> + </CheckboxPrimitive.Root> +)); +Checkbox.displayName = CheckboxPrimitive.Root.displayName; + +export { Checkbox }; diff --git a/pkg/ui/frontend/src/components/ui/code-block.tsx b/pkg/ui/frontend/src/components/ui/code-block.tsx new file mode 100644 index 0000000000000..d07a14bb07ae9 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/code-block.tsx @@ -0,0 +1,208 @@ +import { CodeBlock as ReactCodeBlock } from "react-code-block"; +import { Button } from "./button"; +import { Copy, Check, ChevronDown, ChevronUp } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { useState } from "react"; +import { useTheme } from "next-themes"; +import type { PrismTheme } from "prism-react-renderer"; + +interface CodeBlockProps { + code: string; + language?: string; + fileName?: string; + className?: string; + maxLines?: number; +} + +const lightTheme: PrismTheme = { + plain: { + color: "var(--foreground)", + backgroundColor: "var(--muted)", + }, + styles: [ + { + types: ["comment"], + style: { + color: "#6e7781", + fontStyle: "italic" as const, + }, + }, + { + types: ["keyword", "selector", "changed"], + style: { + color: "#cf222e", + }, + }, + { + types: ["constant", "number", "builtin"], + style: { + color: "#0550ae", + }, + }, + { + types: ["string", "attr-value"], + style: { + color: "#0a3069", + }, + }, + { + types: ["function", "attr-name"], + style: { + color: "#8250df", + }, + }, + { + types: ["tag", "operator"], + style: { + color: "#116329", + }, + }, + { + types: ["variable", "property"], + style: { + color: "#953800", + }, + }, + { + types: ["punctuation"], + style: { + color: "#24292f", + }, + }, + ], +}; + +const darkTheme: PrismTheme = { + plain: { + color: "var(--foreground)", + backgroundColor: "var(--muted)", + }, + styles: [ + { + types: ["comment"], + style: { + color: "#8b949e", + fontStyle: "italic" as const, + }, + }, + { + types: ["keyword", "selector", "changed"], + style: { + color: "#ff7b72", + }, + }, + { + types: ["constant", "number", "builtin"], + style: { + color: "#79c0ff", + }, + }, + { + types: ["string", "attr-value"], + style: { + color: "#a5d6ff", + }, + }, + { + types: ["function", "attr-name"], + style: { + color: "#d2a8ff", + }, + }, + { + types: ["tag", "operator"], + style: { + color: "#7ee787", + }, + }, + { + types: ["variable", "property"], + style: { + color: "#ffa657", + }, + }, + { + types: ["punctuation"], + style: { + color: "#c9d1d9", + }, + }, + ], +}; + +export function CodeBlock({ + code, + language = "typescript", + fileName, + className, + maxLines = 200, +}: CodeBlockProps) { + const [copied, setCopied] = useState(false); + const [isExpanded, setIsExpanded] = useState(false); + const { theme } = useTheme(); + + const onCopy = async () => { + await navigator.clipboard.writeText(code); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + + const lines = code.split("\n"); + const shouldTruncate = lines.length > maxLines; + const displayedCode = isExpanded ? code : lines.slice(0, maxLines).join("\n"); + + return ( + <div className={cn("relative group rounded-lg overflow-hidden", className)}> + {fileName && ( + <div className="flex items-center justify-between px-4 py-2 border-b bg-muted/50"> + <div className="text-sm text-muted-foreground">{fileName}</div> + <Button + variant="ghost" + size="icon" + className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity" + onClick={onCopy} + > + {copied ? ( + <Check className="h-4 w-4" /> + ) : ( + <Copy className="h-4 w-4" /> + )} + <span className="sr-only">Copy code</span> + </Button> + </div> + )} + <ReactCodeBlock + code={displayedCode} + language={language} + theme={theme === "dark" ? darkTheme : lightTheme} + > + <ReactCodeBlock.Code className="bg-muted/50 p-4 text-sm whitespace-pre-wrap break-words"> + <ReactCodeBlock.LineContent className="max-w-full"> + <ReactCodeBlock.Token /> + </ReactCodeBlock.LineContent> + </ReactCodeBlock.Code> + </ReactCodeBlock> + {shouldTruncate && ( + <div className="flex justify-center p-2 border-t bg-muted/50"> + <Button + variant="ghost" + size="sm" + onClick={() => setIsExpanded(!isExpanded)} + className="flex items-center gap-2" + > + {isExpanded ? ( + <> + Show Less <ChevronUp className="h-4 w-4" /> + </> + ) : ( + <> + Show More ({lines.length - maxLines} more lines){" "} + <ChevronDown className="h-4 w-4" /> + </> + )} + </Button> + </div> + )} + </div> + ); +} diff --git a/pkg/ui/frontend/src/components/ui/collapsible.tsx b/pkg/ui/frontend/src/components/ui/collapsible.tsx new file mode 100644 index 0000000000000..a23e7a281287e --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/collapsible.tsx @@ -0,0 +1,9 @@ +import * as CollapsiblePrimitive from "@radix-ui/react-collapsible" + +const Collapsible = CollapsiblePrimitive.Root + +const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger + +const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent + +export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/pkg/ui/frontend/src/components/ui/command.tsx b/pkg/ui/frontend/src/components/ui/command.tsx new file mode 100644 index 0000000000000..0db642a6e9725 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/command.tsx @@ -0,0 +1,151 @@ +import * as React from "react" +import { type DialogProps } from "@radix-ui/react-dialog" +import { Command as CommandPrimitive } from "cmdk" +import { Search } from "lucide-react" + +import { cn } from "@/lib/utils" +import { Dialog, DialogContent } from "@/components/ui/dialog" + +const Command = React.forwardRef< + React.ElementRef<typeof CommandPrimitive>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive> +>(({ className, ...props }, ref) => ( + <CommandPrimitive + ref={ref} + className={cn( + "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", + className + )} + {...props} + /> +)) +Command.displayName = CommandPrimitive.displayName + +const CommandDialog = ({ children, ...props }: DialogProps) => { + return ( + <Dialog {...props}> + <DialogContent className="overflow-hidden p-0"> + <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"> + {children} + </Command> + </DialogContent> + </Dialog> + ) +} + +const CommandInput = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.Input>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input> +>(({ className, ...props }, ref) => ( + <div className="flex items-center border-b px-3" cmdk-input-wrapper=""> + <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" /> + <CommandPrimitive.Input + ref={ref} + className={cn( + "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50", + className + )} + {...props} + /> + </div> +)) + +CommandInput.displayName = CommandPrimitive.Input.displayName + +const CommandList = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.List>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.List> +>(({ className, ...props }, ref) => ( + <CommandPrimitive.List + ref={ref} + className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)} + {...props} + /> +)) + +CommandList.displayName = CommandPrimitive.List.displayName + +const CommandEmpty = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.Empty>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty> +>((props, ref) => ( + <CommandPrimitive.Empty + ref={ref} + className="py-6 text-center text-sm" + {...props} + /> +)) + +CommandEmpty.displayName = CommandPrimitive.Empty.displayName + +const CommandGroup = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.Group>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group> +>(({ className, ...props }, ref) => ( + <CommandPrimitive.Group + ref={ref} + className={cn( + "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground", + className + )} + {...props} + /> +)) + +CommandGroup.displayName = CommandPrimitive.Group.displayName + +const CommandSeparator = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.Separator>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator> +>(({ className, ...props }, ref) => ( + <CommandPrimitive.Separator + ref={ref} + className={cn("-mx-1 h-px bg-border", className)} + {...props} + /> +)) +CommandSeparator.displayName = CommandPrimitive.Separator.displayName + +const CommandItem = React.forwardRef< + React.ElementRef<typeof CommandPrimitive.Item>, + React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item> +>(({ className, ...props }, ref) => ( + <CommandPrimitive.Item + ref={ref} + className={cn( + "relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", + className + )} + {...props} + /> +)) + +CommandItem.displayName = CommandPrimitive.Item.displayName + +const CommandShortcut = ({ + className, + ...props +}: React.HTMLAttributes<HTMLSpanElement>) => { + return ( + <span + className={cn( + "ml-auto text-xs tracking-widest text-muted-foreground", + className + )} + {...props} + /> + ) +} +CommandShortcut.displayName = "CommandShortcut" + +export { + Command, + CommandDialog, + CommandInput, + CommandList, + CommandEmpty, + CommandGroup, + CommandItem, + CommandShortcut, + CommandSeparator, +} diff --git a/pkg/ui/frontend/src/components/ui/dialog.tsx b/pkg/ui/frontend/src/components/ui/dialog.tsx new file mode 100644 index 0000000000000..bff19f9750683 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/dialog.tsx @@ -0,0 +1,120 @@ +import * as React from "react"; +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { X } from "lucide-react"; + +import { cn } from "@/lib/utils"; + +const Dialog = DialogPrimitive.Root; + +const DialogTrigger = DialogPrimitive.Trigger; + +const DialogPortal = DialogPrimitive.Portal; + +const DialogClose = DialogPrimitive.Close; + +const DialogOverlay = React.forwardRef< + React.ElementRef<typeof DialogPrimitive.Overlay>, + React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay> +>(({ className, ...props }, ref) => ( + <DialogPrimitive.Overlay + ref={ref} + className={cn( + "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", + className + )} + {...props} + /> +)); +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; + +const DialogContent = React.forwardRef< + React.ElementRef<typeof DialogPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> +>(({ className, children, ...props }, ref) => ( + <DialogPortal> + <DialogOverlay /> + <DialogPrimitive.Content + ref={ref} + className={cn( + "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg", + className + )} + {...props} + > + {children} + <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"> + <X className="h-4 w-4" /> + <span className="sr-only">Close</span> + </DialogPrimitive.Close> + </DialogPrimitive.Content> + </DialogPortal> +)); +DialogContent.displayName = DialogPrimitive.Content.displayName; + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes<HTMLDivElement>) => ( + <div + className={cn( + "flex flex-col space-y-1.5 text-center sm:text-left", + className + )} + {...props} + /> +); +DialogHeader.displayName = "DialogHeader"; + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes<HTMLDivElement>) => ( + <div + className={cn( + "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", + className + )} + {...props} + /> +); +DialogFooter.displayName = "DialogFooter"; + +const DialogTitle = React.forwardRef< + React.ElementRef<typeof DialogPrimitive.Title>, + React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title> +>(({ className, ...props }, ref) => ( + <DialogPrimitive.Title + ref={ref} + className={cn( + "text-lg font-semibold leading-none tracking-tight", + className + )} + {...props} + /> +)); +DialogTitle.displayName = DialogPrimitive.Title.displayName; + +const DialogDescription = React.forwardRef< + React.ElementRef<typeof DialogPrimitive.Description>, + React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description> +>(({ className, ...props }, ref) => ( + <DialogPrimitive.Description + ref={ref} + className={cn("text-sm text-muted-foreground", className)} + {...props} + /> +)); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/pkg/ui/frontend/src/components/ui/dropdown-menu.tsx b/pkg/ui/frontend/src/components/ui/dropdown-menu.tsx new file mode 100644 index 0000000000000..5c1e59d3726dd --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,198 @@ +import * as React from "react"; +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { Check, ChevronRight, Circle } from "lucide-react"; + +import { cn } from "@/lib/utils"; + +const DropdownMenu = DropdownMenuPrimitive.Root; + +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; + +const DropdownMenuGroup = DropdownMenuPrimitive.Group; + +const DropdownMenuPortal = DropdownMenuPrimitive.Portal; + +const DropdownMenuSub = DropdownMenuPrimitive.Sub; + +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & { + inset?: boolean; + } +>(({ className, inset, children, ...props }, ref) => ( + <DropdownMenuPrimitive.SubTrigger + ref={ref} + className={cn( + "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent", + inset && "pl-8", + className + )} + {...props} + > + {children} + <ChevronRight className="ml-auto h-4 w-4" /> + </DropdownMenuPrimitive.SubTrigger> +)); +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName; + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent> +>(({ className, ...props }, ref) => ( + <DropdownMenuPrimitive.SubContent + ref={ref} + className={cn( + "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + className + )} + {...props} + /> +)); +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName; + +const DropdownMenuContent = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> +>(({ className, sideOffset = 4, ...props }, ref) => ( + <DropdownMenuPrimitive.Portal> + <DropdownMenuPrimitive.Content + ref={ref} + sideOffset={sideOffset} + className={cn( + "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + className + )} + {...props} + /> + </DropdownMenuPrimitive.Portal> +)); +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; + +const DropdownMenuItem = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.Item>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + <DropdownMenuPrimitive.Item + ref={ref} + className={cn( + "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", + inset && "pl-8", + className + )} + {...props} + /> +)); +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem> +>(({ className, children, checked, ...props }, ref) => ( + <DropdownMenuPrimitive.CheckboxItem + ref={ref} + className={cn( + "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", + className + )} + checked={checked} + {...props} + > + <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> + <DropdownMenuPrimitive.ItemIndicator> + <Check className="h-4 w-4" /> + </DropdownMenuPrimitive.ItemIndicator> + </span> + {children} + </DropdownMenuPrimitive.CheckboxItem> +)); +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName; + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem> +>(({ className, children, ...props }, ref) => ( + <DropdownMenuPrimitive.RadioItem + ref={ref} + className={cn( + "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", + className + )} + {...props} + > + <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> + <DropdownMenuPrimitive.ItemIndicator> + <Circle className="h-2 w-2 fill-current" /> + </DropdownMenuPrimitive.ItemIndicator> + </span> + {children} + </DropdownMenuPrimitive.RadioItem> +)); +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.Label>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + <DropdownMenuPrimitive.Label + ref={ref} + className={cn( + "px-2 py-1.5 text-sm font-semibold", + inset && "pl-8", + className + )} + {...props} + /> +)); +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef<typeof DropdownMenuPrimitive.Separator>, + React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator> +>(({ className, ...props }, ref) => ( + <DropdownMenuPrimitive.Separator + ref={ref} + className={cn("-mx-1 my-1 h-px bg-muted", className)} + {...props} + /> +)); +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes<HTMLSpanElement>) => { + return ( + <span + className={cn("ml-auto text-xs tracking-widest opacity-60", className)} + {...props} + /> + ); +}; +DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; + +export { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuGroup, + DropdownMenuPortal, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuRadioGroup, +}; diff --git a/pkg/ui/frontend/src/components/ui/form.tsx b/pkg/ui/frontend/src/components/ui/form.tsx new file mode 100644 index 0000000000000..f6afdaf24faa0 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/form.tsx @@ -0,0 +1,176 @@ +import * as React from "react" +import * as LabelPrimitive from "@radix-ui/react-label" +import { Slot } from "@radix-ui/react-slot" +import { + Controller, + ControllerProps, + FieldPath, + FieldValues, + FormProvider, + useFormContext, +} from "react-hook-form" + +import { cn } from "@/lib/utils" +import { Label } from "@/components/ui/label" + +const Form = FormProvider + +type FormFieldContextValue< + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> +> = { + name: TName +} + +const FormFieldContext = React.createContext<FormFieldContextValue>( + {} as FormFieldContextValue +) + +const FormField = < + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> +>({ + ...props +}: ControllerProps<TFieldValues, TName>) => { + return ( + <FormFieldContext.Provider value={{ name: props.name }}> + <Controller {...props} /> + </FormFieldContext.Provider> + ) +} + +const useFormField = () => { + const fieldContext = React.useContext(FormFieldContext) + const itemContext = React.useContext(FormItemContext) + const { getFieldState, formState } = useFormContext() + + const fieldState = getFieldState(fieldContext.name, formState) + + if (!fieldContext) { + throw new Error("useFormField should be used within <FormField>") + } + + const { id } = itemContext + + return { + id, + name: fieldContext.name, + formItemId: `${id}-form-item`, + formDescriptionId: `${id}-form-item-description`, + formMessageId: `${id}-form-item-message`, + ...fieldState, + } +} + +type FormItemContextValue = { + id: string +} + +const FormItemContext = React.createContext<FormItemContextValue>( + {} as FormItemContextValue +) + +const FormItem = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> +>(({ className, ...props }, ref) => { + const id = React.useId() + + return ( + <FormItemContext.Provider value={{ id }}> + <div ref={ref} className={cn("space-y-2", className)} {...props} /> + </FormItemContext.Provider> + ) +}) +FormItem.displayName = "FormItem" + +const FormLabel = React.forwardRef< + React.ElementRef<typeof LabelPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> +>(({ className, ...props }, ref) => { + const { error, formItemId } = useFormField() + + return ( + <Label + ref={ref} + className={cn(error && "text-destructive", className)} + htmlFor={formItemId} + {...props} + /> + ) +}) +FormLabel.displayName = "FormLabel" + +const FormControl = React.forwardRef< + React.ElementRef<typeof Slot>, + React.ComponentPropsWithoutRef<typeof Slot> +>(({ ...props }, ref) => { + const { error, formItemId, formDescriptionId, formMessageId } = useFormField() + + return ( + <Slot + ref={ref} + id={formItemId} + aria-describedby={ + !error + ? `${formDescriptionId}` + : `${formDescriptionId} ${formMessageId}` + } + aria-invalid={!!error} + {...props} + /> + ) +}) +FormControl.displayName = "FormControl" + +const FormDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLParagraphElement> +>(({ className, ...props }, ref) => { + const { formDescriptionId } = useFormField() + + return ( + <p + ref={ref} + id={formDescriptionId} + className={cn("text-[0.8rem] text-muted-foreground", className)} + {...props} + /> + ) +}) +FormDescription.displayName = "FormDescription" + +const FormMessage = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLParagraphElement> +>(({ className, children, ...props }, ref) => { + const { error, formMessageId } = useFormField() + const body = error ? String(error?.message) : children + + if (!body) { + return null + } + + return ( + <p + ref={ref} + id={formMessageId} + className={cn("text-[0.8rem] font-medium text-destructive", className)} + {...props} + > + {body} + </p> + ) +}) +FormMessage.displayName = "FormMessage" + +export { + useFormField, + Form, + FormItem, + FormLabel, + FormControl, + FormDescription, + FormMessage, + FormField, +} diff --git a/pkg/ui/frontend/src/components/ui/hover-card.tsx b/pkg/ui/frontend/src/components/ui/hover-card.tsx new file mode 100644 index 0000000000000..863ff0148f0bb --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/hover-card.tsx @@ -0,0 +1,27 @@ +import * as React from "react" +import * as HoverCardPrimitive from "@radix-ui/react-hover-card" + +import { cn } from "@/lib/utils" + +const HoverCard = HoverCardPrimitive.Root + +const HoverCardTrigger = HoverCardPrimitive.Trigger + +const HoverCardContent = React.forwardRef< + React.ElementRef<typeof HoverCardPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content> +>(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( + <HoverCardPrimitive.Content + ref={ref} + align={align} + sideOffset={sideOffset} + className={cn( + "z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + className + )} + {...props} + /> +)) +HoverCardContent.displayName = HoverCardPrimitive.Content.displayName + +export { HoverCard, HoverCardTrigger, HoverCardContent } diff --git a/pkg/ui/frontend/src/components/ui/index.ts b/pkg/ui/frontend/src/components/ui/index.ts new file mode 100644 index 0000000000000..0816bc0462c68 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/index.ts @@ -0,0 +1,25 @@ +export * from "./badge"; +export * from "./breadcrumb"; +export * from "./button"; +export * from "./card"; +export * from "./chart"; +export * from "./code-block"; +export * from "./collapsible"; +export * from "./command"; +export * from "./dialog"; +export * from "./dropdown-menu"; +export * from "./hover-card"; +export * from "./input"; +export * from "./label"; +export * from "./popover"; +export * from "./scroll-area"; +export * from "./scroll-to-top"; +export * from "./select"; +export * from "./separator"; +export * from "./sheet"; +export * from "./sidebar"; +export * from "./skeleton"; +export * from "./switch"; +export * from "./table"; +export * from "./tabs"; +export * from "./tooltip"; diff --git a/pkg/ui/frontend/src/components/ui/input.tsx b/pkg/ui/frontend/src/components/ui/input.tsx new file mode 100644 index 0000000000000..69b64fb245511 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/input.tsx @@ -0,0 +1,22 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>( + ({ className, type, ...props }, ref) => { + return ( + <input + type={type} + className={cn( + "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", + className + )} + ref={ref} + {...props} + /> + ) + } +) +Input.displayName = "Input" + +export { Input } diff --git a/pkg/ui/frontend/src/components/ui/label.tsx b/pkg/ui/frontend/src/components/ui/label.tsx new file mode 100644 index 0000000000000..683faa7938199 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/label.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import * as LabelPrimitive from "@radix-ui/react-label" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const labelVariants = cva( + "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" +) + +const Label = React.forwardRef< + React.ElementRef<typeof LabelPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & + VariantProps<typeof labelVariants> +>(({ className, ...props }, ref) => ( + <LabelPrimitive.Root + ref={ref} + className={cn(labelVariants(), className)} + {...props} + /> +)) +Label.displayName = LabelPrimitive.Root.displayName + +export { Label } diff --git a/pkg/ui/frontend/src/components/ui/popover.tsx b/pkg/ui/frontend/src/components/ui/popover.tsx new file mode 100644 index 0000000000000..d82e714959e16 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/popover.tsx @@ -0,0 +1,31 @@ +import * as React from "react" +import * as PopoverPrimitive from "@radix-ui/react-popover" + +import { cn } from "@/lib/utils" + +const Popover = PopoverPrimitive.Root + +const PopoverTrigger = PopoverPrimitive.Trigger + +const PopoverAnchor = PopoverPrimitive.Anchor + +const PopoverContent = React.forwardRef< + React.ElementRef<typeof PopoverPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> +>(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( + <PopoverPrimitive.Portal> + <PopoverPrimitive.Content + ref={ref} + align={align} + sideOffset={sideOffset} + className={cn( + "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + className + )} + {...props} + /> + </PopoverPrimitive.Portal> +)) +PopoverContent.displayName = PopoverPrimitive.Content.displayName + +export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor } diff --git a/pkg/ui/frontend/src/components/ui/progress.tsx b/pkg/ui/frontend/src/components/ui/progress.tsx new file mode 100644 index 0000000000000..3fd47adade499 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/progress.tsx @@ -0,0 +1,26 @@ +import * as React from "react" +import * as ProgressPrimitive from "@radix-ui/react-progress" + +import { cn } from "@/lib/utils" + +const Progress = React.forwardRef< + React.ElementRef<typeof ProgressPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> +>(({ className, value, ...props }, ref) => ( + <ProgressPrimitive.Root + ref={ref} + className={cn( + "relative h-2 w-full overflow-hidden rounded-full bg-primary/20", + className + )} + {...props} + > + <ProgressPrimitive.Indicator + className="h-full w-full flex-1 bg-primary transition-all" + style={{ transform: `translateX(-${100 - (value || 0)}%)` }} + /> + </ProgressPrimitive.Root> +)) +Progress.displayName = ProgressPrimitive.Root.displayName + +export { Progress } diff --git a/pkg/ui/frontend/src/components/ui/scroll-area.tsx b/pkg/ui/frontend/src/components/ui/scroll-area.tsx new file mode 100644 index 0000000000000..cf253cf17056c --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/scroll-area.tsx @@ -0,0 +1,46 @@ +import * as React from "react" +import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area" + +import { cn } from "@/lib/utils" + +const ScrollArea = React.forwardRef< + React.ElementRef<typeof ScrollAreaPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> +>(({ className, children, ...props }, ref) => ( + <ScrollAreaPrimitive.Root + ref={ref} + className={cn("relative overflow-hidden", className)} + {...props} + > + <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]"> + {children} + </ScrollAreaPrimitive.Viewport> + <ScrollBar /> + <ScrollAreaPrimitive.Corner /> + </ScrollAreaPrimitive.Root> +)) +ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName + +const ScrollBar = React.forwardRef< + React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>, + React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> +>(({ className, orientation = "vertical", ...props }, ref) => ( + <ScrollAreaPrimitive.ScrollAreaScrollbar + ref={ref} + orientation={orientation} + className={cn( + "flex touch-none select-none transition-colors", + orientation === "vertical" && + "h-full w-2.5 border-l border-l-transparent p-[1px]", + orientation === "horizontal" && + "h-2.5 flex-col border-t border-t-transparent p-[1px]", + className + )} + {...props} + > + <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" /> + </ScrollAreaPrimitive.ScrollAreaScrollbar> +)) +ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName + +export { ScrollArea, ScrollBar } diff --git a/pkg/ui/frontend/src/components/ui/scroll-to-top.tsx b/pkg/ui/frontend/src/components/ui/scroll-to-top.tsx new file mode 100644 index 0000000000000..d4f222817eb6b --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/scroll-to-top.tsx @@ -0,0 +1,36 @@ +import { useState, useEffect } from "react"; +import { Button } from "./button"; +import { ArrowUp } from "lucide-react"; + +export function ScrollToTop() { + const [show, setShow] = useState(false); + + useEffect(() => { + const handleScroll = () => { + setShow(window.scrollY > 300); + }; + + window.addEventListener("scroll", handleScroll); + return () => window.removeEventListener("scroll", handleScroll); + }, []); + + const scrollToTop = () => { + window.scrollTo({ + top: 0, + behavior: "smooth", + }); + }; + + if (!show) return null; + + return ( + <Button + onClick={scrollToTop} + size="icon" + className="fixed bottom-8 right-8 rounded-full shadow-lg transition-all duration-300" + aria-label="Back to top" + > + <ArrowUp className="h-4 w-4" /> + </Button> + ); +} diff --git a/pkg/ui/frontend/src/components/ui/select.tsx b/pkg/ui/frontend/src/components/ui/select.tsx new file mode 100644 index 0000000000000..a84242cfa727b --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/select.tsx @@ -0,0 +1,157 @@ +import * as React from "react" +import * as SelectPrimitive from "@radix-ui/react-select" +import { Check, ChevronDown, ChevronUp } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Select = SelectPrimitive.Root + +const SelectGroup = SelectPrimitive.Group + +const SelectValue = SelectPrimitive.Value + +const SelectTrigger = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.Trigger>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> +>(({ className, children, ...props }, ref) => ( + <SelectPrimitive.Trigger + ref={ref} + className={cn( + "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1", + className + )} + {...props} + > + {children} + <SelectPrimitive.Icon asChild> + <ChevronDown className="h-4 w-4 opacity-50" /> + </SelectPrimitive.Icon> + </SelectPrimitive.Trigger> +)) +SelectTrigger.displayName = SelectPrimitive.Trigger.displayName + +const SelectScrollUpButton = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.ScrollUpButton>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton> +>(({ className, ...props }, ref) => ( + <SelectPrimitive.ScrollUpButton + ref={ref} + className={cn( + "flex cursor-default items-center justify-center py-1", + className + )} + {...props} + > + <ChevronUp className="h-4 w-4" /> + </SelectPrimitive.ScrollUpButton> +)) +SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName + +const SelectScrollDownButton = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.ScrollDownButton>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton> +>(({ className, ...props }, ref) => ( + <SelectPrimitive.ScrollDownButton + ref={ref} + className={cn( + "flex cursor-default items-center justify-center py-1", + className + )} + {...props} + > + <ChevronDown className="h-4 w-4" /> + </SelectPrimitive.ScrollDownButton> +)) +SelectScrollDownButton.displayName = + SelectPrimitive.ScrollDownButton.displayName + +const SelectContent = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> +>(({ className, children, position = "popper", ...props }, ref) => ( + <SelectPrimitive.Portal> + <SelectPrimitive.Content + ref={ref} + className={cn( + "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + position === "popper" && + "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", + className + )} + position={position} + {...props} + > + <SelectScrollUpButton /> + <SelectPrimitive.Viewport + className={cn( + "p-1", + position === "popper" && + "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]" + )} + > + {children} + </SelectPrimitive.Viewport> + <SelectScrollDownButton /> + </SelectPrimitive.Content> + </SelectPrimitive.Portal> +)) +SelectContent.displayName = SelectPrimitive.Content.displayName + +const SelectLabel = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.Label>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> +>(({ className, ...props }, ref) => ( + <SelectPrimitive.Label + ref={ref} + className={cn("px-2 py-1.5 text-sm font-semibold", className)} + {...props} + /> +)) +SelectLabel.displayName = SelectPrimitive.Label.displayName + +const SelectItem = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.Item>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> +>(({ className, children, ...props }, ref) => ( + <SelectPrimitive.Item + ref={ref} + className={cn( + "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", + className + )} + {...props} + > + <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center"> + <SelectPrimitive.ItemIndicator> + <Check className="h-4 w-4" /> + </SelectPrimitive.ItemIndicator> + </span> + <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> + </SelectPrimitive.Item> +)) +SelectItem.displayName = SelectPrimitive.Item.displayName + +const SelectSeparator = React.forwardRef< + React.ElementRef<typeof SelectPrimitive.Separator>, + React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator> +>(({ className, ...props }, ref) => ( + <SelectPrimitive.Separator + ref={ref} + className={cn("-mx-1 my-1 h-px bg-muted", className)} + {...props} + /> +)) +SelectSeparator.displayName = SelectPrimitive.Separator.displayName + +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +} diff --git a/pkg/ui/frontend/src/components/ui/separator.tsx b/pkg/ui/frontend/src/components/ui/separator.tsx new file mode 100644 index 0000000000000..6d7f12265ba03 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/separator.tsx @@ -0,0 +1,29 @@ +import * as React from "react" +import * as SeparatorPrimitive from "@radix-ui/react-separator" + +import { cn } from "@/lib/utils" + +const Separator = React.forwardRef< + React.ElementRef<typeof SeparatorPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> +>( + ( + { className, orientation = "horizontal", decorative = true, ...props }, + ref + ) => ( + <SeparatorPrimitive.Root + ref={ref} + decorative={decorative} + orientation={orientation} + className={cn( + "shrink-0 bg-border", + orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", + className + )} + {...props} + /> + ) +) +Separator.displayName = SeparatorPrimitive.Root.displayName + +export { Separator } diff --git a/pkg/ui/frontend/src/components/ui/sheet.tsx b/pkg/ui/frontend/src/components/ui/sheet.tsx new file mode 100644 index 0000000000000..272cb721eb48b --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/sheet.tsx @@ -0,0 +1,140 @@ +"use client" + +import * as React from "react" +import * as SheetPrimitive from "@radix-ui/react-dialog" +import { cva, type VariantProps } from "class-variance-authority" +import { X } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Sheet = SheetPrimitive.Root + +const SheetTrigger = SheetPrimitive.Trigger + +const SheetClose = SheetPrimitive.Close + +const SheetPortal = SheetPrimitive.Portal + +const SheetOverlay = React.forwardRef< + React.ElementRef<typeof SheetPrimitive.Overlay>, + React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay> +>(({ className, ...props }, ref) => ( + <SheetPrimitive.Overlay + className={cn( + "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", + className + )} + {...props} + ref={ref} + /> +)) +SheetOverlay.displayName = SheetPrimitive.Overlay.displayName + +const sheetVariants = cva( + "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out", + { + variants: { + side: { + top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top", + bottom: + "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom", + left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm", + right: + "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm", + }, + }, + defaultVariants: { + side: "right", + }, + } +) + +interface SheetContentProps + extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>, + VariantProps<typeof sheetVariants> {} + +const SheetContent = React.forwardRef< + React.ElementRef<typeof SheetPrimitive.Content>, + SheetContentProps +>(({ side = "right", className, children, ...props }, ref) => ( + <SheetPortal> + <SheetOverlay /> + <SheetPrimitive.Content + ref={ref} + className={cn(sheetVariants({ side }), className)} + {...props} + > + <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary"> + <X className="h-4 w-4" /> + <span className="sr-only">Close</span> + </SheetPrimitive.Close> + {children} + </SheetPrimitive.Content> + </SheetPortal> +)) +SheetContent.displayName = SheetPrimitive.Content.displayName + +const SheetHeader = ({ + className, + ...props +}: React.HTMLAttributes<HTMLDivElement>) => ( + <div + className={cn( + "flex flex-col space-y-2 text-center sm:text-left", + className + )} + {...props} + /> +) +SheetHeader.displayName = "SheetHeader" + +const SheetFooter = ({ + className, + ...props +}: React.HTMLAttributes<HTMLDivElement>) => ( + <div + className={cn( + "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", + className + )} + {...props} + /> +) +SheetFooter.displayName = "SheetFooter" + +const SheetTitle = React.forwardRef< + React.ElementRef<typeof SheetPrimitive.Title>, + React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title> +>(({ className, ...props }, ref) => ( + <SheetPrimitive.Title + ref={ref} + className={cn("text-lg font-semibold text-foreground", className)} + {...props} + /> +)) +SheetTitle.displayName = SheetPrimitive.Title.displayName + +const SheetDescription = React.forwardRef< + React.ElementRef<typeof SheetPrimitive.Description>, + React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description> +>(({ className, ...props }, ref) => ( + <SheetPrimitive.Description + ref={ref} + className={cn("text-sm text-muted-foreground", className)} + {...props} + /> +)) +SheetDescription.displayName = SheetPrimitive.Description.displayName + +export { + Sheet, + SheetPortal, + SheetOverlay, + SheetTrigger, + SheetClose, + SheetContent, + SheetHeader, + SheetFooter, + SheetTitle, + SheetDescription, +} diff --git a/pkg/ui/frontend/src/components/ui/sidebar.tsx b/pkg/ui/frontend/src/components/ui/sidebar.tsx new file mode 100644 index 0000000000000..1a173c7d380cc --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/sidebar.tsx @@ -0,0 +1,761 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { VariantProps, cva } from "class-variance-authority" +import { PanelLeft } from "lucide-react" + +import { useIsMobile } from "@/hooks/use-mobile" +import { cn } from "@/lib/utils" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Separator } from "@/components/ui/separator" +import { Sheet, SheetContent } from "@/components/ui/sheet" +import { Skeleton } from "@/components/ui/skeleton" +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip" + +const SIDEBAR_COOKIE_NAME = "sidebar:state" +const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7 +const SIDEBAR_WIDTH = "16rem" +const SIDEBAR_WIDTH_MOBILE = "18rem" +const SIDEBAR_WIDTH_ICON = "3rem" +const SIDEBAR_KEYBOARD_SHORTCUT = "b" + +type SidebarContext = { + state: "expanded" | "collapsed" + open: boolean + setOpen: (open: boolean) => void + openMobile: boolean + setOpenMobile: (open: boolean) => void + isMobile: boolean + toggleSidebar: () => void +} + +const SidebarContext = React.createContext<SidebarContext | null>(null) + +function useSidebar() { + const context = React.useContext(SidebarContext) + if (!context) { + throw new Error("useSidebar must be used within a SidebarProvider.") + } + + return context +} + +const SidebarProvider = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { + defaultOpen?: boolean + open?: boolean + onOpenChange?: (open: boolean) => void + } +>( + ( + { + defaultOpen = true, + open: openProp, + onOpenChange: setOpenProp, + className, + style, + children, + ...props + }, + ref + ) => { + const isMobile = useIsMobile() + const [openMobile, setOpenMobile] = React.useState(false) + + // This is the internal state of the sidebar. + // We use openProp and setOpenProp for control from outside the component. + const [_open, _setOpen] = React.useState(defaultOpen) + const open = openProp ?? _open + const setOpen = React.useCallback( + (value: boolean | ((value: boolean) => boolean)) => { + const openState = typeof value === "function" ? value(open) : value + if (setOpenProp) { + setOpenProp(openState) + } else { + _setOpen(openState) + } + + // This sets the cookie to keep the sidebar state. + document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` + }, + [setOpenProp, open] + ) + + // Helper to toggle the sidebar. + const toggleSidebar = React.useCallback(() => { + return isMobile + ? setOpenMobile((open) => !open) + : setOpen((open) => !open) + }, [isMobile, setOpen, setOpenMobile]) + + // Adds a keyboard shortcut to toggle the sidebar. + React.useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if ( + event.key === SIDEBAR_KEYBOARD_SHORTCUT && + (event.metaKey || event.ctrlKey) + ) { + event.preventDefault() + toggleSidebar() + } + } + + window.addEventListener("keydown", handleKeyDown) + return () => window.removeEventListener("keydown", handleKeyDown) + }, [toggleSidebar]) + + // We add a state so that we can do data-state="expanded" or "collapsed". + // This makes it easier to style the sidebar with Tailwind classes. + const state = open ? "expanded" : "collapsed" + + const contextValue = React.useMemo<SidebarContext>( + () => ({ + state, + open, + setOpen, + isMobile, + openMobile, + setOpenMobile, + toggleSidebar, + }), + [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar] + ) + + return ( + <SidebarContext.Provider value={contextValue}> + <TooltipProvider delayDuration={0}> + <div + style={ + { + "--sidebar-width": SIDEBAR_WIDTH, + "--sidebar-width-icon": SIDEBAR_WIDTH_ICON, + ...style, + } as React.CSSProperties + } + className={cn( + "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar", + className + )} + ref={ref} + {...props} + > + {children} + </div> + </TooltipProvider> + </SidebarContext.Provider> + ) + } +) +SidebarProvider.displayName = "SidebarProvider" + +const Sidebar = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { + side?: "left" | "right" + variant?: "sidebar" | "floating" | "inset" + collapsible?: "offcanvas" | "icon" | "none" + } +>( + ( + { + side = "left", + variant = "sidebar", + collapsible = "offcanvas", + className, + children, + ...props + }, + ref + ) => { + const { isMobile, state, openMobile, setOpenMobile } = useSidebar() + + if (collapsible === "none") { + return ( + <div + className={cn( + "flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground", + className + )} + ref={ref} + {...props} + > + {children} + </div> + ) + } + + if (isMobile) { + return ( + <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}> + <SheetContent + data-sidebar="sidebar" + data-mobile="true" + className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden" + style={ + { + "--sidebar-width": SIDEBAR_WIDTH_MOBILE, + } as React.CSSProperties + } + side={side} + > + <div className="flex h-full w-full flex-col">{children}</div> + </SheetContent> + </Sheet> + ) + } + + return ( + <div + ref={ref} + className="group peer hidden text-sidebar-foreground md:block" + data-state={state} + data-collapsible={state === "collapsed" ? collapsible : ""} + data-variant={variant} + data-side={side} + > + {/* This is what handles the sidebar gap on desktop */} + <div + className={cn( + "relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear", + "group-data-[collapsible=offcanvas]:w-0", + "group-data-[side=right]:rotate-180", + variant === "floating" || variant === "inset" + ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]" + : "group-data-[collapsible=icon]:w-[--sidebar-width-icon]" + )} + /> + <div + className={cn( + "fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex", + side === "left" + ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]" + : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]", + // Adjust the padding for floating and inset variants. + variant === "floating" || variant === "inset" + ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]" + : "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l", + className + )} + {...props} + > + <div + data-sidebar="sidebar" + className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow" + > + {children} + </div> + </div> + </div> + ) + } +) +Sidebar.displayName = "Sidebar" + +const SidebarTrigger = React.forwardRef< + React.ElementRef<typeof Button>, + React.ComponentProps<typeof Button> +>(({ className, onClick, ...props }, ref) => { + const { toggleSidebar } = useSidebar() + + return ( + <Button + ref={ref} + data-sidebar="trigger" + variant="ghost" + size="icon" + className={cn("h-7 w-7", className)} + onClick={(event) => { + onClick?.(event) + toggleSidebar() + }} + {...props} + > + <PanelLeft /> + <span className="sr-only">Toggle Sidebar</span> + </Button> + ) +}) +SidebarTrigger.displayName = "SidebarTrigger" + +const SidebarRail = React.forwardRef< + HTMLButtonElement, + React.ComponentProps<"button"> +>(({ className, ...props }, ref) => { + const { toggleSidebar } = useSidebar() + + return ( + <button + ref={ref} + data-sidebar="rail" + aria-label="Toggle Sidebar" + tabIndex={-1} + onClick={toggleSidebar} + title="Toggle Sidebar" + className={cn( + "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex", + "[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize", + "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize", + "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar", + "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2", + "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2", + className + )} + {...props} + /> + ) +}) +SidebarRail.displayName = "SidebarRail" + +const SidebarInset = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"main"> +>(({ className, ...props }, ref) => { + return ( + <main + ref={ref} + className={cn( + "relative flex min-h-svh flex-1 flex-col bg-background", + "peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow", + className + )} + {...props} + /> + ) +}) +SidebarInset.displayName = "SidebarInset" + +const SidebarInput = React.forwardRef< + React.ElementRef<typeof Input>, + React.ComponentProps<typeof Input> +>(({ className, ...props }, ref) => { + return ( + <Input + ref={ref} + data-sidebar="input" + className={cn( + "h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring", + className + )} + {...props} + /> + ) +}) +SidebarInput.displayName = "SidebarInput" + +const SidebarHeader = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => { + return ( + <div + ref={ref} + data-sidebar="header" + className={cn("flex flex-col gap-2 p-2", className)} + {...props} + /> + ) +}) +SidebarHeader.displayName = "SidebarHeader" + +const SidebarFooter = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => { + return ( + <div + ref={ref} + data-sidebar="footer" + className={cn("flex flex-col gap-2 p-2", className)} + {...props} + /> + ) +}) +SidebarFooter.displayName = "SidebarFooter" + +const SidebarSeparator = React.forwardRef< + React.ElementRef<typeof Separator>, + React.ComponentProps<typeof Separator> +>(({ className, ...props }, ref) => { + return ( + <Separator + ref={ref} + data-sidebar="separator" + className={cn("mx-2 w-auto bg-sidebar-border", className)} + {...props} + /> + ) +}) +SidebarSeparator.displayName = "SidebarSeparator" + +const SidebarContent = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => { + return ( + <div + ref={ref} + data-sidebar="content" + className={cn( + "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden", + className + )} + {...props} + /> + ) +}) +SidebarContent.displayName = "SidebarContent" + +const SidebarGroup = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => { + return ( + <div + ref={ref} + data-sidebar="group" + className={cn("relative flex w-full min-w-0 flex-col p-2", className)} + {...props} + /> + ) +}) +SidebarGroup.displayName = "SidebarGroup" + +const SidebarGroupLabel = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { asChild?: boolean } +>(({ className, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "div" + + return ( + <Comp + ref={ref} + data-sidebar="group-label" + className={cn( + "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0", + "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0", + className + )} + {...props} + /> + ) +}) +SidebarGroupLabel.displayName = "SidebarGroupLabel" + +const SidebarGroupAction = React.forwardRef< + HTMLButtonElement, + React.ComponentProps<"button"> & { asChild?: boolean } +>(({ className, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + + return ( + <Comp + ref={ref} + data-sidebar="group-action" + className={cn( + "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0", + // Increases the hit area of the button on mobile. + "after:absolute after:-inset-2 after:md:hidden", + "group-data-[collapsible=icon]:hidden", + className + )} + {...props} + /> + ) +}) +SidebarGroupAction.displayName = "SidebarGroupAction" + +const SidebarGroupContent = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + data-sidebar="group-content" + className={cn("w-full text-sm", className)} + {...props} + /> +)) +SidebarGroupContent.displayName = "SidebarGroupContent" + +const SidebarMenu = React.forwardRef< + HTMLUListElement, + React.ComponentProps<"ul"> +>(({ className, ...props }, ref) => ( + <ul + ref={ref} + data-sidebar="menu" + className={cn("flex w-full min-w-0 flex-col gap-1", className)} + {...props} + /> +)) +SidebarMenu.displayName = "SidebarMenu" + +const SidebarMenuItem = React.forwardRef< + HTMLLIElement, + React.ComponentProps<"li"> +>(({ className, ...props }, ref) => ( + <li + ref={ref} + data-sidebar="menu-item" + className={cn("group/menu-item relative", className)} + {...props} + /> +)) +SidebarMenuItem.displayName = "SidebarMenuItem" + +const sidebarMenuButtonVariants = cva( + "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0", + { + variants: { + variant: { + default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground", + outline: + "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]", + }, + size: { + default: "h-8 text-sm", + sm: "h-7 text-xs", + lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +const SidebarMenuButton = React.forwardRef< + HTMLButtonElement, + React.ComponentProps<"button"> & { + asChild?: boolean + isActive?: boolean + tooltip?: string | React.ComponentProps<typeof TooltipContent> + } & VariantProps<typeof sidebarMenuButtonVariants> +>( + ( + { + asChild = false, + isActive = false, + variant = "default", + size = "default", + tooltip, + className, + ...props + }, + ref + ) => { + const Comp = asChild ? Slot : "button" + const { isMobile, state } = useSidebar() + + const button = ( + <Comp + ref={ref} + data-sidebar="menu-button" + data-size={size} + data-active={isActive} + className={cn(sidebarMenuButtonVariants({ variant, size }), className)} + {...props} + /> + ) + + if (!tooltip) { + return button + } + + if (typeof tooltip === "string") { + tooltip = { + children: tooltip, + } + } + + return ( + <Tooltip> + <TooltipTrigger asChild>{button}</TooltipTrigger> + <TooltipContent + side="right" + align="center" + hidden={state !== "collapsed" || isMobile} + {...tooltip} + /> + </Tooltip> + ) + } +) +SidebarMenuButton.displayName = "SidebarMenuButton" + +const SidebarMenuAction = React.forwardRef< + HTMLButtonElement, + React.ComponentProps<"button"> & { + asChild?: boolean + showOnHover?: boolean + } +>(({ className, asChild = false, showOnHover = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + + return ( + <Comp + ref={ref} + data-sidebar="menu-action" + className={cn( + "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0", + // Increases the hit area of the button on mobile. + "after:absolute after:-inset-2 after:md:hidden", + "peer-data-[size=sm]/menu-button:top-1", + "peer-data-[size=default]/menu-button:top-1.5", + "peer-data-[size=lg]/menu-button:top-2.5", + "group-data-[collapsible=icon]:hidden", + showOnHover && + "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0", + className + )} + {...props} + /> + ) +}) +SidebarMenuAction.displayName = "SidebarMenuAction" + +const SidebarMenuBadge = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + data-sidebar="menu-badge" + className={cn( + "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground", + "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground", + "peer-data-[size=sm]/menu-button:top-1", + "peer-data-[size=default]/menu-button:top-1.5", + "peer-data-[size=lg]/menu-button:top-2.5", + "group-data-[collapsible=icon]:hidden", + className + )} + {...props} + /> +)) +SidebarMenuBadge.displayName = "SidebarMenuBadge" + +const SidebarMenuSkeleton = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { + showIcon?: boolean + } +>(({ className, showIcon = false, ...props }, ref) => { + // Random width between 50 to 90%. + const width = React.useMemo(() => { + return `${Math.floor(Math.random() * 40) + 50}%` + }, []) + + return ( + <div + ref={ref} + data-sidebar="menu-skeleton" + className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)} + {...props} + > + {showIcon && ( + <Skeleton + className="size-4 rounded-md" + data-sidebar="menu-skeleton-icon" + /> + )} + <Skeleton + className="h-4 max-w-[--skeleton-width] flex-1" + data-sidebar="menu-skeleton-text" + style={ + { + "--skeleton-width": width, + } as React.CSSProperties + } + /> + </div> + ) +}) +SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton" + +const SidebarMenuSub = React.forwardRef< + HTMLUListElement, + React.ComponentProps<"ul"> +>(({ className, ...props }, ref) => ( + <ul + ref={ref} + data-sidebar="menu-sub" + className={cn( + "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5", + "group-data-[collapsible=icon]:hidden", + className + )} + {...props} + /> +)) +SidebarMenuSub.displayName = "SidebarMenuSub" + +const SidebarMenuSubItem = React.forwardRef< + HTMLLIElement, + React.ComponentProps<"li"> +>(({ ...props }, ref) => <li ref={ref} {...props} />) +SidebarMenuSubItem.displayName = "SidebarMenuSubItem" + +const SidebarMenuSubButton = React.forwardRef< + HTMLAnchorElement, + React.ComponentProps<"a"> & { + asChild?: boolean + size?: "sm" | "md" + isActive?: boolean + } +>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => { + const Comp = asChild ? Slot : "a" + + return ( + <Comp + ref={ref} + data-sidebar="menu-sub-button" + data-size={size} + data-active={isActive} + className={cn( + "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground", + "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground", + size === "sm" && "text-xs", + size === "md" && "text-sm", + "group-data-[collapsible=icon]:hidden", + className + )} + {...props} + /> + ) +}) +SidebarMenuSubButton.displayName = "SidebarMenuSubButton" + +export { + Sidebar, + SidebarContent, + SidebarFooter, + SidebarGroup, + SidebarGroupAction, + SidebarGroupContent, + SidebarGroupLabel, + SidebarHeader, + SidebarInput, + SidebarInset, + SidebarMenu, + SidebarMenuAction, + SidebarMenuBadge, + SidebarMenuButton, + SidebarMenuItem, + SidebarMenuSkeleton, + SidebarMenuSub, + SidebarMenuSubButton, + SidebarMenuSubItem, + SidebarProvider, + SidebarRail, + SidebarSeparator, + SidebarTrigger, + useSidebar, +} diff --git a/pkg/ui/frontend/src/components/ui/skeleton.tsx b/pkg/ui/frontend/src/components/ui/skeleton.tsx new file mode 100644 index 0000000000000..d7e45f7bd315f --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/skeleton.tsx @@ -0,0 +1,15 @@ +import { cn } from "@/lib/utils" + +function Skeleton({ + className, + ...props +}: React.HTMLAttributes<HTMLDivElement>) { + return ( + <div + className={cn("animate-pulse rounded-md bg-primary/10", className)} + {...props} + /> + ) +} + +export { Skeleton } diff --git a/pkg/ui/frontend/src/components/ui/switch.tsx b/pkg/ui/frontend/src/components/ui/switch.tsx new file mode 100644 index 0000000000000..455c23b6cd5ad --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/switch.tsx @@ -0,0 +1,27 @@ +import * as React from "react" +import * as SwitchPrimitives from "@radix-ui/react-switch" + +import { cn } from "@/lib/utils" + +const Switch = React.forwardRef< + React.ElementRef<typeof SwitchPrimitives.Root>, + React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> +>(({ className, ...props }, ref) => ( + <SwitchPrimitives.Root + className={cn( + "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input", + className + )} + {...props} + ref={ref} + > + <SwitchPrimitives.Thumb + className={cn( + "pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" + )} + /> + </SwitchPrimitives.Root> +)) +Switch.displayName = SwitchPrimitives.Root.displayName + +export { Switch } diff --git a/pkg/ui/frontend/src/components/ui/table.tsx b/pkg/ui/frontend/src/components/ui/table.tsx new file mode 100644 index 0000000000000..c0df655c0bf26 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/table.tsx @@ -0,0 +1,120 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Table = React.forwardRef< + HTMLTableElement, + React.HTMLAttributes<HTMLTableElement> +>(({ className, ...props }, ref) => ( + <div className="relative w-full overflow-auto"> + <table + ref={ref} + className={cn("w-full caption-bottom text-sm", className)} + {...props} + /> + </div> +)) +Table.displayName = "Table" + +const TableHeader = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes<HTMLTableSectionElement> +>(({ className, ...props }, ref) => ( + <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} /> +)) +TableHeader.displayName = "TableHeader" + +const TableBody = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes<HTMLTableSectionElement> +>(({ className, ...props }, ref) => ( + <tbody + ref={ref} + className={cn("[&_tr:last-child]:border-0", className)} + {...props} + /> +)) +TableBody.displayName = "TableBody" + +const TableFooter = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes<HTMLTableSectionElement> +>(({ className, ...props }, ref) => ( + <tfoot + ref={ref} + className={cn( + "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", + className + )} + {...props} + /> +)) +TableFooter.displayName = "TableFooter" + +const TableRow = React.forwardRef< + HTMLTableRowElement, + React.HTMLAttributes<HTMLTableRowElement> +>(({ className, ...props }, ref) => ( + <tr + ref={ref} + className={cn( + "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", + className + )} + {...props} + /> +)) +TableRow.displayName = "TableRow" + +const TableHead = React.forwardRef< + HTMLTableCellElement, + React.ThHTMLAttributes<HTMLTableCellElement> +>(({ className, ...props }, ref) => ( + <th + ref={ref} + className={cn( + "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", + className + )} + {...props} + /> +)) +TableHead.displayName = "TableHead" + +const TableCell = React.forwardRef< + HTMLTableCellElement, + React.TdHTMLAttributes<HTMLTableCellElement> +>(({ className, ...props }, ref) => ( + <td + ref={ref} + className={cn( + "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", + className + )} + {...props} + /> +)) +TableCell.displayName = "TableCell" + +const TableCaption = React.forwardRef< + HTMLTableCaptionElement, + React.HTMLAttributes<HTMLTableCaptionElement> +>(({ className, ...props }, ref) => ( + <caption + ref={ref} + className={cn("mt-4 text-sm text-muted-foreground", className)} + {...props} + /> +)) +TableCaption.displayName = "TableCaption" + +export { + Table, + TableHeader, + TableBody, + TableFooter, + TableHead, + TableRow, + TableCell, + TableCaption, +} diff --git a/pkg/ui/frontend/src/components/ui/tabs.tsx b/pkg/ui/frontend/src/components/ui/tabs.tsx new file mode 100644 index 0000000000000..85d83beab3224 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/tabs.tsx @@ -0,0 +1,53 @@ +import * as React from "react" +import * as TabsPrimitive from "@radix-ui/react-tabs" + +import { cn } from "@/lib/utils" + +const Tabs = TabsPrimitive.Root + +const TabsList = React.forwardRef< + React.ElementRef<typeof TabsPrimitive.List>, + React.ComponentPropsWithoutRef<typeof TabsPrimitive.List> +>(({ className, ...props }, ref) => ( + <TabsPrimitive.List + ref={ref} + className={cn( + "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground", + className + )} + {...props} + /> +)) +TabsList.displayName = TabsPrimitive.List.displayName + +const TabsTrigger = React.forwardRef< + React.ElementRef<typeof TabsPrimitive.Trigger>, + React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger> +>(({ className, ...props }, ref) => ( + <TabsPrimitive.Trigger + ref={ref} + className={cn( + "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow", + className + )} + {...props} + /> +)) +TabsTrigger.displayName = TabsPrimitive.Trigger.displayName + +const TabsContent = React.forwardRef< + React.ElementRef<typeof TabsPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content> +>(({ className, ...props }, ref) => ( + <TabsPrimitive.Content + ref={ref} + className={cn( + "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", + className + )} + {...props} + /> +)) +TabsContent.displayName = TabsPrimitive.Content.displayName + +export { Tabs, TabsList, TabsTrigger, TabsContent } diff --git a/pkg/ui/frontend/src/components/ui/textarea.tsx b/pkg/ui/frontend/src/components/ui/textarea.tsx new file mode 100644 index 0000000000000..e56b0affd7e03 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/textarea.tsx @@ -0,0 +1,22 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Textarea = React.forwardRef< + HTMLTextAreaElement, + React.ComponentProps<"textarea"> +>(({ className, ...props }, ref) => { + return ( + <textarea + className={cn( + "flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", + className + )} + ref={ref} + {...props} + /> + ) +}) +Textarea.displayName = "Textarea" + +export { Textarea } diff --git a/pkg/ui/frontend/src/components/ui/toast.tsx b/pkg/ui/frontend/src/components/ui/toast.tsx new file mode 100644 index 0000000000000..2ddb7c5a838eb --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/toast.tsx @@ -0,0 +1,127 @@ +import * as React from "react" +import * as ToastPrimitives from "@radix-ui/react-toast" +import { cva, type VariantProps } from "class-variance-authority" +import { X } from "lucide-react" + +import { cn } from "@/lib/utils" + +const ToastProvider = ToastPrimitives.Provider + +const ToastViewport = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Viewport>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport> +>(({ className, ...props }, ref) => ( + <ToastPrimitives.Viewport + ref={ref} + className={cn( + "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", + className + )} + {...props} + /> +)) +ToastViewport.displayName = ToastPrimitives.Viewport.displayName + +const toastVariants = cva( + "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", + { + variants: { + variant: { + default: "border bg-background text-foreground", + destructive: + "destructive group border-destructive bg-destructive text-destructive-foreground", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +const Toast = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Root>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & + VariantProps<typeof toastVariants> +>(({ className, variant, ...props }, ref) => { + return ( + <ToastPrimitives.Root + ref={ref} + className={cn(toastVariants({ variant }), className)} + {...props} + /> + ) +}) +Toast.displayName = ToastPrimitives.Root.displayName + +const ToastAction = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Action>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action> +>(({ className, ...props }, ref) => ( + <ToastPrimitives.Action + ref={ref} + className={cn( + "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", + className + )} + {...props} + /> +)) +ToastAction.displayName = ToastPrimitives.Action.displayName + +const ToastClose = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Close>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close> +>(({ className, ...props }, ref) => ( + <ToastPrimitives.Close + ref={ref} + className={cn( + "absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", + className + )} + toast-close="" + {...props} + > + <X className="h-4 w-4" /> + </ToastPrimitives.Close> +)) +ToastClose.displayName = ToastPrimitives.Close.displayName + +const ToastTitle = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Title>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title> +>(({ className, ...props }, ref) => ( + <ToastPrimitives.Title + ref={ref} + className={cn("text-sm font-semibold [&+div]:text-xs", className)} + {...props} + /> +)) +ToastTitle.displayName = ToastPrimitives.Title.displayName + +const ToastDescription = React.forwardRef< + React.ElementRef<typeof ToastPrimitives.Description>, + React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description> +>(({ className, ...props }, ref) => ( + <ToastPrimitives.Description + ref={ref} + className={cn("text-sm opacity-90", className)} + {...props} + /> +)) +ToastDescription.displayName = ToastPrimitives.Description.displayName + +type ToastProps = React.ComponentPropsWithoutRef<typeof Toast> + +type ToastActionElement = React.ReactElement<typeof ToastAction> + +export { + type ToastProps, + type ToastActionElement, + ToastProvider, + ToastViewport, + Toast, + ToastTitle, + ToastDescription, + ToastClose, + ToastAction, +} diff --git a/pkg/ui/frontend/src/components/ui/toaster.tsx b/pkg/ui/frontend/src/components/ui/toaster.tsx new file mode 100644 index 0000000000000..6c67edff67a48 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/toaster.tsx @@ -0,0 +1,33 @@ +import { useToast } from "@/hooks/use-toast" +import { + Toast, + ToastClose, + ToastDescription, + ToastProvider, + ToastTitle, + ToastViewport, +} from "@/components/ui/toast" + +export function Toaster() { + const { toasts } = useToast() + + return ( + <ToastProvider> + {toasts.map(function ({ id, title, description, action, ...props }) { + return ( + <Toast key={id} {...props}> + <div className="grid gap-1"> + {title && <ToastTitle>{title}</ToastTitle>} + {description && ( + <ToastDescription>{description}</ToastDescription> + )} + </div> + {action} + <ToastClose /> + </Toast> + ) + })} + <ToastViewport /> + </ToastProvider> + ) +} diff --git a/pkg/ui/frontend/src/components/ui/toggle-group.tsx b/pkg/ui/frontend/src/components/ui/toggle-group.tsx new file mode 100644 index 0000000000000..afe5da62559ca --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/toggle-group.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group" +import { type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" +import { toggleVariants } from "@/components/ui/toggle" + +const ToggleGroupContext = React.createContext< + VariantProps<typeof toggleVariants> +>({ + size: "default", + variant: "default", +}) + +const ToggleGroup = React.forwardRef< + React.ElementRef<typeof ToggleGroupPrimitive.Root>, + React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & + VariantProps<typeof toggleVariants> +>(({ className, variant, size, children, ...props }, ref) => ( + <ToggleGroupPrimitive.Root + ref={ref} + className={cn("flex items-center justify-center gap-1", className)} + {...props} + > + <ToggleGroupContext.Provider value={{ variant, size }}> + {children} + </ToggleGroupContext.Provider> + </ToggleGroupPrimitive.Root> +)) + +ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName + +const ToggleGroupItem = React.forwardRef< + React.ElementRef<typeof ToggleGroupPrimitive.Item>, + React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> & + VariantProps<typeof toggleVariants> +>(({ className, children, variant, size, ...props }, ref) => { + const context = React.useContext(ToggleGroupContext) + + return ( + <ToggleGroupPrimitive.Item + ref={ref} + className={cn( + toggleVariants({ + variant: context.variant || variant, + size: context.size || size, + }), + className + )} + {...props} + > + {children} + </ToggleGroupPrimitive.Item> + ) +}) + +ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName + +export { ToggleGroup, ToggleGroupItem } diff --git a/pkg/ui/frontend/src/components/ui/toggle.tsx b/pkg/ui/frontend/src/components/ui/toggle.tsx new file mode 100644 index 0000000000000..db35d78be4122 --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/toggle.tsx @@ -0,0 +1,45 @@ +"use client" + +import * as React from "react" +import * as TogglePrimitive from "@radix-ui/react-toggle" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const toggleVariants = cva( + "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", + { + variants: { + variant: { + default: "bg-transparent", + outline: + "border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground", + }, + size: { + default: "h-9 px-2 min-w-9", + sm: "h-8 px-1.5 min-w-8", + lg: "h-10 px-2.5 min-w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +const Toggle = React.forwardRef< + React.ElementRef<typeof TogglePrimitive.Root>, + React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & + VariantProps<typeof toggleVariants> +>(({ className, variant, size, ...props }, ref) => ( + <TogglePrimitive.Root + ref={ref} + className={cn(toggleVariants({ variant, size, className }))} + {...props} + /> +)) + +Toggle.displayName = TogglePrimitive.Root.displayName + +export { Toggle, toggleVariants } diff --git a/pkg/ui/frontend/src/components/ui/tooltip.tsx b/pkg/ui/frontend/src/components/ui/tooltip.tsx new file mode 100644 index 0000000000000..218d1835f790e --- /dev/null +++ b/pkg/ui/frontend/src/components/ui/tooltip.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import * as TooltipPrimitive from "@radix-ui/react-tooltip" + +import { cn } from "@/lib/utils" + +const TooltipProvider = TooltipPrimitive.Provider + +const Tooltip = TooltipPrimitive.Root + +const TooltipTrigger = TooltipPrimitive.Trigger + +const TooltipContent = React.forwardRef< + React.ElementRef<typeof TooltipPrimitive.Content>, + React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> +>(({ className, sideOffset = 4, ...props }, ref) => ( + <TooltipPrimitive.Portal> + <TooltipPrimitive.Content + ref={ref} + sideOffset={sideOffset} + className={cn( + "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + className + )} + {...props} + /> + </TooltipPrimitive.Portal> +)) +TooltipContent.displayName = TooltipPrimitive.Content.displayName + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } diff --git a/pkg/ui/frontend/src/components/version-display.tsx b/pkg/ui/frontend/src/components/version-display.tsx new file mode 100644 index 0000000000000..2067fcbed3328 --- /dev/null +++ b/pkg/ui/frontend/src/components/version-display.tsx @@ -0,0 +1,97 @@ +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; +import { useVersionInfo } from "@/hooks/use-version-info"; +import { Loader2 } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { useState } from "react"; +import { CopyButton } from "@/components/common/copy-button"; + +export function VersionDisplay() { + const { mostCommonVersion, versionInfos, isLoading } = useVersionInfo(); + const [isOpen, setIsOpen] = useState(false); + + const getVersionText = () => { + return versionInfos + .map( + ({ version, info }) => `Version: ${version} +Revision: ${info.revision} +Branch: ${info.branch} +Build User: ${info.buildUser} +Build Date: ${info.buildDate} +Go Version: ${info.goVersion} +` + ) + .join("\n"); + }; + + return ( + <HoverCard open={isOpen} onOpenChange={setIsOpen}> + <HoverCardTrigger asChild> + <span className="text-sm text-muted-foreground flex items-center gap-1"> + <button + onClick={() => setIsOpen(!isOpen)} + className={cn( + "transition-opacity duration-200 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded px-1 -mx-1", + { + "opacity-0": isLoading, + "opacity-100": !isLoading, + } + )} + > + {mostCommonVersion} + </button> + {isLoading && ( + <> + <Loader2 className="h-3 w-3 animate-spin" /> + Loading... + </> + )} + </span> + </HoverCardTrigger> + <HoverCardContent side="bottom" align="start" className="w-[400px]"> + <div className="p-2"> + <div className="flex items-center justify-between mb-2"> + <div className="font-semibold">Build Information</div> + {!isLoading && versionInfos.length > 0 && ( + <CopyButton text={getVersionText()} /> + )} + </div> + <div + className={cn("transition-opacity duration-200", { + "opacity-0": isLoading, + "opacity-100": !isLoading, + })} + > + {versionInfos.length > 0 ? ( + versionInfos.map(({ version, info }) => ( + <div key={version} className="mb-2 last:mb-0"> + <div className="font-semibold">{version}</div> + <div className="text-sm"> + <div>Revision: {info.revision}</div> + <div>Branch: {info.branch}</div> + <div>Build User: {info.buildUser}</div> + <div>Build Date: {info.buildDate}</div> + <div>Go Version: {info.goVersion}</div> + </div> + </div> + )) + ) : ( + <div className="text-sm text-muted-foreground"> + No build information available + </div> + )} + </div> + {isLoading && ( + <div className="flex items-center gap-2"> + <Loader2 className="h-4 w-4 animate-spin" /> + <span>Loading build information...</span> + </div> + )} + </div> + </HoverCardContent> + </HoverCard> + ); +} diff --git a/pkg/ui/frontend/src/config/routes.tsx b/pkg/ui/frontend/src/config/routes.tsx new file mode 100644 index 0000000000000..6e3cb89f7dbb6 --- /dev/null +++ b/pkg/ui/frontend/src/config/routes.tsx @@ -0,0 +1,114 @@ +import { + NodeBreadcrumb, + RingBreadcrumb, +} from "@/components/shared/route-breadcrumbs"; +import { NotFound } from "@/components/shared/errors/not-found"; +import Ring from "@/pages/ring"; +import { RouteObject } from "react-router-dom"; +import { DataObjectsPage } from "@/pages/data-objects"; +import { FileMetadataPage } from "@/pages/file-metadata"; +import Nodes from "@/pages/nodes"; +import { BreadcrumbComponentType } from "use-react-router-breadcrumbs"; +import NodeDetails from "@/pages/node-details"; +import ComingSoon from "@/pages/coming-soon"; +import DeletesPage from "@/pages/deletes"; +import NewDeleteRequest from "@/pages/new-delete"; +import AnalyzeLabels from "@/pages/analyze-labels"; + +type RouteObjectWithBreadcrumb = Omit<RouteObject, "children"> & { + breadcrumb: string | BreadcrumbComponentType; +}; + +// Routes configuration for breadcrumbs +export const routes: RouteObjectWithBreadcrumb[] = [ + { + path: "/", + breadcrumb: "Home", + element: <Nodes />, + }, + { + path: "/nodes", + breadcrumb: "Nodes", + element: <Nodes />, + }, + { + path: "/nodes/:nodeName", + breadcrumb: NodeBreadcrumb, + element: <NodeDetails />, + }, + { + path: "/versions", + breadcrumb: "Versions", + element: <ComingSoon />, + }, + { + path: "/rings", + breadcrumb: "Rings", + element: <Ring />, + }, + { + path: "/rings/:ringName", + breadcrumb: RingBreadcrumb, + element: <Ring />, + }, + { + path: "/storage", + breadcrumb: "Storage", + element: <ComingSoon />, + }, + { + path: "/storage/object", + breadcrumb: "Object Storage", + element: <ComingSoon />, + }, + { + path: "/storage/dataobj", + breadcrumb: "Data Objects", + element: <DataObjectsPage />, + }, + { + path: "/storage/dataobj/metadata", + breadcrumb: "File Metadata", + element: <FileMetadataPage />, + }, + { + path: "/tenants", + breadcrumb: "Tenants", + element: <ComingSoon />, + }, + { + path: "/tenants/deletes", + breadcrumb: "Deletes", + element: <DeletesPage />, + }, + { + path: "/tenants/deletes/new", + element: <NewDeleteRequest />, + breadcrumb: "New Delete Request", + }, + { + path: "/tenants/analyze-labels", + element: <AnalyzeLabels />, + breadcrumb: "Analyze Labels", + }, + { + path: "/tenants/limits", + breadcrumb: "Limits", + element: <ComingSoon />, + }, + { + path: "/tenants/labels", + breadcrumb: "Labels", + element: <ComingSoon />, + }, + { + path: "/rules", + breadcrumb: "Rules", + element: <ComingSoon />, + }, + { + path: "/404", + breadcrumb: "404", + element: <NotFound />, + }, +]; diff --git a/pkg/ui/frontend/src/contexts/cluster-context.ts b/pkg/ui/frontend/src/contexts/cluster-context.ts new file mode 100644 index 0000000000000..2105494063362 --- /dev/null +++ b/pkg/ui/frontend/src/contexts/cluster-context.ts @@ -0,0 +1,12 @@ +import { createContext } from "react"; +import { ClusterContextValue } from "./types"; + +const initialContextValue: ClusterContextValue = { + cluster: null, + error: null, + isLoading: true, + refresh: () => Promise.resolve(), +}; + +export const ClusterContext = + createContext<ClusterContextValue>(initialContextValue); diff --git a/pkg/ui/frontend/src/contexts/cluster-provider.tsx b/pkg/ui/frontend/src/contexts/cluster-provider.tsx new file mode 100644 index 0000000000000..bfb31ec4d1030 --- /dev/null +++ b/pkg/ui/frontend/src/contexts/cluster-provider.tsx @@ -0,0 +1,54 @@ +import { useState, useCallback, useRef, useEffect, ReactNode } from "react"; +import { Cluster } from "@/types/cluster"; +import { ClusterContext } from "./cluster-context"; + +interface ClusterProviderProps { + children: ReactNode; +} + +export function ClusterProvider({ children }: ClusterProviderProps) { + const [cluster, setCluster] = useState<Cluster | null>(null); + const [error, setError] = useState<string | null>(null); + const [isLoading, setIsLoading] = useState(true); + const isFetchingRef = useRef(false); + + const fetchCluster = useCallback(async () => { + if (isFetchingRef.current) { + return; + } + + isFetchingRef.current = true; + setIsLoading(true); + + try { + const response = await fetch("/ui/api/v1/cluster/nodes"); + if (!response.ok) { + throw new Error(`Failed to fetch cluster data: ${response.statusText}`); + } + const data = await response.json(); + setCluster(data); + setError(null); + } catch (err) { + setError( + err instanceof Error ? err.message : "An unknown error occurred" + ); + } finally { + setIsLoading(false); + isFetchingRef.current = false; + } + }, []); + + const refresh = useCallback(async () => { + await fetchCluster(); + }, [fetchCluster]); + + useEffect(() => { + fetchCluster(); + }, [fetchCluster]); + + return ( + <ClusterContext.Provider value={{ cluster, error, isLoading, refresh }}> + {children} + </ClusterContext.Provider> + ); +} diff --git a/pkg/ui/frontend/src/contexts/index.ts b/pkg/ui/frontend/src/contexts/index.ts new file mode 100644 index 0000000000000..30aa05ef2f7b7 --- /dev/null +++ b/pkg/ui/frontend/src/contexts/index.ts @@ -0,0 +1,4 @@ +export * from "./cluster-context"; +export * from "./cluster-provider"; +export * from "./use-cluster"; +export * from "./types"; diff --git a/pkg/ui/frontend/src/contexts/types.ts b/pkg/ui/frontend/src/contexts/types.ts new file mode 100644 index 0000000000000..b91009c76c9c4 --- /dev/null +++ b/pkg/ui/frontend/src/contexts/types.ts @@ -0,0 +1,18 @@ +import { Cluster } from "@/types/cluster"; + +export interface ClusterContextValue { + cluster: Cluster | null; + error: string | null; + isLoading: boolean; + refresh: () => Promise<void>; +} + +export interface BreadcrumbItem { + title: string; + path: string; +} + +export interface BreadcrumbContextType { + items: BreadcrumbItem[]; + setBreadcrumb: (items: BreadcrumbItem[]) => void; +} diff --git a/pkg/ui/frontend/src/contexts/use-cluster.ts b/pkg/ui/frontend/src/contexts/use-cluster.ts new file mode 100644 index 0000000000000..ec9368a728cba --- /dev/null +++ b/pkg/ui/frontend/src/contexts/use-cluster.ts @@ -0,0 +1,11 @@ +import { useContext } from "react"; +import { ClusterContextValue } from "./types"; +import { ClusterContext } from "./cluster-context"; + +export function useCluster(): ClusterContextValue { + const context = useContext(ClusterContext); + if (!context) { + throw new Error("useCluster must be used within a ClusterProvider"); + } + return context; +} diff --git a/pkg/ui/frontend/src/features/theme/components/theme-provider.tsx b/pkg/ui/frontend/src/features/theme/components/theme-provider.tsx new file mode 100644 index 0000000000000..6b4d1d68ebce4 --- /dev/null +++ b/pkg/ui/frontend/src/features/theme/components/theme-provider.tsx @@ -0,0 +1,44 @@ +import { useEffect, useState } from "react"; +import { Theme, ThemeContext, ThemeProviderProps } from "../theme-context"; + +export function ThemeProvider({ + children, + defaultTheme = "light", + storageKey = "loki-ui-theme", + ...props +}: ThemeProviderProps) { + const [theme, setTheme] = useState<Theme>(() => { + try { + const storedTheme = localStorage.getItem(storageKey); + return storedTheme === "dark" || storedTheme === "light" + ? storedTheme + : defaultTheme; + } catch { + return defaultTheme; + } + }); + + const handleThemeChange = (newTheme: Theme) => { + try { + localStorage.setItem(storageKey, newTheme); + setTheme(newTheme); + } catch (error) { + console.error("Failed to save theme:", error); + } + }; + + useEffect(() => { + const root = window.document.documentElement; + root.classList.remove("light", "dark"); + root.classList.add(theme); + }, [theme]); + + return ( + <ThemeContext.Provider + value={{ theme, setTheme: handleThemeChange }} + {...props} + > + {children} + </ThemeContext.Provider> + ); +} diff --git a/pkg/ui/frontend/src/features/theme/components/theme-toggle.tsx b/pkg/ui/frontend/src/features/theme/components/theme-toggle.tsx new file mode 100644 index 0000000000000..db558eb8b4447 --- /dev/null +++ b/pkg/ui/frontend/src/features/theme/components/theme-toggle.tsx @@ -0,0 +1,28 @@ +import { Moon, Sun } from "lucide-react"; +import { useTheme } from "../theme-context"; +import { Button } from "../../../components/ui/button"; + +export function ThemeToggle() { + const { theme, setTheme } = useTheme(); + + const handleThemeChange = () => { + const newTheme = theme === "light" ? "dark" : "light"; + setTheme(newTheme); + }; + + return ( + <Button + variant="ghost" + size="icon" + className="bg-muted hover:bg-muted-hover rounded-lg" + onClick={handleThemeChange} + > + {theme === "light" ? ( + <Sun className="h-[1.2rem] w-[1.2rem]" /> + ) : ( + <Moon className="h-[1.2rem] w-[1.2rem]" /> + )} + <span className="sr-only">Toggle theme</span> + </Button> + ); +} diff --git a/pkg/ui/frontend/src/features/theme/index.ts b/pkg/ui/frontend/src/features/theme/index.ts new file mode 100644 index 0000000000000..c0e6ccd762d1e --- /dev/null +++ b/pkg/ui/frontend/src/features/theme/index.ts @@ -0,0 +1,3 @@ +export * from "./theme-context"; +export { ThemeProvider } from "./components/theme-provider"; +export { ThemeToggle } from "./components/theme-toggle"; diff --git a/pkg/ui/frontend/src/features/theme/theme-context.ts b/pkg/ui/frontend/src/features/theme/theme-context.ts new file mode 100644 index 0000000000000..34ca21caf3929 --- /dev/null +++ b/pkg/ui/frontend/src/features/theme/theme-context.ts @@ -0,0 +1,29 @@ +import { createContext, useContext } from "react"; + +export type Theme = "dark" | "light"; + +export type ThemeProviderProps = { + children: React.ReactNode; + defaultTheme?: Theme; + storageKey?: string; +}; + +export type ThemeContextType = { + theme: Theme; + setTheme: (theme: Theme) => void; +}; + +export const initialState: ThemeContextType = { + theme: "light", + setTheme: () => null, +}; + +export const ThemeContext = createContext<ThemeContextType>(initialState); + +export function useTheme() { + const context = useContext(ThemeContext); + if (context === undefined) { + throw new Error("useTheme must be used within a ThemeProvider"); + } + return context; +} diff --git a/pkg/ui/frontend/src/hooks/index.ts b/pkg/ui/frontend/src/hooks/index.ts new file mode 100644 index 0000000000000..66e4e766a7acf --- /dev/null +++ b/pkg/ui/frontend/src/hooks/index.ts @@ -0,0 +1,5 @@ +export * from "./use-version-info"; +export * from "./use-node-details"; +export * from "./use-node-metrics"; +export * from "./use-log-level"; +export * from "./use-mobile"; diff --git a/pkg/ui/frontend/src/hooks/use-explorer-data.ts b/pkg/ui/frontend/src/hooks/use-explorer-data.ts new file mode 100644 index 0000000000000..bc21b1c65e864 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-explorer-data.ts @@ -0,0 +1,52 @@ +import { useQuery } from "@tanstack/react-query"; +import { ExplorerData, ExplorerFile } from "@/types/explorer"; +import { useCluster } from "@/contexts/use-cluster"; +import { useMemo } from "react"; +import { findNodeName } from "@/lib/utils"; + +// mux.HandleFunc("/api/v1/dataobj/list", s.handleList) +// mux.HandleFunc("/api/v1/dataobj/inspect", s.handleInspect) +// mux.HandleFunc("/api/v1/dataobj/download", s.handleDownload) +// mux.HandleFunc("/api/v1/dataobj/provider", s.handleProvider) + +export function useExplorerData(path: string) { + const { cluster } = useCluster(); + + const nodeName = useMemo(() => { + return findNodeName(cluster?.members, "dataobj-explorer"); + }, [cluster?.members]); + + return useQuery<ExplorerData>({ + queryKey: ["explorer", path, nodeName], + queryFn: async () => { + if (!nodeName) { + throw new Error("Node name not found"); + } + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/dataobj/api/v1/list?path=${encodeURIComponent( + path + )}` + ); + if (!response.ok) { + throw new Error("Failed to fetch explorer data"); + } + const data = (await response.json()) as ExplorerData; + return { + ...data, + files: sortFilesByDate(data.files).map((file) => ({ + ...file, + downloadUrl: `/api/v1/proxy/${nodeName}/dataobj/api/v1/download?file=${encodeURIComponent( + path ? `${path}/${file.name}` : file.name + )}`, + })), + }; + }, + }); +} + +const sortFilesByDate = (files: ExplorerFile[]): ExplorerFile[] => { + return [...files].sort( + (a, b) => + new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime() + ); +}; diff --git a/pkg/ui/frontend/src/hooks/use-file-metadata.ts b/pkg/ui/frontend/src/hooks/use-file-metadata.ts new file mode 100644 index 0000000000000..7038af5e5c462 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-file-metadata.ts @@ -0,0 +1,36 @@ +import { useQuery } from "@tanstack/react-query"; +import { findNodeName } from "@/lib/utils"; +import { useCluster } from "@/contexts/use-cluster"; +import { useMemo } from "react"; +import { FileMetadataResponse } from "@/types/explorer"; + +export function useFileMetadata(path: string | undefined) { + const { cluster } = useCluster(); + const nodeName = useMemo(() => { + return findNodeName(cluster?.members, "dataobj-explorer"); + }, [cluster?.members]); + const downloadUrl = useMemo(() => { + return `/api/v1/proxy/${nodeName}/dataobj/api/v1/download?file=${encodeURIComponent( + path || "" + )}`; + }, [path, nodeName]); + const query = useQuery<FileMetadataResponse>({ + queryKey: ["file-metadata", path, nodeName], + queryFn: async () => { + if (!path) throw new Error("No file path provided"); + if (!nodeName) throw new Error("Node name not found"); + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/dataobj/api/v1/inspect?file=${encodeURIComponent( + path + )}` + ); + if (!response.ok) { + throw new Error("Failed to fetch file metadata"); + } + return response.json(); + }, + enabled: !!path && !!nodeName, + }); + + return { ...query, downloadUrl }; +} diff --git a/pkg/ui/frontend/src/hooks/use-log-level.ts b/pkg/ui/frontend/src/hooks/use-log-level.ts new file mode 100644 index 0000000000000..da3e564d03402 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-log-level.ts @@ -0,0 +1,92 @@ +import { useState, useEffect } from "react"; + +interface LogLevelResponse { + status: string; + message: string; +} + +interface UseLogLevelResult { + logLevel: string; + isLoading: boolean; + error: string | null; + success: boolean; + setLogLevel: (level: string) => Promise<void>; +} + +export function useLogLevel(nodeName: string | undefined): UseLogLevelResult { + const [logLevel, setLogLevelState] = useState<string>("info"); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState<string | null>(null); + const [success, setSuccess] = useState(false); + + const parseLogLevel = (response: LogLevelResponse): string => { + const match = response.message.match(/Current log level is (\w+)/); + return match?.[1] || "info"; + }; + + useEffect(() => { + async function fetchLogLevel() { + if (!nodeName) return; + + setIsLoading(true); + setError(null); + + try { + const res = await fetch(`/ui/api/v1/proxy/${nodeName}/log_level`); + if (!res.ok) + throw new Error(`Failed to fetch log level: ${res.statusText}`); + const data: LogLevelResponse = await res.json(); + setLogLevelState(parseLogLevel(data)); + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to fetch log level" + ); + } finally { + setIsLoading(false); + } + } + + fetchLogLevel(); + }, [nodeName]); + + const setLogLevel = async (level: string) => { + if (!nodeName) return; + + setIsLoading(true); + setError(null); + setSuccess(false); + + try { + const res = await fetch( + `/ui/api/v1/proxy/${nodeName}/log_level?log_level=${level}`, + { method: "POST" } + ); + if (!res.ok) + throw new Error(`Failed to update log level: ${res.statusText}`); + const data: LogLevelResponse = await res.json(); + + if (data.status === "success" && data.message.includes(level)) { + setLogLevelState(level); + setSuccess(true); + // Reset success state after 3 seconds + setTimeout(() => setSuccess(false), 3000); + } else { + throw new Error("Failed to update log level: Unexpected response"); + } + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to update log level" + ); + } finally { + setIsLoading(false); + } + }; + + return { + logLevel, + isLoading, + error, + success, + setLogLevel, + }; +} diff --git a/pkg/ui/frontend/src/hooks/use-mobile.tsx b/pkg/ui/frontend/src/hooks/use-mobile.tsx new file mode 100644 index 0000000000000..2b0fe1dfef3b1 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-mobile.tsx @@ -0,0 +1,19 @@ +import * as React from "react" + +const MOBILE_BREAKPOINT = 768 + +export function useIsMobile() { + const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined) + + React.useEffect(() => { + const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) + const onChange = () => { + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) + } + mql.addEventListener("change", onChange) + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) + return () => mql.removeEventListener("change", onChange) + }, []) + + return !!isMobile +} diff --git a/pkg/ui/frontend/src/hooks/use-node-details.ts b/pkg/ui/frontend/src/hooks/use-node-details.ts new file mode 100644 index 0000000000000..78928e6e96e72 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-node-details.ts @@ -0,0 +1,77 @@ +import { useState, useEffect } from "react"; + +interface NodeMetrics { + store_object_type?: string; + distributor_replication_factor?: number; + [key: string]: string | number | boolean | undefined; +} + +interface NodeDetails { + services: Array<{ service: string; status: string }>; + build: { + version: string; + revision: string; + branch: string; + buildUser: string; + buildDate: string; + goVersion: string; + }; + config: string; + target: string; + clusterID: string; + clusterSeededAt: number; + os: string; + arch: string; + edition: string; + metrics: NodeMetrics; +} + +interface UseNodeDetailsResult { + nodeDetails: NodeDetails | null; + isLoading: boolean; + error: string | null; +} + +export function useNodeDetails( + nodeName: string | undefined +): UseNodeDetailsResult { + const [nodeDetails, setNodeDetails] = useState<NodeDetails | null>(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState<string | null>(null); + + useEffect(() => { + if (!nodeName) { + setError("Node name is required"); + return; + } + + setIsLoading(true); + setError(null); + + fetch(`/ui/api/v1/proxy/${nodeName}/ui/api/v1/cluster/nodes/self/details`) + .then((response) => { + if (!response.ok) { + throw new Error( + `Failed to fetch node details: ${response.statusText}` + ); + } + return response.json(); + }) + .then((data) => { + data.target = + data.config.match(/target:\s*([^\n]+)/)?.[1]?.trim() || ""; + setNodeDetails(data); + setIsLoading(false); + }) + .catch((error) => { + setError(error instanceof Error ? error.message : "An error occurred"); + setIsLoading(false); + }); + }, [nodeName]); + + return { + nodeDetails, + isLoading, + error, + }; +} diff --git a/pkg/ui/frontend/src/hooks/use-node-metrics.ts b/pkg/ui/frontend/src/hooks/use-node-metrics.ts new file mode 100644 index 0000000000000..5cd9227a17540 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-node-metrics.ts @@ -0,0 +1,70 @@ +import { useState, useEffect } from "react"; + +interface UseNodeMetricsResult { + isLoading: boolean; + error: string | null; + metrics: string; +} + +export function useNodeMetrics( + nodeName: string | undefined, + isMetricsTabActive: boolean +): UseNodeMetricsResult { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState<string | null>(null); + const [metrics, setMetrics] = useState<string>(""); + + useEffect(() => { + // Reset state when tab becomes inactive + if (!isMetricsTabActive) { + setMetrics(""); + return; + } + + // Don't fetch if nodeName is undefined + if (!nodeName) { + return; + } + + const abortController = new AbortController(); + + async function fetchMetrics() { + setIsLoading(true); + setError(null); + + try { + const response = await fetch(`/ui/api/v1/proxy/${nodeName}/metrics`, { + signal: abortController.signal, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch metrics: ${response.statusText}`); + } + + const metricsData = await response.text(); + setMetrics(metricsData); + } catch (err) { + if (err instanceof Error) { + setError(err.message); + } else { + setError("An unknown error occurred"); + } + } finally { + setIsLoading(false); + } + } + + fetchMetrics(); + + // Cleanup function to abort fetch if component unmounts or dependencies change + return () => { + abortController.abort(); + }; + }, [nodeName, isMetricsTabActive]); // Only re-run if nodeName or tab active state changes + + return { + isLoading, + error, + metrics, + }; +} diff --git a/pkg/ui/frontend/src/hooks/use-partition-ring.ts b/pkg/ui/frontend/src/hooks/use-partition-ring.ts new file mode 100644 index 0000000000000..0853bb1a0ddf7 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-partition-ring.ts @@ -0,0 +1,249 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + PartitionInstance, + PartitionRingResponse, + RingTypes, +} from "@/types/ring"; +import { useCluster } from "@/contexts/use-cluster"; +import { useRateNodeMetrics } from "./use-rate-node-metrics"; +import { getRingProxyPath, parseZoneFromOwner } from "@/lib/ring-utils"; + +interface PartitionState { + partitions: PartitionInstance[]; + error: string; + isLoading: boolean; +} + +export interface UsePartitionRingResult { + partitions: PartitionInstance[]; + error: string; + isLoading: boolean; + fetchPartitions: () => Promise<void>; + changePartitionState: ( + partitionIds: number[], + newState: string + ) => Promise<{ success: number; total: number }>; + partitionsByState: Record<string, number>; + uniqueStates: string[]; + uniqueZones: string[]; +} + +// Map of partition states to their numeric values +const PARTITION_STATE_VALUES: Record<string, string> = { + "0": "PartitionUnknown", + "1": "PartitionPending", + "2": "PartitionActive", + "3": "PartitionInactive", + "4": "PartitionDeleted", +}; + +export interface UsePartitionRingOptions { + isPaused?: boolean; +} + +export function usePartitionRing({ + isPaused = false, +}: UsePartitionRingOptions = {}): UsePartitionRingResult { + const { cluster, isLoading: isClusterLoading } = useCluster(); + const [state, setState] = useState<PartitionState>({ + partitions: [], + error: "", + isLoading: false, + }); + const abortControllerRef = useRef<AbortController>(); + + const ringProxyPath = useCallback(() => { + return getRingProxyPath(cluster?.members, RingTypes.PARTITION_INGESTER); + }, [cluster]); + + const { fetchMetrics } = useRateNodeMetrics(); + const fetchPartitions = useCallback(async () => { + if (!ringProxyPath()) { + setState((prev) => ({ + ...prev, + partitions: [], + error: "No cluster members available", + isLoading: false, + })); + return; + } + + // Cancel any in-flight requests + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + + // Create new abort controller for this request + abortControllerRef.current = new AbortController(); + + try { + setState((prev) => ({ ...prev, isLoading: true, error: "" })); + const response = await fetch(ringProxyPath(), { + signal: abortControllerRef.current.signal, + headers: { + Accept: "application/json", + }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch partitions: ${response.statusText}`); + } + + const data: PartitionRingResponse = await response.json(); + // Denormalize partitions and add zone information + const denormalizedPartitions = data.partitions.flatMap( + (partition: PartitionInstance) => + partition.owner_ids.map((owner) => ({ + ...partition, + owner_id: owner, + owner_ids: [owner], + zone: parseZoneFromOwner(owner), + })) + ); + + const uniqueNodes = Array.from( + new Set( + denormalizedPartitions + .map((p) => p.owner_ids) + .flat() + .filter((id) => id !== undefined) + ) + ); + // Fetch metrics for all nodes + const metricsData = await fetchMetrics({ + nodeNames: uniqueNodes, + metrics: [ + "loki_ingest_storage_reader_fetch_bytes_total", + "loki_ingest_storage_reader_fetch_compressed_bytes_total", + ], + }); + // Update partitions with metrics + setState((prev) => ({ + ...prev, + isLoading: false, + partitions: denormalizedPartitions.map((partition) => { + if (!partition.owner_id) return partition; + const nodeRates = metricsData[partition.owner_id] || []; + return { + ...partition, + uncompressedRate: + nodeRates.find( + (r) => r.name === "loki_ingest_storage_reader_fetch_bytes_total" + )?.rate || 0, + compressedRate: + nodeRates.find( + (r) => + r.name === + "loki_ingest_storage_reader_fetch_compressed_bytes_total" + )?.rate || 0, + }; + }), + })); + } catch (err) { + // Only set error if it's not an abort error + if (err instanceof Error && err.name !== "AbortError") { + setState((prev) => ({ + ...prev, + error: err instanceof Error ? err.message : "Unknown error occurred", + isLoading: false, + })); + } + } + }, [ringProxyPath, fetchMetrics]); + + const changePartitionState = useCallback( + async (selectedPartitionDetails: number[], newState: string) => { + if (!ringProxyPath()) { + throw new Error("No cluster members available"); + } + const uniquePartitions = Array.from(new Set(selectedPartitionDetails)); + const total = uniquePartitions.length; + let success = 0; + + await Promise.allSettled( + uniquePartitions.map(async (partitionId) => { + const formData = new FormData(); + formData.append("action", "change_state"); + formData.append("partition_id", partitionId.toString()); + const stateValue = PARTITION_STATE_VALUES[newState]; + if (stateValue === undefined) { + throw new Error(`Invalid partition state: ${newState}`); + } + formData.append("partition_state", stateValue.toString()); + + const response = await fetch(ringProxyPath(), { + method: "POST", + body: formData, + }); + + if (!response.ok) { + const error = await response.text(); + throw new Error( + `Failed to change state for partition ${partitionId}: ${error}` + ); + } + + success++; + return partitionId; + }) + ); + + return { success, total }; + }, + [ringProxyPath] + ); + + // Calculate partition statistics with memoization for each part + const partitionStats = useMemo(() => { + const states = new Set<string>(); + const zones = new Set<string>(); + const byState: Record<string, number> = {}; + + state.partitions.forEach((partition) => { + const partitionState = partition.state.toString(); + byState[partitionState] = (byState[partitionState] || 0) + 1; + states.add(partitionState); + + partition.owner_ids.forEach((owner) => { + const zone = owner.split("-")[2]; // Extract zone from owner ID + if (zone) { + zones.add(zone); + } + }); + }); + + return { + partitionsByState: byState, + uniqueStates: Array.from(states).sort(), + uniqueZones: Array.from(zones).sort(), + }; + }, [state.partitions]); + + // Cleanup effect + useEffect(() => { + return () => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + }; + }, []); + + // Initial fetch and refresh loop + useEffect(() => { + fetchPartitions(); + + if (!isPaused) { + const intervalId = setInterval(fetchPartitions, 5000); + return () => clearInterval(intervalId); + } + }, [fetchPartitions, isPaused]); + + return { + partitions: state.partitions, + error: state.error, + isLoading: state.isLoading || isClusterLoading, + fetchPartitions, + changePartitionState, + ...partitionStats, + }; +} diff --git a/pkg/ui/frontend/src/hooks/use-rate-node-metrics.ts b/pkg/ui/frontend/src/hooks/use-rate-node-metrics.ts new file mode 100644 index 0000000000000..867e618dc8de3 --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-rate-node-metrics.ts @@ -0,0 +1,122 @@ +import { useCallback, useRef } from "react"; + +interface MetricSample { + timestamp: number; + values: Record<string, number>; +} + +interface RateMetric { + name: string; + rate: number; + currentValue: number; +} + +interface UseRateNodeMetricsOptions { + nodeNames: string[]; + metrics: string[]; +} + +interface NodeMetrics { + [nodeId: string]: RateMetric[]; +} +export const useRateNodeMetrics = () => { + const previousSamplesRef = useRef<Record<string, MetricSample>>({}); + + const fetchMetrics = useCallback( + async ({ + nodeNames, + metrics, + }: UseRateNodeMetricsOptions): Promise<NodeMetrics> => { + if (!nodeNames.length) { + return {}; + } + + const currentSamples: Record<string, MetricSample> = { + ...previousSamplesRef.current, + }; + const newRates: NodeMetrics = {}; + + // Fetch metrics for all nodes in parallel + await Promise.all( + nodeNames.map(async (nodeName) => { + try { + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/metrics` + ); + + if (!response.ok) { + throw new Error( + `Failed to fetch metrics: ${response.statusText}` + ); + } + + const text = await response.text(); + const currentSample: MetricSample = { + timestamp: Date.now(), + values: {}, + }; + + // Parse the metrics text and extract values + metrics.forEach((metricName) => { + const regex = new RegExp( + `${metricName}\\{[^}]*\\}\\s+([\\d.e+]+)` + ); + const match = text.match(regex); + if (match) { + currentSample.values[metricName] = parseFloat(match[1]); + } + }); + + const previousSample = previousSamplesRef.current[nodeName]; + currentSamples[nodeName] = currentSample; + + // Calculate rates if we have a previous sample + if (previousSample) { + const timeDiffSeconds = + (currentSample.timestamp - previousSample.timestamp) / 1000; + + // Only calculate rates if we have a meaningful time difference + if (timeDiffSeconds > 0) { + const nodeRates = metrics.map((metricName) => { + const currentValue = currentSample.values[metricName]; + const previousValue = previousSample.values[metricName]; + + if ( + currentValue !== undefined && + previousValue !== undefined + ) { + const rate = + (currentValue - previousValue) / timeDiffSeconds; + return { + name: metricName, + rate, + currentValue, + }; + } + + return { + name: metricName, + rate: 0, + currentValue: currentValue ?? 0, + }; + }); + + newRates[nodeName] = nodeRates; + } + } + } catch (err) { + console.error(`Error fetching metrics for node ${nodeName}:`, err); + } + }) + ); + + previousSamplesRef.current = currentSamples; + return newRates; + }, + [] + ); + + return { + fetchMetrics, + }; +}; diff --git a/pkg/ui/frontend/src/hooks/use-ring.ts b/pkg/ui/frontend/src/hooks/use-ring.ts new file mode 100644 index 0000000000000..5698f1bf6df5a --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-ring.ts @@ -0,0 +1,252 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { RingResponse, RingType, RingTypes } from "@/types/ring"; +import { useCluster } from "@/contexts/use-cluster"; +import { getRingProxyPath, needsTokens } from "@/lib/ring-utils"; + +export const AVAILABLE_RINGS: Array<{ id: RingType; title: string }> = [ + { id: RingTypes.INGESTER, title: "Ingester" }, + { id: RingTypes.PARTITION_INGESTER, title: "Partition Ingester" }, + { id: RingTypes.DISTRIBUTOR, title: "Distributor" }, + { id: RingTypes.PATTERN_INGESTER, title: "Pattern Ingester" }, + { id: RingTypes.QUERY_SCHEDULER, title: "Scheduler" }, + { id: RingTypes.COMPACTOR, title: "Compactor" }, + { id: RingTypes.RULER, title: "Ruler" }, + { id: RingTypes.INDEX_GATEWAY, title: "Index Gateway" }, +]; + +// Function to parse ownership from HTML response +function parseOwnershipFromHTML(html: string): Record<string, string> { + const ownerships: Record<string, string> = {}; + try { + // Extract instance rows from the table + const tableRegex = /<tbody[^>]*>([\s\S]*?)<\/tbody>/; + const tableMatch = html.match(tableRegex); + if (!tableMatch) return ownerships; + + const rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/g; + const rows = Array.from(tableMatch[1].matchAll(rowRegex)); + + for (const row of rows) { + const cellRegex = /<td[^>]*>([\s\S]*?)<\/td>/g; + const cells = Array.from(row[1].matchAll(cellRegex)).map((m) => + m[1].trim().replace(/&nbsp;/g, "") + ); + + if (cells.length >= 10) { + const id = cells[0]; + const ownership = cells[9].endsWith("%") ? cells[9] : `${cells[9]}%`; + ownerships[id] = ownership; + } + } + } catch (err) { + console.error("Error parsing ring HTML:", err); + } + return ownerships; +} + +export interface UseRingOptions { + ringName?: RingType; + isPaused?: boolean; +} + +export interface UseRingResult { + ring: RingResponse | null; + error: string; + isLoading: boolean; + fetchRing: () => Promise<void>; + forgetInstances: ( + instanceIds: string[] + ) => Promise<{ success: number; total: number }>; + uniqueStates: string[]; + uniqueZones: string[]; + isTokenBased: boolean; +} + +export function useRing({ + ringName, + isPaused = false, +}: UseRingOptions): UseRingResult { + const { cluster } = useCluster(); + const [ring, setRing] = useState<RingResponse | null>(null); + const [error, setError] = useState<string>(""); + const [isLoading, setIsLoading] = useState(false); + const abortControllerRef = useRef<AbortController>(); + + const isTokenBased = useMemo(() => needsTokens(ringName), [ringName]); + + const ringProxyPath = useCallback(() => { + return getRingProxyPath(cluster?.members, ringName ?? ""); + }, [cluster, ringName]); + + const fetchRing = useCallback(async () => { + if (!ringName) { + setError("Ring name is required"); + return; + } + const path = ringProxyPath(); + if (!path) { + setError("No cluster members available"); + return; + } + + // Cancel any in-flight requests + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + abortControllerRef.current = new AbortController(); + + setIsLoading(true); + try { + // Fetch JSON data first + const jsonResponse = await fetch(path, { + headers: { + Accept: "application/json", + }, + signal: abortControllerRef.current.signal, + }); + + if (!jsonResponse.ok) { + throw new Error(`Failed to fetch ring: ${jsonResponse.statusText}`); + } + + const jsonData: RingResponse = await jsonResponse.json(); + if (!jsonData || !jsonData.shards) { + setRing(null); + return; + } + + // Then fetch text/plain data to get ownership information + const textResponse = await fetch(path, { + headers: { + Accept: "text/plain", + }, + signal: abortControllerRef.current.signal, + }); + + if (!textResponse.ok) { + throw new Error( + `Failed to fetch ring ownership: ${textResponse.statusText}` + ); + } + + const text = await textResponse.text(); + const ownerships = parseOwnershipFromHTML(text); + + // Merge ownership information into the JSON data + const mergedData: RingResponse = { + ...jsonData, + shards: jsonData.shards.map((shard) => ({ + ...shard, + ownership: ownerships[shard.id] || "0%", + })), + }; + + setRing(mergedData); + setError(""); + } catch (err) { + if (err instanceof Error && err.name === "AbortError") { + return; + } + console.error("Error fetching ring:", err); + setError(err instanceof Error ? err.message : "Unknown error"); + setRing(null); + } finally { + setIsLoading(false); + } + }, [ringName, ringProxyPath]); + + const forgetInstances = useCallback( + async (instanceIds: string[]) => { + const path = ringProxyPath(); + if (!path) { + throw new Error("Ring name and node name are required"); + } + + let success = 0; + const total = instanceIds.length; + + for (const instanceId of instanceIds) { + try { + const formData = new FormData(); + formData.append("forget", instanceId); + const response = await fetch(path, { + method: "POST", + body: formData, + }); + if (response.ok) { + success++; + } + } catch (err) { + console.error(`Error forgetting instance ${instanceId}:`, err); + } + } + + return { success, total }; + }, + [ringProxyPath] + ); + + // Calculate instance statistics + const { uniqueStates, uniqueZones } = useMemo(() => { + if (!ring?.shards) { + return { uniqueStates: [], uniqueZones: [] }; + } + + const states = new Set<string>(); + const zones = new Set<string>(); + const byState: Record<string, number> = {}; + + ring.shards.forEach((instance) => { + const state = instance.state || "unknown"; + byState[state] = (byState[state] || 0) + 1; + if (state && state.trim()) { + states.add(state); + } + if (instance.zone && instance.zone.trim()) { + zones.add(instance.zone); + } + }); + + return { + uniqueStates: Array.from(states).sort(), + uniqueZones: Array.from(zones).sort(), + }; + }, [ring?.shards]); + + // Cleanup effect + useEffect(() => { + return () => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + }; + }, []); + + // Initial fetch and refresh loop + useEffect(() => { + fetchRing(); + + // Set up refresh interval only if not paused + if (!isPaused) { + const intervalId = setInterval(() => { + fetchRing(); + }, 5000); + + // Cleanup interval on unmount + return () => { + clearInterval(intervalId); + }; + } + }, [fetchRing, isPaused]); + + return { + ring, + error, + isLoading, + fetchRing, + forgetInstances, + uniqueStates, + uniqueZones, + isTokenBased, + }; +} diff --git a/pkg/ui/frontend/src/hooks/use-toast.ts b/pkg/ui/frontend/src/hooks/use-toast.ts new file mode 100644 index 0000000000000..266d3800a544f --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-toast.ts @@ -0,0 +1,191 @@ +"use client"; + +// Inspired by react-hot-toast library +import * as React from "react"; + +import type { ToastActionElement, ToastProps } from "@/components/ui/toast"; + +const TOAST_LIMIT = 5; +const TOAST_REMOVE_DELAY = 1000000; + +type ToasterToast = ToastProps & { + id: string; + title?: React.ReactNode; + description?: React.ReactNode; + action?: ToastActionElement; +}; + +const actionTypes = { + ADD_TOAST: "ADD_TOAST", + UPDATE_TOAST: "UPDATE_TOAST", + DISMISS_TOAST: "DISMISS_TOAST", + REMOVE_TOAST: "REMOVE_TOAST", +} as const; + +let count = 0; + +function genId() { + count = (count + 1) % Number.MAX_SAFE_INTEGER; + return count.toString(); +} + +type ActionType = typeof actionTypes; + +type Action = + | { + type: ActionType["ADD_TOAST"]; + toast: ToasterToast; + } + | { + type: ActionType["UPDATE_TOAST"]; + toast: Partial<ToasterToast>; + } + | { + type: ActionType["DISMISS_TOAST"]; + toastId?: ToasterToast["id"]; + } + | { + type: ActionType["REMOVE_TOAST"]; + toastId?: ToasterToast["id"]; + }; + +interface State { + toasts: ToasterToast[]; +} + +const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>(); + +const addToRemoveQueue = (toastId: string) => { + if (toastTimeouts.has(toastId)) { + return; + } + + const timeout = setTimeout(() => { + toastTimeouts.delete(toastId); + dispatch({ + type: "REMOVE_TOAST", + toastId: toastId, + }); + }, TOAST_REMOVE_DELAY); + + toastTimeouts.set(toastId, timeout); +}; + +export const reducer = (state: State, action: Action): State => { + switch (action.type) { + case "ADD_TOAST": + return { + ...state, + toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), + }; + + case "UPDATE_TOAST": + return { + ...state, + toasts: state.toasts.map((t) => + t.id === action.toast.id ? { ...t, ...action.toast } : t + ), + }; + + case "DISMISS_TOAST": { + const { toastId } = action; + + // ! Side effects ! - This could be extracted into a dismissToast() action, + // but I'll keep it here for simplicity + if (toastId) { + addToRemoveQueue(toastId); + } else { + state.toasts.forEach((toast) => { + addToRemoveQueue(toast.id); + }); + } + + return { + ...state, + toasts: state.toasts.map((t) => + t.id === toastId || toastId === undefined + ? { + ...t, + open: false, + } + : t + ), + }; + } + case "REMOVE_TOAST": + if (action.toastId === undefined) { + return { + ...state, + toasts: [], + }; + } + return { + ...state, + toasts: state.toasts.filter((t) => t.id !== action.toastId), + }; + } +}; + +const listeners: Array<(state: State) => void> = []; + +let memoryState: State = { toasts: [] }; + +function dispatch(action: Action) { + memoryState = reducer(memoryState, action); + listeners.forEach((listener) => { + listener(memoryState); + }); +} + +type Toast = Omit<ToasterToast, "id">; + +function toast({ ...props }: Toast) { + const id = genId(); + + const update = (props: ToasterToast) => + dispatch({ + type: "UPDATE_TOAST", + toast: { ...props, id }, + }); + const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }); + + dispatch({ + type: "ADD_TOAST", + toast: { + ...props, + id, + open: true, + onOpenChange: (open) => { + if (!open) dismiss(); + }, + }, + }); + + return { + id: id, + dismiss, + update, + }; +} + +function useToast() { + const [state, setState] = React.useState<State>(memoryState); + + React.useEffect(() => { + listeners.push(setState); + return () => { + const index = listeners.indexOf(setState); + if (index > -1) { + listeners.splice(index, 1); + } + }; + }, [state]); + + return { + ...state, + toast, + dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), + }; +} + +export { useToast, toast }; diff --git a/pkg/ui/frontend/src/hooks/use-version-info.ts b/pkg/ui/frontend/src/hooks/use-version-info.ts new file mode 100644 index 0000000000000..2b779eaca323a --- /dev/null +++ b/pkg/ui/frontend/src/hooks/use-version-info.ts @@ -0,0 +1,102 @@ +import { useCluster } from "@/contexts/use-cluster"; +import { useEffect, useState } from "react"; + +interface VersionInfo { + revision: string; + branch: string; + buildUser: string; + buildDate: string; + goVersion: string; +} + +interface UseVersionInfoResult { + mostCommonVersion: string; + versionInfos: Array<{ + version: string; + info: VersionInfo; + }>; + isLoading: boolean; +} + +export function useVersionInfo(): UseVersionInfoResult { + const { cluster, isLoading: clusterLoading } = useCluster(); + const [debouncedLoading, setDebouncedLoading] = useState(true); + + useEffect(() => { + let timeoutId: NodeJS.Timeout; + + if (clusterLoading) { + setDebouncedLoading(true); + } else { + // When loading finishes, keep the loading state for a minimum duration + timeoutId = setTimeout(() => { + setDebouncedLoading(false); + }, 500); // Keep loading state visible for 500ms after data loads + } + + return () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + }; + }, [clusterLoading]); + + const getMostCommonVersion = (): string => { + if (!cluster?.members) return "v0.0.0"; + + const versionCounts = new Map<string, number>(); + Object.values(cluster.members).forEach((member) => { + if (!member.build.version) return; + const version = member.build.version; + versionCounts.set(version, (versionCounts.get(version) || 0) + 1); + }); + + let mostCommonVersion = "v0.0.0"; + let maxCount = 0; + + versionCounts.forEach((count, version) => { + if (count > maxCount) { + maxCount = count; + mostCommonVersion = version; + } + }); + + return mostCommonVersion; + }; + + const getVersionInfos = (): Array<{ version: string; info: VersionInfo }> => { + if (!cluster?.members) return []; + + const versions = new Set<string>(); + const buildInfo = new Map<string, VersionInfo>(); + + Object.values(cluster.members).forEach((member) => { + const version = member.build.version; + versions.add(version); + buildInfo.set(version, { + revision: member.build.revision, + branch: member.build.branch, + buildUser: member.build.buildUser, + buildDate: member.build.buildDate, + goVersion: member.build.goVersion, + }); + }); + + return Array.from(versions).map((version) => ({ + version: version ?? "v0.0.0", + info: buildInfo.get(version) ?? { + revision: "v0.0.0", + branch: "v0.0.0", + buildUser: "v0.0.0", + buildDate: "v0.0.0", + goVersion: "v0.0.0", + }, + })); + }; + + return { + mostCommonVersion: getMostCommonVersion(), + versionInfos: getVersionInfos(), + isLoading: debouncedLoading, + }; +} diff --git a/pkg/ui/frontend/src/index.css b/pkg/ui/frontend/src/index.css new file mode 100644 index 0000000000000..ee0debb31226b --- /dev/null +++ b/pkg/ui/frontend/src/index.css @@ -0,0 +1,95 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 0 0% 3.9%; + --muted: 0 0% 96.1%; + --muted-foreground: 0 0% 45.1%; + --popover: 0 0% 100%; + --popover-foreground: 0 0% 3.9%; + --border: 0 0% 89.8%; + --input: 0 0% 89.8%; + --card: 0 0% 100%; + --card-foreground: 0 0% 3.9%; + --primary: 0 0% 9%; + --primary-foreground: 0 0% 98%; + --secondary: 0 0% 96.1%; + --secondary-foreground: 0 0% 9%; + --accent: 0 0% 96.1%; + --accent-foreground: 0 0% 9%; + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 0 0% 98%; + --ring: 0 0% 3.9%; + --radius: 0.5rem; + --chart-1: 12 76% 61%; + --chart-2: 173 58% 39%; + --chart-3: 197 37% 24%; + --chart-4: 43 74% 66%; + --chart-5: 27 87% 67%; + --sidebar-background: 0 0% 98%; + --sidebar-foreground: 240 5.3% 26.1%; + --sidebar-primary: 240 5.9% 10%; + --sidebar-primary-foreground: 0 0% 98%; + --sidebar-accent: 240 4.8% 95.9%; + --sidebar-accent-foreground: 240 5.9% 10%; + --sidebar-border: 220 13% 91%; + --sidebar-ring: 217.2 91.2% 59.8%; + } + + .dark { + --background: 0 0% 7%; + --foreground: 0 0% 90%; + --card: 0 0% 9%; + --card-foreground: 0 0% 90%; + --popover: 0 0% 7%; + --popover-foreground: 0 0% 90%; + --primary: 199 87% 64%; + --primary-foreground: 0 0% 7%; + --secondary: 0 0% 11%; + --secondary-foreground: 0 0% 90%; + --muted: 0 0% 11%; + --muted-foreground: 0 0% 63%; + --accent: 0 0% 11%; + --accent-foreground: 0 0% 90%; + --destructive: 0 84% 60%; + --destructive-foreground: 0 0% 90%; + --border: 0 0% 13%; + --input: 0 0% 13%; + --ring: 0 0% 13%; + --radius: 0.25rem; + --chart-1: 199 87% 64%; + --chart-2: 120 56% 49%; + --chart-3: 40 100% 50%; + --chart-4: 283 39% 53%; + --chart-5: 13 75% 58%; + --sidebar-background: 0 0% 7%; + --sidebar-foreground: 0 0% 90%; + --sidebar-primary: 199 87% 64%; + --sidebar-primary-foreground: 0 0% 100%; + --sidebar-accent: 0 0% 11%; + --sidebar-accent-foreground: 0 0% 90%; + --sidebar-border: 0 0% 13%; + --sidebar-ring: 199 87% 64%; + } +} + +@layer base { + * { + @apply border-border; + } + body { + @apply font-sans antialiased bg-background text-foreground; + } +} + +@layer base { + * { + @apply border-border; + } + body { + @apply bg-background text-foreground; + } +} diff --git a/pkg/ui/frontend/src/layout/github-link.tsx b/pkg/ui/frontend/src/layout/github-link.tsx new file mode 100644 index 0000000000000..8bc4424cae68c --- /dev/null +++ b/pkg/ui/frontend/src/layout/github-link.tsx @@ -0,0 +1,26 @@ +import { Button } from "../components/ui/button"; + +export function GitHubLink() { + return ( + <Button + variant="ghost" + size="icon" + className="bg-muted hover:bg-muted-hover rounded-lg" + asChild + > + <a + href="https://github.com/grafana/loki" + target="_blank" + rel="noopener noreferrer" + > + <svg viewBox="0 0 438.549 438.549" className="h-[1.2rem] w-[1.2rem]"> + <path + fill="currentColor" + d="M409.132 114.573c-19.608-33.596-46.205-60.194-79.798-79.8-33.598-19.607-70.277-29.408-110.063-29.408-39.781 0-76.472 9.804-110.063 29.408-33.596 19.605-60.192 46.204-79.8 79.8C9.803 148.168 0 184.854 0 224.63c0 47.78 13.94 90.745 41.827 128.906 27.884 38.164 63.906 64.572 108.063 79.227 5.14.954 8.945.283 11.419-1.996 2.475-2.282 3.711-5.14 3.711-8.562 0-.571-.049-5.708-.144-15.417a2549.81 2549.81 0 01-.144-25.406l-6.567 1.136c-4.187.767-9.469 1.092-15.846 1-6.374-.089-12.991-.757-19.842-1.999-6.854-1.231-13.229-4.086-19.13-8.559-5.898-4.473-10.085-10.328-12.56-17.556l-2.855-6.57c-1.903-4.374-4.899-9.233-8.992-14.559-4.093-5.331-8.232-8.945-12.419-10.848l-1.999-1.431c-1.332-.951-2.568-2.098-3.711-3.429-1.142-1.331-1.997-2.663-2.568-3.997-.572-1.335-.098-2.43 1.427-3.289 1.525-.859 4.281-1.276 8.28-1.276l5.708.853c3.807.763 8.516 3.042 14.133 6.851 5.614 3.806 10.229 8.754 13.846 14.842 4.38 7.806 9.657 13.754 15.846 17.847 6.184 4.093 12.419 6.136 18.699 6.136 6.28 0 11.704-.476 16.274-1.423 4.565-.952 8.848-2.383 12.847-4.285 1.713-12.758 6.377-22.559 13.988-29.41-10.848-1.14-20.601-2.857-29.264-5.14-8.658-2.286-17.605-5.996-26.835-11.14-9.235-5.137-16.896-11.516-22.985-19.126-6.09-7.614-11.088-17.61-14.987-29.979-3.901-12.374-5.852-26.648-5.852-42.826 0-23.035 7.52-42.637 22.557-58.817-7.044-17.318-6.379-36.732 1.997-58.24 5.52-1.715 13.706-.428 24.554 3.853 10.85 4.283 18.794 7.952 23.84 10.994 5.046 3.041 9.089 5.618 12.135 7.708 17.705-4.947 35.976-7.421 54.818-7.421s37.117 2.474 54.823 7.421l10.849-6.849c7.419-4.57 16.18-8.758 26.262-12.565 10.088-3.805 17.802-4.853 23.134-3.138 8.562 21.509 9.325 40.922 2.279 58.24 15.036 16.18 22.559 35.787 22.559 58.817 0 16.178-1.958 30.497-5.853 42.966-3.9 12.471-8.941 22.457-15.125 29.979-6.191 7.521-13.901 13.85-23.131 18.986-9.232 5.14-18.182 8.85-26.84 11.136-8.662 2.286-18.415 4.004-29.263 5.146 9.894 8.562 14.842 22.077 14.842 40.539v60.237c0 3.422 1.19 6.279 3.572 8.562 2.379 2.279 6.136 2.95 11.276 1.995 44.163-14.653 80.185-41.062 108.068-79.226 27.88-38.161 41.825-81.126 41.825-128.906-.01-39.771-9.818-76.454-29.414-110.049z" + /> + </svg> + <span className="sr-only">View on GitHub</span> + </a> + </Button> + ); +} diff --git a/pkg/ui/frontend/src/layout/header-actions.tsx b/pkg/ui/frontend/src/layout/header-actions.tsx new file mode 100644 index 0000000000000..583a634c4ce68 --- /dev/null +++ b/pkg/ui/frontend/src/layout/header-actions.tsx @@ -0,0 +1,11 @@ +import { GitHubLink } from "./github-link"; +import { ThemeToggle } from "../features/theme"; + +export function HeaderActions() { + return ( + <div className="flex items-center gap-2"> + <GitHubLink /> + <ThemeToggle /> + </div> + ); +} diff --git a/pkg/ui/frontend/src/layout/index.ts b/pkg/ui/frontend/src/layout/index.ts new file mode 100644 index 0000000000000..b90eb12e5c850 --- /dev/null +++ b/pkg/ui/frontend/src/layout/index.ts @@ -0,0 +1,4 @@ +export * from "./header-actions"; +export * from "./layout"; +export * from "./sidebar"; +export * from "./github-link"; diff --git a/pkg/ui/frontend/src/layout/layout.tsx b/pkg/ui/frontend/src/layout/layout.tsx new file mode 100644 index 0000000000000..78c45186465d4 --- /dev/null +++ b/pkg/ui/frontend/src/layout/layout.tsx @@ -0,0 +1,39 @@ +import React from "react"; +import { HeaderActions } from "./header-actions"; +import { BreadcrumbNav } from "@/components/shared/breadcrumb-nav"; +import { AppSidebar } from "./sidebar"; +import { + SidebarInset, + SidebarProvider, + SidebarTrigger, +} from "../components/ui/sidebar"; +import { Separator } from "../components/ui/separator"; +import { ScrollToTop } from "../components/ui/scroll-to-top"; +import { Toaster } from "@/components/ui/toaster"; + +interface AppLayoutProps { + children: React.ReactNode; +} + +export function AppLayout({ children }: AppLayoutProps) { + return ( + <div className="flex min-h-screen"> + <SidebarProvider> + <AppSidebar /> + <SidebarInset> + <header className="flex h-16 shrink-0 items-center gap-2 border-b px-4"> + <SidebarTrigger /> + <Separator orientation="vertical" className="mr-2 h-4" /> + <BreadcrumbNav /> + <div className="ml-auto px-4"> + <HeaderActions /> + </div> + </header> + <main className="flex flex-1 flex-col">{children}</main> + <Toaster /> + <ScrollToTop /> + </SidebarInset> + </SidebarProvider> + </div> + ); +} diff --git a/pkg/ui/frontend/src/layout/page-container.tsx b/pkg/ui/frontend/src/layout/page-container.tsx new file mode 100644 index 0000000000000..7297e67e186d6 --- /dev/null +++ b/pkg/ui/frontend/src/layout/page-container.tsx @@ -0,0 +1,25 @@ +import { cn } from "@/lib/utils"; + +interface PageContainerProps extends React.HTMLAttributes<HTMLDivElement> { + children: React.ReactNode; + /** + * Whether to add vertical spacing between children + * @default true + */ + spacing?: boolean; +} + +export function PageContainer({ + children, + className, + spacing = true, + ...props +}: PageContainerProps) { + return ( + <div className="container p-6"> + <div className={cn(spacing && "space-y-6", className)} {...props}> + {children} + </div> + </div> + ); +} diff --git a/pkg/ui/frontend/src/layout/sidebar.tsx b/pkg/ui/frontend/src/layout/sidebar.tsx new file mode 100644 index 0000000000000..b9218e6266b08 --- /dev/null +++ b/pkg/ui/frontend/src/layout/sidebar.tsx @@ -0,0 +1,320 @@ +import * as React from "react"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { getBasename } from "../util"; +import { VersionDisplay } from "@/components/version-display"; +import { useLocation, Link } from "react-router-dom"; +import { + ChevronDown, + CircleDot, + Database, + GaugeCircle, + LayoutDashboard, + Users, + BookOpen, +} from "lucide-react"; +import { useCluster } from "@/contexts/use-cluster"; +import { getAvailableRings } from "@/lib/ring-utils"; + +import { + Sidebar, + SidebarContent, + SidebarGroup, + SidebarHeader, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + SidebarMenuSub, + SidebarMenuSubButton, + SidebarMenuSubItem, + SidebarRail, +} from "@/components/ui/sidebar"; +import { cn } from "@/lib/utils"; + +interface NavItem { + title: string; + url: string; + icon?: React.ReactNode; + items?: Array<{ title: string; url: string }>; +} + +interface Member { + services?: Array<{ service: string }>; +} + +interface ClusterData { + members?: Record<string, Member>; +} + +function useNavItems( + cluster: ClusterData | null, + baseItems: NavItem[] +): NavItem[] { + const [navItems, setNavItems] = React.useState<NavItem[]>(baseItems); + + React.useEffect(() => { + if (!cluster?.members) return; + + // Update nav items based on available services + const newItems = baseItems.map((item) => { + if (item.title === "Rings" && cluster.members) { + return { + ...item, + items: getAvailableRings(cluster.members), + }; + } + return item; + }); + + setNavItems(newItems); + }, [cluster?.members, baseItems]); + + return navItems; +} + +const baseNavItems: NavItem[] = [ + { + title: "Cluster", + url: "/nodes", + icon: <LayoutDashboard className="h-4 w-4" />, + items: [ + { + title: "Nodes", + url: "/nodes", + }, + { + title: "Rollouts & Versions", + url: "/versions", + }, + ], + }, + { + title: "Rings", + url: "/rings", + icon: <CircleDot className="h-4 w-4" />, + items: [], + }, + { + title: "Storage", + url: "/storage", + icon: <Database className="h-4 w-4" />, + items: [ + { + title: "Object Storage", + url: "/storage/object", + }, + { + title: "Data Objects", + url: "/storage/dataobj", + }, + ], + }, + { + title: "Tenants", + url: "/tenants", + icon: <Users className="h-4 w-4" />, + items: [ + { + title: "Analyze Labels", + url: "/tenants/analyze-labels", + }, + { + title: "Deletes", + url: "/tenants/deletes", + }, + { + title: "Limits", + url: "/tenants/limits", + }, + { + title: "Labels", + url: "/tenants/labels", + }, + ], + }, + { + title: "Rules", + url: "/rules", + icon: <GaugeCircle className="h-4 w-4" />, + items: [], + }, + { + title: "Documentation", + url: "https://grafana.com/docs/loki/latest/", + icon: <BookOpen className="h-4 w-4" />, + items: [], + }, +]; + +// Custom wrapper for SidebarRail to handle theme-specific styling +function CustomSidebarRail(props: React.ComponentProps<typeof SidebarRail>) { + return ( + <SidebarRail + {...props} + className={cn( + "after:bg-border/40 hover:after:bg-border", + "hover:bg-muted/50", + props.className + )} + /> + ); +} + +const OPEN_SECTIONS_KEY = "loki-sidebar-open-sections"; + +interface NavItemProps { + item: NavItem; + isOpen: boolean; + isActive: (url: string) => boolean; + onToggle: (title: string) => void; +} + +const NavItemComponent = React.memo(function NavItemComponent({ + item, + isOpen, + isActive, + onToggle, +}: NavItemProps) { + return ( + <SidebarMenuItem> + <SidebarMenuButton + asChild + isActive={isActive(item.url)} + onClick={() => onToggle(item.title)} + > + <div className="flex items-center justify-between font-medium"> + <div className="flex items-center gap-2"> + {item.icon} + <Link + to={`${item.url}`} + target={item.url.includes("http") ? "_blank" : "_self"} + > + {item.title} + </Link> + </div> + {item.items && item.items.length > 0 && ( + <ChevronDown + className={cn( + "h-4 w-4 transition-transform duration-200", + isOpen ? "rotate-0" : "-rotate-90" + )} + /> + )} + </div> + </SidebarMenuButton> + {item.items && item.items.length > 0 && isOpen && ( + <SidebarMenuSub> + {item.items.map((subItem) => ( + <SidebarMenuSubItem key={subItem.title}> + <SidebarMenuSubButton asChild isActive={isActive(subItem.url)}> + <Link to={`${subItem.url}`}>{subItem.title}</Link> + </SidebarMenuSubButton> + </SidebarMenuSubItem> + ))} + </SidebarMenuSub> + )} + </SidebarMenuItem> + ); +}); + +export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) { + const basename = getBasename(); + const location = useLocation(); + const { cluster } = useCluster(); + const currentPath = location.pathname.replace(basename, "/"); + + // Initialize state from localStorage or default to all sections open + const [openSections, setOpenSections] = React.useState< + Record<string, boolean> + >(() => { + const stored = localStorage.getItem(OPEN_SECTIONS_KEY); + if (stored) { + try { + return JSON.parse(stored); + } catch { + return baseNavItems.reduce( + (acc, item) => ({ + ...acc, + [item.title]: true, + }), + {} + ); + } + } + return baseNavItems.reduce( + (acc, item) => ({ + ...acc, + [item.title]: true, + }), + {} + ); + }); + + // Use the stable nav items hook + const navItems = useNavItems(cluster, baseNavItems); + + const isActive = React.useCallback( + (url: string) => { + if (url === "/") { + return currentPath === "/"; + } + return currentPath.startsWith(url); + }, + [currentPath] + ); + + const toggleSection = React.useCallback((title: string) => { + setOpenSections((prev) => { + const next = { + ...prev, + [title]: !prev[title], + }; + localStorage.setItem(OPEN_SECTIONS_KEY, JSON.stringify(next)); + return next; + }); + }, []); + + return ( + <Sidebar {...props}> + <SidebarHeader className="py-4"> + <SidebarMenu> + <SidebarMenuItem> + <SidebarMenuButton size="lg" asChild> + <div className="flex items-center gap-3 px-6 py-4"> + <img + src="https://grafana.com/media/docs/loki/logo-grafana-loki.png" + alt="Loki Logo" + className="h-7 w-7" + /> + <div className="flex flex-col gap-0.5"> + <span className="text-sm font-semibold leading-none"> + Grafana Loki + </span> + <VersionDisplay /> + </div> + </div> + </SidebarMenuButton> + </SidebarMenuItem> + </SidebarMenu> + </SidebarHeader> + <ScrollArea className="flex-1"> + <SidebarContent> + <SidebarGroup> + <SidebarMenu> + {navItems.map((item) => ( + <React.Fragment key={item.title}> + <NavItemComponent + item={item} + isOpen={openSections[item.title]} + isActive={isActive} + onToggle={toggleSection} + /> + </React.Fragment> + ))} + </SidebarMenu> + </SidebarGroup> + </SidebarContent> + </ScrollArea> + <CustomSidebarRail /> + </Sidebar> + ); +} diff --git a/pkg/ui/frontend/src/lib/ring-utils.ts b/pkg/ui/frontend/src/lib/ring-utils.ts new file mode 100644 index 0000000000000..bd29b45f2a447 --- /dev/null +++ b/pkg/ui/frontend/src/lib/ring-utils.ts @@ -0,0 +1,211 @@ +import { RingType, RingTypes } from "@/types/ring"; +import { formatDistanceToNowStrict, formatISO } from "date-fns"; +import { findNodeName, hasService } from "./utils"; + +export function formatRelativeTime(timestamp: string) { + const date = new Date(timestamp); + return `${formatDistanceToNowStrict(date)} ago`; +} + +export function formatTimestamp(timestamp: string) { + const date = new Date(timestamp); + return formatISO(date, { format: "extended" }); +} + +export function getStateColors(state: string | number): string { + const numericState = typeof state === "string" ? parseInt(state, 10) : state; + switch (numericState) { + case 2: // Active + return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"; + case 1: // Pending + return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"; + case 3: // Inactive + return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"; + case 4: // Deleted + return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"; + default: // Unknown + return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"; + } +} + +export function getZoneColors(zone: string) { + // Create a consistent hash of the zone name to always get the same color for the same zone + const hash = zone.split("").reduce((acc, char) => { + return char.charCodeAt(0) + ((acc << 5) - acc); + }, 0); + + // Using only colors not used in state indicators + // Avoiding: green, yellow, blue, purple, red, gray + const colors = [ + "bg-rose-100 text-rose-800 dark:bg-rose-900 dark:text-rose-200", + "bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200", + "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200", + "bg-lime-100 text-lime-800 dark:bg-lime-900 dark:text-lime-200", + "bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200", + "bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200", + "bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200", + "bg-fuchsia-100 text-fuchsia-800 dark:bg-fuchsia-900 dark:text-fuchsia-200", + ]; + + const index = Math.abs(hash) % colors.length; + return colors[index]; +} + +export function parseZoneFromOwner(owner: string): string { + const parts = owner.split("-"); + return parts.length >= 3 ? parts[parts.length - 2] : ""; +} + +export function getFirstZoneFromOwners(owners: string[]): string { + if (!owners.length) return ""; + return parseZoneFromOwner(owners[0]); +} + +export function formatBytes(bytes: number): string { + const units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let value = bytes; + let unitIndex = 0; + + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024; + unitIndex++; + } + + return `${value.toFixed(1)} ${units[unitIndex]}`; +} + +interface Member { + services?: Array<{ service: string }>; +} + +// Helper function to check if a service exists in any member +export const clusterSupportService = ( + members: Record<string, Member>, + serviceName: string +): boolean => { + return Object.values(members).some((member) => + hasService(member, serviceName) + ); +}; + +export const ServiceNames = { + ingester: "ingester", + "partition-ring": "partition-ring", + distributor: "distributor", + "pattern-ingester": "pattern-ingester", + "query-scheduler": "query-scheduler", + compactor: "compactor", + ruler: "ruler", + "index-gateway": "index-gateway", +}; + +export const RingServices: Record< + string, + { title: string; ringName: RingType; ringPath: string; needsTokens: boolean } +> = { + ingester: { + title: "Ingester", + ringName: RingTypes.INGESTER, + ringPath: "/ring", + needsTokens: true, + }, + "partition-ring": { + title: "Partition Ingester", + ringName: RingTypes.PARTITION_INGESTER, + ringPath: "/partition-ring", + needsTokens: true, + }, + distributor: { + title: "Distributor", + ringName: RingTypes.DISTRIBUTOR, + ringPath: "/distributor/ring", + needsTokens: false, + }, + "pattern-ingester": { + title: "Pattern Ingester", + ringName: RingTypes.PATTERN_INGESTER, + ringPath: "/pattern/ring", + needsTokens: true, + }, + "query-scheduler": { + title: "Scheduler", + ringName: RingTypes.QUERY_SCHEDULER, + ringPath: "/scheduler/ring", + needsTokens: false, + }, + compactor: { + title: "Compactor", + ringName: RingTypes.COMPACTOR, + ringPath: "/compactor/ring", + needsTokens: false, + }, + ruler: { + title: "Ruler", + ringName: RingTypes.RULER, + ringPath: "/ruler/ring", + needsTokens: true, + }, + "index-gateway": { + title: "Index Gateway", + ringName: RingTypes.INDEX_GATEWAY, + ringPath: "/indexgateway/ring", + needsTokens: true, + }, +}; + +function findServiceName(ringType: RingType) { + return Object.keys(RingServices).find( + (key) => RingServices[key].ringName === ringType + ); +} + +// Function to determine if a ring type needs tokens +export function needsTokens(ringName: RingType | undefined): boolean { + if (!ringName) return false; + const serviceName = findServiceName(ringName); + if (!serviceName) return false; + return RingServices[serviceName].needsTokens; +} + +// Helper function to get available rings based on cluster services +export const getAvailableRings = ( + members: Record<string, Member> +): Array<{ title: string; url: string }> => { + const rings: Array<{ title: string; url: string }> = []; + + if (!members) return rings; + + // loop through services type an push to rigns + + for (const service in RingServices) { + if (clusterSupportService(members, service)) { + rings.push({ + title: RingServices[service].title, + url: `/rings/${RingServices[service].ringName}`, + }); + } + } + return rings; +}; + +// Utility function to get ring proxy path +export function getRingProxyPath( + members: Record<string, Member> | undefined, + ringName: RingType +): string { + if (!members) return ""; + if (!ringName) return ""; + + const serviceName = findServiceName(ringName); + if (!serviceName) return ""; + // Find the first member that has the serviceName + const nodeName = findNodeName(members, serviceName); + if (!nodeName) return ""; + + const proxyPath = `/ui/api/v1/proxy/${nodeName}`; + const ringPath = RingServices[serviceName].ringPath; + const tokensParam = RingServices[serviceName].needsTokens + ? "?tokens=true" + : ""; + return `${proxyPath}${ringPath}${tokensParam}`; +} diff --git a/pkg/ui/frontend/src/lib/utils.ts b/pkg/ui/frontend/src/lib/utils.ts new file mode 100644 index 0000000000000..d37f4aa5d9479 --- /dev/null +++ b/pkg/ui/frontend/src/lib/utils.ts @@ -0,0 +1,34 @@ +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +export function formatBytes(bytes: number): string { + if (bytes === 0) return "0 B"; + const k = 1024; + const sizes = ["B", "KB", "MB", "GB", "TB", "PB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`; +} + +interface Member { + services?: Array<{ service: string }>; +} + +export function findNodeName( + members: Record<string, Member> | undefined, + serviceName: string +) { + if (!members) return null; + return Object.keys(members).find((key) => + hasService(members[key], serviceName) + ); +} + +export function hasService(member: Member, serviceName: string): boolean { + return ( + member.services?.some((service) => service.service === serviceName) ?? false + ); +} diff --git a/pkg/ui/frontend/src/main.tsx b/pkg/ui/frontend/src/main.tsx new file mode 100644 index 0000000000000..3d13bf855a0aa --- /dev/null +++ b/pkg/ui/frontend/src/main.tsx @@ -0,0 +1,38 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { RouterProvider, createBrowserRouter } from "react-router-dom"; + +import App from "./App"; +import "./index.css"; +import { getBasename } from "./util"; + +const basename = getBasename(); + +const router = createBrowserRouter( + [ + { + path: "*", + element: <App />, + }, + ], + { + basename, + future: { + v7_relativeSplatPath: true, + }, + } +); + +const root = document.getElementById("root"); +if (!root) throw new Error("Root element not found"); + +createRoot(root).render( + <StrictMode> + <RouterProvider + router={router} + future={{ + v7_startTransition: true, + }} + /> + </StrictMode> +); diff --git a/pkg/ui/frontend/src/pages/analyze-labels.tsx b/pkg/ui/frontend/src/pages/analyze-labels.tsx new file mode 100644 index 0000000000000..d8ec30d4f7c72 --- /dev/null +++ b/pkg/ui/frontend/src/pages/analyze-labels.tsx @@ -0,0 +1,640 @@ +import { useState, useMemo, useEffect } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Input } from "@/components/ui/input"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import * as z from "zod"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { useCluster } from "@/contexts/use-cluster"; +import { findNodeName } from "@/lib/utils"; +import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts"; +import { + ChartConfig, + ChartContainer, + ChartTooltip, + ChartTooltipContent, +} from "@/components/ui/chart"; +import { DataTableColumnHeader } from "@/components/common/data-table-column-header"; +import { ChevronDown } from "lucide-react"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible"; +import { Badge } from "@/components/ui/badge"; +import { cn } from "@/lib/utils"; +import { useToast } from "@/hooks/use-toast"; + +const formSchema = z.object({ + tenant: z.string().min(1, "Tenant ID is required"), + since: z.string(), + matcher: z.string().default("{}"), +}); + +const durationOptions = [ + { value: "1h", label: "Last 1 hour" }, + { value: "3h", label: "Last 3 hours" }, + { value: "6h", label: "Last 6 hours" }, + { value: "12h", label: "Last 12 hours" }, + { value: "24h", label: "Last 24 hours" }, +]; + +interface LabelValue { + value: string; + count: number; +} + +interface LabelAnalysis { + name: string; + uniqueValues: number; + inStreams: number; + sampleValues: LabelValue[]; +} + +type SortField = "name" | "uniqueValues" | "inStreams" | "cardinality"; +type MetricType = "uniqueValues" | "inStreams"; + +interface LabelValuesListProps { + values: LabelValue[]; + totalValues: number; +} + +function LabelValuesList({ values, totalValues }: LabelValuesListProps) { + return ( + <div className="space-y-2 py-2"> + {values.map(({ value, count }) => ( + <div + key={value} + className="grid grid-cols-[200px_1fr_80px] items-center gap-4" + > + <Badge + variant="outline" + className="font-mono text-xs justify-self-start overflow-hidden" + > + {value} + </Badge> + <div className="h-2 bg-muted rounded-full overflow-hidden"> + <div + className="h-full bg-primary" + style={{ width: `${(count / totalValues) * 100}%` }} + /> + </div> + <span className="text-xs text-muted-foreground tabular-nums justify-self-end"> + {((count / totalValues) * 100).toFixed(1)}% + </span> + </div> + ))} + </div> + ); +} + +export default function AnalyzeLabels() { + const { cluster } = useCluster(); + const { toast } = useToast(); + const [analysisResults, setAnalysisResults] = useState<{ + totalStreams: number; + uniqueLabels: number; + labels: LabelAnalysis[]; + } | null>(null); + const [sortField, setSortField] = useState<SortField>("uniqueValues"); + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc"); + const [selectedMetric, setSelectedMetric] = + useState<MetricType>("uniqueValues"); + const [openRows, setOpenRows] = useState<Set<string>>(new Set()); + + const form = useForm<z.infer<typeof formSchema>>({ + resolver: zodResolver(formSchema), + defaultValues: { + matcher: "{}", + since: "1h", + }, + }); + + const nodeName = findNodeName(cluster?.members, "query-frontend"); + + const { isLoading, refetch } = useQuery({ + queryKey: ["analyze-labels"], + queryFn: async () => { + try { + const values = form.getValues(); + const end = new Date(); + const start = new Date(end.getTime() - parseDuration(values.since)); + + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/loki/api/v1/series?match[]=${encodeURIComponent( + values.matcher + )}&start=${start.getTime() * 1e6}&end=${end.getTime() * 1e6}`, + { + headers: { + "X-Scope-OrgID": values.tenant, + }, + } + ); + + if (!response.ok) { + const error = await response.text(); + throw new Error(error || "Failed to fetch series"); + } + + const data = await response.json(); + const labelMap = new Map< + string, + { uniqueValues: Set<string>; inStreams: number } + >(); + const valueCountMap = new Map<string, Map<string, number>>(); + + // Process the streams similar to the CLI tool + data.data.forEach((stream: Record<string, string>) => { + Object.entries(stream).forEach(([name, value]) => { + if (!labelMap.has(name)) { + labelMap.set(name, { uniqueValues: new Set(), inStreams: 0 }); + valueCountMap.set(name, new Map()); + } + const label = labelMap.get(name) as { + uniqueValues: Set<string>; + inStreams: number; + }; + const valueCounts = valueCountMap.get(name)!; + + label.uniqueValues.add(value); + label.inStreams++; + valueCounts.set(value, (valueCounts.get(value) || 0) + 1); + }); + }); + + // Convert to array and sort by unique values count + const labels = Array.from(labelMap.entries()).map(([name, stats]) => { + const valueCounts = Array.from(valueCountMap.get(name)!.entries()) + .map(([value, count]) => ({ value, count })) + .sort((a, b) => b.count - a.count) + .slice(0, 5); + + return { + name, + uniqueValues: stats.uniqueValues.size, + inStreams: stats.inStreams, + sampleValues: valueCounts, + }; + }); + labels.sort((a, b) => b.uniqueValues - a.uniqueValues); + + setAnalysisResults({ + totalStreams: data.data.length, + uniqueLabels: labelMap.size, + labels, + }); + + return data; + } catch (error) { + toast({ + variant: "destructive", + title: "Error analyzing labels", + description: + error instanceof Error + ? error.message + : "An unexpected error occurred", + }); + throw error; + } + }, + enabled: false, + }); + + function onSubmit() { + refetch(); + } + + // Generate CSS variables for colors + const colorStyles = useMemo(() => { + const style = document.createElement("style"); + const colors = + analysisResults?.labels + .slice(0, 10) + .map((_, index) => { + const hue = (index * 137.5) % 360; + return `--chart-color-${index}: hsl(${hue}, 70%, 50%);`; + }) + .join("\n") || ""; + style.textContent = `:root { ${colors} }`; + document.head.appendChild(style); + return () => style.remove(); + }, [analysisResults]); + + // Use effect to cleanup styles + useEffect(() => { + return colorStyles; + }, [colorStyles]); + + // Update chart configuration + const chartConfig = { + value: { + label: + selectedMetric === "uniqueValues" + ? "Unique Values" + : "Found In Streams", + theme: { + light: "var(--chart-color-0)", + dark: "var(--chart-color-0)", + }, + }, + } satisfies ChartConfig; + + const sortedLabels = useMemo(() => { + if (!analysisResults) return []; + + return [...analysisResults.labels].sort((a, b) => { + let comparison = 0; + switch (sortField) { + case "name": + comparison = a.name.localeCompare(b.name); + break; + case "uniqueValues": + comparison = a.uniqueValues - b.uniqueValues; + break; + case "inStreams": + comparison = a.inStreams - b.inStreams; + break; + case "cardinality": + comparison = + a.uniqueValues / a.inStreams - b.uniqueValues / b.inStreams; + break; + } + return sortDirection === "asc" ? comparison : -comparison; + }); + }, [analysisResults, sortField, sortDirection]); + + return ( + <div className="container mx-auto p-4 space-y-6"> + <Card> + <CardHeader> + <CardTitle>Analyze Labels</CardTitle> + <CardDescription> + Analyze label distribution across your log streams + </CardDescription> + </CardHeader> + <CardContent> + <Form {...form}> + <form + onSubmit={form.handleSubmit(onSubmit)} + className="grid grid-cols-1 md:grid-cols-4 gap-4" + > + <FormField + control={form.control} + name="tenant" + render={({ field }) => ( + <FormItem className="flex flex-col space-y-1.5"> + <FormLabel>Tenant ID</FormLabel> + <FormControl> + <Input placeholder="Enter tenant ID..." {...field} /> + </FormControl> + <FormMessage className="text-xs" /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="since" + render={({ field }) => ( + <FormItem className="flex flex-col space-y-1.5"> + <FormLabel>Time Range</FormLabel> + <Select + onValueChange={field.onChange} + defaultValue={field.value} + > + <FormControl> + <SelectTrigger> + <SelectValue placeholder="Select time range" /> + </SelectTrigger> + </FormControl> + <SelectContent> + {durationOptions.map((option) => ( + <SelectItem key={option.value} value={option.value}> + {option.label} + </SelectItem> + ))} + </SelectContent> + </Select> + <FormMessage className="text-xs" /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="matcher" + render={({ field }) => ( + <FormItem className="flex flex-col space-y-1.5"> + <FormLabel>Matcher</FormLabel> + <FormControl> + <Input + placeholder="Enter matcher... (default: {})" + {...field} + /> + </FormControl> + <FormMessage className="text-xs" /> + </FormItem> + )} + /> + + <Button + type="submit" + disabled={isLoading} + className="self-end h-10" + > + {isLoading ? "Analyzing..." : "Analyze"} + </Button> + </form> + </Form> + </CardContent> + </Card> + + {analysisResults && ( + <> + <Card> + <CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row"> + <div className="flex flex-1 flex-col justify-center gap-1 px-6 py-5 sm:py-6"> + <CardTitle>Label Distribution</CardTitle> + <CardDescription> + Top 20 labels by unique values + </CardDescription> + </div> + <div className="flex"> + <div className="relative z-30 flex flex-1 flex-col justify-center gap-1 px-6 py-4 text-left sm:px-8 sm:py-6"> + <span className="text-xs text-muted-foreground"> + Total Streams + </span> + <span className="text-lg font-bold leading-none sm:text-3xl"> + {analysisResults.totalStreams.toLocaleString()} + </span> + </div> + <div className="relative z-30 flex flex-1 flex-col justify-center gap-1 border-l px-6 py-4 text-left sm:px-8 sm:py-6"> + <span className="text-xs text-muted-foreground"> + Unique Labels + </span> + <span className="text-lg font-bold leading-none sm:text-3xl"> + {analysisResults.uniqueLabels.toLocaleString()} + </span> + </div> + </div> + </CardHeader> + <CardContent className="px-2 sm:p-6"> + <div className="mb-4"> + <Select + value={selectedMetric} + onValueChange={(value: MetricType) => + setSelectedMetric(value) + } + > + <SelectTrigger className="w-[200px]"> + <SelectValue placeholder="Select metric" /> + </SelectTrigger> + <SelectContent> + <SelectItem value="uniqueValues">Unique Values</SelectItem> + <SelectItem value="inStreams">Found In Streams</SelectItem> + </SelectContent> + </Select> + </div> + <ChartContainer + config={chartConfig} + className="aspect-auto h-[500px] w-full" + > + <BarChart + data={analysisResults.labels + .slice(0, 20) + .map((label, index) => ({ + name: label.name, + value: + selectedMetric === "uniqueValues" + ? label.uniqueValues + : label.inStreams, + fill: `var(--chart-color-${index})`, + }))} + layout="vertical" + margin={{ + right: 24, + }} + barSize={ + ((500 - 48) / Math.min(20, analysisResults.labels.length)) * + 0.6 + } + maxBarSize={24} + > + <CartesianGrid horizontal={false} /> + <YAxis + dataKey="name" + type="category" + tickLine={false} + axisLine={false} + width={90} + fontSize={11} + interval={0} + /> + <XAxis + type="number" + tickLine={false} + axisLine={false} + tickMargin={8} + /> + <ChartTooltip + content={<ChartTooltipContent className="w-[200px]" />} + /> + <Bar + dataKey="value" + fillOpacity={0.8} + radius={[4, 4, 0, 0]} + /> + </BarChart> + </ChartContainer> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle>Label Details</CardTitle> + </CardHeader> + <CardContent> + <Table> + <TableHeader> + <TableRow> + <TableHead> + <DataTableColumnHeader + title="Label Name" + field="name" + sortField={sortField} + sortDirection={sortDirection} + onSort={(field) => { + if (field === sortField) { + setSortDirection( + sortDirection === "asc" ? "desc" : "asc" + ); + } else { + setSortField(field as SortField); + setSortDirection("desc"); + } + }} + /> + </TableHead> + <TableHead> + <DataTableColumnHeader + title="Unique Values" + field="uniqueValues" + sortField={sortField} + sortDirection={sortDirection} + onSort={(field) => { + if (field === sortField) { + setSortDirection( + sortDirection === "asc" ? "desc" : "asc" + ); + } else { + setSortField(field as SortField); + setSortDirection("desc"); + } + }} + /> + </TableHead> + <TableHead> + <DataTableColumnHeader + title="Found In Streams" + field="inStreams" + sortField={sortField} + sortDirection={sortDirection} + onSort={(field) => { + if (field === sortField) { + setSortDirection( + sortDirection === "asc" ? "desc" : "asc" + ); + } else { + setSortField(field as SortField); + setSortDirection("desc"); + } + }} + /> + </TableHead> + <TableHead> + <DataTableColumnHeader + title="Cardinality %" + field="cardinality" + sortField={sortField} + sortDirection={sortDirection} + onSort={(field) => { + if (field === sortField) { + setSortDirection( + sortDirection === "asc" ? "desc" : "asc" + ); + } else { + setSortField(field as SortField); + setSortDirection("desc"); + } + }} + /> + </TableHead> + </TableRow> + </TableHeader> + <TableBody> + {sortedLabels.map((label) => ( + <Collapsible + key={label.name} + asChild + open={openRows.has(label.name)} + onOpenChange={(isOpen) => { + const newOpenRows = new Set(openRows); + if (isOpen) { + newOpenRows.add(label.name); + } else { + newOpenRows.delete(label.name); + } + setOpenRows(newOpenRows); + }} + > + <> + <TableRow> + <TableCell className="font-medium"> + <CollapsibleTrigger className="flex items-center gap-2 hover:text-primary"> + <ChevronDown + className={cn( + "h-4 w-4 transition-transform", + openRows.has(label.name) && "rotate-180" + )} + /> + {label.name} + </CollapsibleTrigger> + </TableCell> + <TableCell> + {label.uniqueValues.toLocaleString()} + </TableCell> + <TableCell> + {label.inStreams.toLocaleString()} + </TableCell> + <TableCell> + {( + (label.uniqueValues / label.inStreams) * + 100 + ).toFixed(2)} + % + </TableCell> + </TableRow> + <CollapsibleContent asChild> + <TableRow> + <TableCell + colSpan={4} + className="border-t-0 bg-muted/5" + > + <div className="px-4"> + <LabelValuesList + values={label.sampleValues} + totalValues={label.inStreams} + /> + </div> + </TableCell> + </TableRow> + </CollapsibleContent> + </> + </Collapsible> + ))} + </TableBody> + </Table> + </CardContent> + </Card> + </> + )} + </div> + ); +} + +function parseDuration(duration: string): number { + const value = parseInt(duration); + const unit = duration.slice(-1); + const multiplier = unit === "h" ? 3600000 : 0; // Convert hours to milliseconds + return value * multiplier; +} diff --git a/pkg/ui/frontend/src/pages/base-ring.tsx b/pkg/ui/frontend/src/pages/base-ring.tsx new file mode 100644 index 0000000000000..0ca2fe40be0ab --- /dev/null +++ b/pkg/ui/frontend/src/pages/base-ring.tsx @@ -0,0 +1,59 @@ +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Link } from "react-router-dom"; +import { AlertCircle, CircleDot } from "lucide-react"; +import { AVAILABLE_RINGS } from "@/hooks/use-ring"; +import { RingType } from "@/types/ring"; +import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert"; +import { PageContainer } from "@/layout/page-container"; + +interface BaseRingProps { + error?: string; + ringName?: RingType; +} + +export function BaseRing({ error, ringName }: BaseRingProps) { + // Show error state if there is an error + if (error) { + return ( + <PageContainer> + <Alert variant="destructive"> + <AlertCircle className="h-4 w-4" /> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + </PageContainer> + ); + } + + // Show ring selection if no ring is selected + if (!ringName) { + return ( + <PageContainer> + <div className="space-y-6"> + <div className="flex items-center space-x-4"> + <CircleDot className="h-6 w-6" /> + <h1 className="text-2xl font-bold tracking-tight">Rings</h1> + </div> + <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> + {AVAILABLE_RINGS.map((ring) => ( + <Link key={ring.id} to={`/rings/${ring.id}`}> + <Card className="hover:bg-muted/50 transition-colors cursor-pointer"> + <CardHeader> + <CardTitle>{ring.title}</CardTitle> + </CardHeader> + <CardContent> + <p className="text-sm text-muted-foreground"> + View and manage {ring.title.toLowerCase()} ring members + </p> + </CardContent> + </Card> + </Link> + ))} + </div> + </div> + </PageContainer> + ); + } + + return null; +} diff --git a/pkg/ui/frontend/src/pages/coming-soon.tsx b/pkg/ui/frontend/src/pages/coming-soon.tsx new file mode 100644 index 0000000000000..7aca765bae8b9 --- /dev/null +++ b/pkg/ui/frontend/src/pages/coming-soon.tsx @@ -0,0 +1,13 @@ +import { Construction } from "lucide-react"; + +export default function ComingSoon() { + return ( + <div className="flex flex-col items-center justify-center min-h-[80vh] p-4"> + <Construction className="h-16 w-16 text-muted-foreground mb-6" /> + <h1 className="text-4xl font-bold text-center mb-4">Coming Soon</h1> + <p className="text-lg text-muted-foreground text-center max-w-md"> + We're working hard to bring you this feature. Stay tuned for updates! + </p> + </div> + ); +} diff --git a/pkg/ui/frontend/src/pages/data-objects.tsx b/pkg/ui/frontend/src/pages/data-objects.tsx new file mode 100644 index 0000000000000..7a31048e627ad --- /dev/null +++ b/pkg/ui/frontend/src/pages/data-objects.tsx @@ -0,0 +1,64 @@ +import { useSearchParams } from "react-router-dom"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { FileList } from "@/components/explorer/file-list"; +import { useExplorerData } from "@/hooks/use-explorer-data"; +import { ExplorerBreadcrumb } from "@/components/explorer/breadcrumb"; +import { PageContainer } from "@/layout/page-container"; + +export function DataObjectsPage() { + const [searchParams] = useSearchParams(); + const path = searchParams.get("path") || ""; + const { data, isLoading, error } = useExplorerData(path); + + return ( + <PageContainer> + <div className="flex h-full flex-col space-y-6"> + <ExplorerBreadcrumb /> + <ScrollArea className="h-full"> + <div className="grid gap-4"> + <Card> + <CardHeader> + <CardTitle> + <h2 className="text-3xl font-semibold tracking-tight"> + Data Objects Explorer + </h2> + </CardTitle> + <CardDescription> + <p className="text-sm text-muted-foreground mt-1"> + The Data Objects Explorer allows you to explore the data + objects in the cluster. + </p> + </CardDescription> + </CardHeader> + <CardContent> + {isLoading ? ( + <div className="flex items-center justify-center p-8"> + Loading... + </div> + ) : error ? ( + <div className="flex items-center justify-center p-8 text-destructive"> + {error.message} + </div> + ) : data ? ( + <FileList + current={data.current} + parent={data.parent} + files={data.files} + folders={data.folders} + /> + ) : null} + </CardContent> + </Card> + </div> + </ScrollArea> + </div> + </PageContainer> + ); +} diff --git a/pkg/ui/frontend/src/pages/deletes.tsx b/pkg/ui/frontend/src/pages/deletes.tsx new file mode 100644 index 0000000000000..183f5e2c5fbe4 --- /dev/null +++ b/pkg/ui/frontend/src/pages/deletes.tsx @@ -0,0 +1,396 @@ +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader } from "@/components/ui/card"; +import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; +import { useCluster } from "@/contexts/use-cluster"; +import { ServiceNames } from "@/lib/ring-utils"; +import { findNodeName } from "@/lib/utils"; +import { useQuery } from "@tanstack/react-query"; +import { AlertCircle, Loader2, Plus } from "lucide-react"; +import { useMemo, useState } from "react"; +import { Link } from "react-router-dom"; +import { fromUnixTime, formatDistance, format } from "date-fns"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { DataTableColumnHeader } from "@/components/common/data-table-column-header"; +import { Badge } from "@/components/ui/badge"; +import { DateHover } from "@/components/common/date-hover"; +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; +import { Input } from "@/components/ui/input"; +import { PageContainer } from "@/layout/page-container"; + +interface DeleteRequest { + request_id: string; + start_time: number; + end_time: number; + query: string; + status: string; + created_at: number; + user_id: string; + deleted_lines: number; +} + +const DeleteRequestStatus = { + Received: "received", + Processing: "processed", +} as const; + +const useDeletes = (status: string[]) => { + const { cluster } = useCluster(); + const nodeName = useMemo(() => { + return findNodeName(cluster?.members, ServiceNames.compactor); + }, [cluster?.members]); + + const { data, isLoading, error } = useQuery<DeleteRequest[]>({ + queryKey: ["deletes", status, nodeName], + queryFn: async () => { + try { + const requests = await Promise.all( + status.map(async (s) => { + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/compactor/ui/api/v1/deletes?status=${s}` + ); + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + errorText || `HTTP error! status: ${response.status}` + ); + } + return response.json(); + }) + ); + // Flatten the array of arrays into a single array of delete requests + return requests.flat(); + } catch (err) { + throw err instanceof Error + ? err + : new Error("Failed to fetch delete requests"); + } + }, + enabled: !!nodeName, + }); + + return { data, isLoading, error }; +}; + +interface FiltersProps { + selectedStatus: string[]; + onStatusChange: (status: string[]) => void; + queryFilter: string; + onQueryFilterChange: (query: string) => void; +} + +const Filters: React.FC<FiltersProps> = ({ + selectedStatus, + onStatusChange, + queryFilter, + onQueryFilterChange, +}) => { + return ( + <div className="flex items-center gap-4"> + <div className="flex items-center gap-2"> + <span className="text-sm font-medium">Status</span> + <ToggleGroup + type="multiple" + value={selectedStatus} + onValueChange={(value) => { + // Ensure at least one status is always selected + if (value.length > 0) { + onStatusChange(value); + } + }} + className="justify-start" + > + {Object.entries(DeleteRequestStatus).map(([key, value]) => ( + <ToggleGroupItem + key={value} + value={value} + aria-label={`Toggle ${key.toLowerCase()} status`} + className="capitalize" + > + {key} + </ToggleGroupItem> + ))} + </ToggleGroup> + </div> + <Input + type="search" + placeholder="Filter by query..." + value={queryFilter} + onChange={(e) => onQueryFilterChange(e.target.value)} + className="w-[300px]" + /> + </div> + ); +}; + +type DeleteSortField = "status" | "user" | "createdAt" | "duration"; + +interface DeleteListProps { + requests: DeleteRequest[]; + sortField: DeleteSortField; + sortDirection: "asc" | "desc"; + onSort: (field: DeleteSortField) => void; +} + +const StatusBadge = ({ status }: { status: string }) => { + const variant = + status === DeleteRequestStatus.Received ? "secondary" : "default"; + return ( + <Badge variant={variant} className="capitalize"> + {status} + </Badge> + ); +}; + +const RangeHover = ({ start, end }: { start: number; end: number }) => { + const duration = formatDistance( + fromUnixTime(start / 1000), + fromUnixTime(end / 1000) + ); + + const formatUTC = (timestamp: number) => { + const date = new Date(timestamp); + return format( + new Date(date.getTime() + date.getTimezoneOffset() * 60000), + "yyyy-MM-dd HH:mm:ss" + ); + }; + + return ( + <HoverCard> + <HoverCardTrigger> + <span className="cursor-default">{duration}</span> + </HoverCardTrigger> + <HoverCardContent className="w-fit"> + <div className="space-y-2"> + <div className="flex flex-col gap-1"> + <div className="flex items-center gap-2"> + <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> + From + </span> + <span className="font-mono">{formatUTC(start)}</span> + </div> + <div className="flex items-center gap-2"> + <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 rounded dark:bg-gray-700 w-14 text-center"> + To + </span> + <span className="font-mono">{formatUTC(end)}</span> + </div> + </div> + </div> + </HoverCardContent> + </HoverCard> + ); +}; + +const DeleteList: React.FC<DeleteListProps> = ({ + requests, + sortField, + sortDirection, + onSort, +}) => { + const sortedRequests = [...requests].sort((a, b) => { + let comparison = 0; + let durationA: number; + let durationB: number; + + switch (sortField) { + case "status": + comparison = a.status.localeCompare(b.status); + break; + case "user": + comparison = a.user_id.localeCompare(b.user_id); + break; + case "createdAt": + comparison = a.created_at - b.created_at; + break; + case "duration": + durationA = a.end_time - a.start_time; + durationB = b.end_time - b.start_time; + comparison = durationA - durationB; + break; + } + return sortDirection === "asc" ? comparison : -comparison; + }); + + return ( + <div className="rounded-md border bg-card"> + <Table> + <TableHeader> + <TableRow className="hover:bg-transparent"> + <TableHead className="w-[80px]"> + <DataTableColumnHeader<DeleteSortField> + title="Status" + field="status" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[100px]"> + <DataTableColumnHeader<DeleteSortField> + title="User" + field="user" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[200px]"> + <DataTableColumnHeader<DeleteSortField> + title="Created At" + field="createdAt" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[150px]"> + <DataTableColumnHeader<DeleteSortField> + title="Range" + field="duration" + sortField={sortField} + sortDirection={sortDirection} + onSort={onSort} + /> + </TableHead> + <TableHead className="w-[100px]">Deleted Lines</TableHead> + <TableHead>Query</TableHead> + </TableRow> + </TableHeader> + <TableBody> + {sortedRequests.map((request) => ( + <TableRow + key={`${request.request_id}-${request.start_time}-${request.end_time}`} + > + <TableCell className="px-4"> + <StatusBadge status={request.status} /> + </TableCell> + <TableCell>{request.user_id}</TableCell> + <TableCell> + <DateHover date={new Date(request.created_at)} /> + </TableCell> + <TableCell> + <RangeHover start={request.start_time} end={request.end_time} /> + </TableCell> + <TableCell>{request.deleted_lines}</TableCell> + <TableCell> + <code className="font-mono text-sm whitespace-pre-wrap break-all"> + {request.query} + </code> + </TableCell> + </TableRow> + ))} + {sortedRequests.length === 0 && ( + <TableRow> + <TableCell colSpan={7} className="h-24 text-center"> + <div className="text-muted-foreground"> + No delete requests found + </div> + </TableCell> + </TableRow> + )} + </TableBody> + </Table> + </div> + ); +}; + +const DeletesPage = () => { + const [status, setStatus] = useState<string[]>([ + DeleteRequestStatus.Received, + DeleteRequestStatus.Processing, + ]); + const [queryFilter, setQueryFilter] = useState(""); + const [sortField, setSortField] = useState<DeleteSortField>("createdAt"); + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc"); + const { data, isLoading, error } = useDeletes(status); + + const filteredData = useMemo(() => { + if (!data || !queryFilter) return data; + return data.filter((request) => + request.query.toLowerCase().includes(queryFilter.toLowerCase()) + ); + }, [data, queryFilter]); + + const handleSort = (field: DeleteSortField) => { + if (field === sortField) { + setSortDirection(sortDirection === "asc" ? "desc" : "asc"); + } else { + setSortField(field); + setSortDirection("desc"); + } + }; + + return ( + <PageContainer> + <Card className="shadow-sm"> + <CardHeader> + <div className="flex flex-col gap-6"> + <div className="flex items-start justify-between"> + <div> + <h2 className="text-3xl font-semibold tracking-tight"> + Delete Requests + </h2> + <p className="text-sm text-muted-foreground mt-1"> + View and manage delete requests in your cluster + </p> + </div> + <Button variant="default" asChild> + <Link to="/tenants/deletes/new"> + <Plus className="mr-2 h-4 w-4" /> + New Delete Request + </Link> + </Button> + </div> + <Filters + selectedStatus={status} + onStatusChange={setStatus} + queryFilter={queryFilter} + onQueryFilterChange={setQueryFilter} + /> + </div> + </CardHeader> + <CardContent> + <div className="space-y-4"> + {error && ( + <Alert variant="destructive"> + <AlertCircle className="h-4 w-4" /> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error.message}</AlertDescription> + </Alert> + )} + + {isLoading && ( + <div className="flex items-center justify-center p-8"> + <Loader2 className="h-16 w-16 animate-spin" /> + </div> + )} + + {!isLoading && !error && filteredData && ( + <DeleteList + requests={filteredData} + sortField={sortField} + sortDirection={sortDirection} + onSort={handleSort} + /> + )} + </div> + </CardContent> + </Card> + </PageContainer> + ); +}; + +export default DeletesPage; diff --git a/pkg/ui/frontend/src/pages/file-metadata.tsx b/pkg/ui/frontend/src/pages/file-metadata.tsx new file mode 100644 index 0000000000000..42779710158d0 --- /dev/null +++ b/pkg/ui/frontend/src/pages/file-metadata.tsx @@ -0,0 +1,45 @@ +import { useSearchParams } from "react-router-dom"; +import { FileMetadataView } from "@/components/explorer/file-metadata"; +import { useFileMetadata } from "@/hooks/use-file-metadata"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { ExplorerBreadcrumb } from "@/components/explorer/breadcrumb"; +import { Loader2 } from "lucide-react"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { PageContainer } from "@/layout/page-container"; + +export function FileMetadataPage() { + const [searchParams] = useSearchParams(); + const path = searchParams.get("path") || ""; + const { + data: metadata, + downloadUrl, + isLoading, + error, + } = useFileMetadata(path); + + return ( + <PageContainer> + <div className="flex h-full flex-col space-y-6"> + <ExplorerBreadcrumb /> + <ScrollArea className="h-full"> + {isLoading ? ( + <div className="flex items-center justify-center p-8"> + <Loader2 className="h-16 w-16 animate-spin" /> + </div> + ) : error ? ( + <Alert variant="destructive"> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error.message}</AlertDescription> + </Alert> + ) : metadata && path ? ( + <FileMetadataView + metadata={metadata} + filename={path} + downloadUrl={downloadUrl} + /> + ) : null} + </ScrollArea> + </div> + </PageContainer> + ); +} diff --git a/pkg/ui/frontend/src/pages/new-delete.tsx b/pkg/ui/frontend/src/pages/new-delete.tsx new file mode 100644 index 0000000000000..307b2245fbc28 --- /dev/null +++ b/pkg/ui/frontend/src/pages/new-delete.tsx @@ -0,0 +1,333 @@ +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { Textarea } from "@/components/ui/textarea"; +import { useCluster } from "@/contexts/use-cluster"; +import { ServiceNames } from "@/lib/ring-utils"; +import { findNodeName } from "@/lib/utils"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { formatDuration, intervalToDuration } from "date-fns"; +import debounce from "lodash/debounce"; +import { AlertCircle, Loader2 } from "lucide-react"; +import { useCallback, useMemo, useState } from "react"; +import { useForm, ControllerRenderProps } from "react-hook-form"; +import { useNavigate } from "react-router-dom"; +import { useQueryClient } from "@tanstack/react-query"; +import * as z from "zod"; +import DatePicker from "react-datepicker"; +import "react-datepicker/dist/react-datepicker.css"; +import { PageContainer } from "@/layout/page-container"; + +const formSchema = z.object({ + tenant_id: z.string().min(1, "Tenant ID is required"), + query: z.string().min(1, "Query is required"), + start_time: z.date(), + end_time: z + .date() + .refine( + (date) => date > new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), + "End time must be after start time" + ), +}); + +type FormValues = z.infer<typeof formSchema>; + +// Add types for event handlers +type TextareaEvent = React.ChangeEvent<HTMLTextAreaElement>; + +const NewDeleteRequest = () => { + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const [error, setError] = useState<string | null>(null); + const [queryValidating, setQueryValidating] = useState(false); + const { cluster } = useCluster(); + const nodeName = useMemo(() => { + return findNodeName(cluster?.members, ServiceNames.compactor); + }, [cluster?.members]); + + const form = useForm<z.infer<typeof formSchema>>({ + resolver: zodResolver(formSchema), + defaultValues: { + tenant_id: "", + query: "", + start_time: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 1 week ago + end_time: new Date(), // now + }, + }); + + const validateQuery = useCallback( + async (query: string, shouldFormat = false) => { + if (!query.trim()) return; + + setQueryValidating(true); + try { + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/loki/api/v1/format_query?query=${query}`, + { + method: "POST", + } + ); + + const result = await response.json(); + + if (!response.ok || result.status === "invalid-query") { + throw new Error(result.error || "Invalid LogQL query"); + } + + // Clear any existing query errors when validation succeeds + form.clearErrors("query"); + + if (shouldFormat) { + form.setValue("query", result.data); + } + } catch (error) { + form.setError("query", { + message: + error instanceof Error ? error.message : "Invalid LogQL query", + }); + } finally { + setQueryValidating(false); + } + }, + [form, nodeName] + ); + + const debouncedValidate = useMemo( + () => debounce((query: string) => validateQuery(query, false), 1000), + [validateQuery] + ); + + const onSubmit = async (values: z.infer<typeof formSchema>) => { + const params = new URLSearchParams(); + params.append("query", values.query); + params.append( + "start", + Math.floor(values.start_time.getTime() / 1000).toString() + ); + params.append( + "end", + Math.floor(values.end_time.getTime() / 1000).toString() + ); + + try { + const response = await fetch( + `/ui/api/v1/proxy/${nodeName}/compactor/ui/api/v1/deletes?${params.toString()}`, + { + method: "POST", + headers: { + "X-Scope-OrgID": values.tenant_id, + }, + } + ); + + if (!response.ok) { + const text = await response.text(); + throw new Error(text || "Failed to create delete request"); + } + + await queryClient.invalidateQueries({ queryKey: ["deletes"] }); + navigate("/tenants/deletes"); + } catch (error) { + console.error("Error creating delete request:", error); + setError( + error instanceof Error + ? error.message + : "Failed to create delete request" + ); + } + }; + + const duration = useMemo(() => { + const start = form.watch("start_time"); + const end = form.watch("end_time"); + return formatDuration( + intervalToDuration({ + start, + end, + }), + { + format: ["years", "months", "weeks", "days", "hours", "minutes"], + zero: false, + } + ); + }, [form]); + + return ( + <PageContainer> + <Card> + <CardHeader> + <CardTitle>New Delete Request</CardTitle> + </CardHeader> + <CardContent> + {error && ( + <Alert variant="destructive" className="mb-6"> + <AlertCircle className="h-4 w-4" /> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + )} + + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> + <FormField + control={form.control} + name="tenant_id" + render={({ + field, + }: { + field: ControllerRenderProps<FormValues, "tenant_id">; + }) => ( + <FormItem> + <FormLabel>TENANT ID</FormLabel> + <FormControl> + <Input placeholder="Enter tenant ID" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="query" + render={({ + field, + }: { + field: ControllerRenderProps<FormValues, "query">; + }) => ( + <FormItem> + <FormLabel>LOGQL QUERY</FormLabel> + <FormControl> + <div className="relative"> + <Textarea + placeholder='{app="example"}' + className="font-mono" + {...field} + onChange={(e: TextareaEvent) => { + field.onChange(e); + debouncedValidate(e.target.value); + }} + onBlur={async (e: TextareaEvent) => { + field.onBlur(); + if (e.target.value) { + await validateQuery(e.target.value, true); + } + }} + /> + {queryValidating && ( + <div className="absolute right-3 top-3"> + <Loader2 className="h-5 w-5 animate-spin" /> + </div> + )} + </div> + </FormControl> + <FormDescription> + Enter a LogQL query with labels in curly braces + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <div className="grid grid-cols-3 gap-8"> + <FormField + control={form.control} + name="start_time" + render={({ + field, + }: { + field: ControllerRenderProps<FormValues, "start_time">; + }) => ( + <FormItem> + <FormLabel>START TIME</FormLabel> + <FormControl> + <DatePicker + selected={field.value} + onChange={field.onChange} + showTimeSelect + timeFormat="HH:mm" + timeIntervals={15} + dateFormat="yyyy-MM-dd HH:mm" + className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50" + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="end_time" + render={({ + field, + }: { + field: ControllerRenderProps<FormValues, "end_time">; + }) => ( + <FormItem> + <FormLabel>END TIME</FormLabel> + <FormControl> + <DatePicker + selected={field.value} + onChange={field.onChange} + showTimeSelect + timeFormat="HH:mm" + timeIntervals={15} + dateFormat="yyyy-MM-dd HH:mm" + minDate={form.watch("start_time")} + className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50" + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <div className="space-y-2"> + <FormLabel>DURATION</FormLabel> + <div className="h-10 flex items-center"> + <span className="text-sm text-muted-foreground"> + {duration} + </span> + </div> + </div> + </div> + + <div className="flex justify-end space-x-3 pt-6 border-t"> + <Button + type="button" + variant="outline" + onClick={() => navigate("/tenants/deletes")} + > + Cancel + </Button> + <Button + type="submit" + disabled={ + !form.formState.isValid || form.formState.isSubmitting + } + > + {form.formState.isSubmitting + ? "Creating..." + : "Create Delete Request"} + </Button> + </div> + </form> + </Form> + </CardContent> + </Card> + </PageContainer> + ); +}; + +export default NewDeleteRequest; diff --git a/pkg/ui/frontend/src/pages/node-details.tsx b/pkg/ui/frontend/src/pages/node-details.tsx new file mode 100644 index 0000000000000..248c468aabf72 --- /dev/null +++ b/pkg/ui/frontend/src/pages/node-details.tsx @@ -0,0 +1,210 @@ +import { useParams } from "react-router-dom"; +import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card"; +import { ErrorBoundary } from "@/components/shared/errors/error-boundary"; +import { useState } from "react"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { CodeBlock } from "@/components/ui/code-block"; +import { format } from "date-fns"; +import { useNodeDetails } from "@/hooks/use-node-details"; +import { useNodeMetrics } from "@/hooks/use-node-metrics"; +import { ServiceStateDistribution } from "@/components/nodes/service-state-distribution"; +import { ServiceTable } from "@/components/nodes/service-table"; +import { StorageTypeIndicator } from "@/components/nodes/storage-type-indicator"; +import { Label } from "@/components/ui/label"; +import { LogLevelSelect } from "@/components/nodes/log-level-select"; +import { Switch } from "@/components/ui/switch"; +import { VersionInformation } from "@/components/nodes/version-information"; +import { NodeStatusIndicator } from "@/components/nodes/node-status-indicator"; +import { PprofControls } from "@/components/nodes/pprof-controls"; +import { CopyButton } from "@/components/common/copy-button"; +import { PageContainer } from "@/layout/page-container"; +function NodeDetailsPage() { + const { nodeName } = useParams(); + const [activeTab, setActiveTab] = useState("config"); + const { nodeDetails, isLoading, error } = useNodeDetails(nodeName); + const { + metrics: rawMetrics, + isLoading: isLoadingMetrics, + error: metricsError, + } = useNodeMetrics(nodeName, activeTab === "raw-metrics"); + const [showTable, setShowTable] = useState(false); + + if (isLoading) { + return ( + <div className="container space-y-6 p-6"> + <div className="flex items-center justify-center"> + <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div> + <span className="ml-2 text-sm text-muted-foreground">Loading...</span> + </div> + </div> + ); + } + + if (!nodeDetails) { + return ( + <div className="container space-y-6 p-6"> + <div className="bg-red-50 dark:bg-red-900 border-l-4 border-red-400 p-4"> + <div className="flex"> + <div className="ml-3"> + <p className="text-sm text-red-700 dark:text-red-200"> + {error || `Node "${nodeName}" not found`} + </p> + </div> + </div> + </div> + </div> + ); + } + + return ( + <PageContainer> + {/* Main Node Card */} + <Card> + <CardHeader> + <div className="flex items-center gap-4"> + <div className="flex-1"> + <CardTitle> + <h2 className="text-3xl font-semibold tracking-tight"> + <div className="flex items-center gap-2"> + {nodeDetails.target} - {nodeName} + <CopyButton text={nodeName || ""} /> + </div> + </h2> + </CardTitle> + </div> + <NodeStatusIndicator nodeName={nodeName || ""} /> + </div> + </CardHeader> + <CardContent className="space-y-6"> + {/* Three Information Cards */} + <div className="grid grid-cols-3 gap-4"> + <VersionInformation + build={nodeDetails.build} + edition={nodeDetails.edition} + os={nodeDetails.os} + arch={nodeDetails.arch} + /> + + <Card> + <CardHeader> + <CardTitle>Cluster Information</CardTitle> + </CardHeader> + <CardContent> + <div className="space-y-2"> + <div className="space-y-2"> + <Label>Cluster ID</Label> + <p className="text-sm">{nodeDetails.clusterID}</p> + </div> + <div className="space-y-2"> + <Label>Created</Label> + <p className="text-sm"> + {format(nodeDetails.clusterSeededAt, "PPpp")} + </p> + </div> + <div className="space-y-2"> + <Label>Storage</Label> + <p> + <StorageTypeIndicator + type={( + nodeDetails.metrics.store_object_type || "filesystem" + ).toLowerCase()} + className="" + /> + </p> + </div> + </div> + </CardContent> + </Card> + + <Card> + <CardHeader className="flex flex-row items-center justify-between"> + <CardTitle>Service Status</CardTitle> + <div className="flex items-center space-x-2"> + <Label htmlFor="view-mode">Table View</Label> + <Switch + id="view-mode" + checked={showTable} + onCheckedChange={setShowTable} + /> + </div> + </CardHeader> + <CardContent> + {showTable ? ( + <ServiceTable services={nodeDetails.services} /> + ) : ( + <ServiceStateDistribution services={nodeDetails.services} /> + )} + </CardContent> + </Card> + </div> + + {/* Controls Section */} + <div className="flex items-center gap-6"> + <div className="flex items-center gap-2 mr-4"> + <Label>Log Level</Label> + <LogLevelSelect nodeName={nodeName || ""} /> + </div> + + <PprofControls nodeName={nodeName || ""} /> + </div> + + <div> + <Tabs defaultValue="config" onValueChange={setActiveTab}> + <TabsList> + <TabsTrigger value="config">Configuration</TabsTrigger> + <TabsTrigger value="metrics">Analytics</TabsTrigger> + <TabsTrigger value="raw-metrics">Raw Metrics</TabsTrigger> + </TabsList> + <TabsContent value="config" className="mt-6"> + <CodeBlock + language="yaml" + code={nodeDetails.config} + fileName="loki.yaml" + /> + </TabsContent> + <TabsContent value="metrics" className="mt-6"> + {nodeDetails.metrics && ( + <CodeBlock + code={JSON.stringify(nodeDetails.metrics, null, 2)} + language="json" + fileName="analytics.json" + /> + )} + </TabsContent> + <TabsContent value="raw-metrics" className="mt-6"> + {isLoadingMetrics ? ( + <div className="flex items-center justify-center p-6"> + <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div> + <span className="ml-2 text-sm text-muted-foreground"> + Loading metrics... + </span> + </div> + ) : metricsError ? ( + <div className="bg-red-50 dark:bg-red-900 border-l-4 border-red-400 p-4"> + <p className="text-sm text-red-700 dark:text-red-200"> + {metricsError} + </p> + </div> + ) : rawMetrics ? ( + <CodeBlock + code={rawMetrics} + language="yaml" + fileName="metrics" + /> + ) : null} + </TabsContent> + </Tabs> + </div> + </CardContent> + </Card> + </PageContainer> + ); +} + +export default function NodeDetailsPageWithErrorBoundary() { + return ( + <ErrorBoundary> + <NodeDetailsPage /> + </ErrorBoundary> + ); +} diff --git a/pkg/ui/frontend/src/pages/nodes.tsx b/pkg/ui/frontend/src/pages/nodes.tsx new file mode 100644 index 0000000000000..608637e6ad7d7 --- /dev/null +++ b/pkg/ui/frontend/src/pages/nodes.tsx @@ -0,0 +1,148 @@ +import { useState } from "react"; +import NodeFilters from "@/components/nodes/node-filters"; +import NodeList from "@/components/nodes/node-list"; +import { TargetDistributionChart } from "@/components/nodes/target-distribution-chart"; +import { Member, NodeState } from "../types/cluster"; +import { Card, CardHeader, CardContent } from "@/components/ui/card"; +import { ErrorBoundary } from "@/components/shared/errors/error-boundary"; +import { useCluster } from "@/contexts/use-cluster"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { AlertCircle } from "lucide-react"; +import { PageContainer } from "@/layout/page-container"; + +const NodesPage = () => { + const { cluster, error, refresh, isLoading } = useCluster(); + const [nameFilter, setNameFilter] = useState(""); + const [targetFilter, setTargetFilter] = useState<string[]>([]); + const [selectedStates, setSelectedStates] = useState<NodeState[]>([ + "New", + "Starting", + "Running", + "Stopping", + "Terminated", + "Failed", + ]); + const [sortField, setSortField] = useState< + "name" | "target" | "version" | "buildDate" + >("name"); + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc"); + + const handleSort = (field: "name" | "target" | "version" | "buildDate") => { + if (field === sortField) { + setSortDirection(sortDirection === "asc" ? "desc" : "asc"); + } else { + setSortField(field); + setSortDirection("asc"); + } + }; + + const filterNodes = () => { + if (!cluster) return {}; + + return Object.entries(cluster.members).reduce((acc, [name, node]) => { + const matchesName = name.toLowerCase().includes(nameFilter.toLowerCase()); + const matchesTarget = + !targetFilter || + targetFilter.length === 0 || + targetFilter.includes(node.target); + + // Show node if any of its services match any of the selected states + const hasMatchingService = + selectedStates.length === 0 || + (node.services && + Array.isArray(node.services) && + node.services.some( + (service) => + service?.status && + selectedStates.includes(service.status as NodeState) + )); + + if (matchesName && matchesTarget && hasMatchingService) { + acc[name] = node; + } + return acc; + }, {} as { [key: string]: Member }); + }; + + const getAvailableTargets = () => { + if (!cluster) return []; + const targets = new Set<string>(); + Object.values(cluster.members).forEach((node) => { + if (node.target) targets.add(node.target); + }); + return Array.from(targets).sort(); + }; + + return ( + <PageContainer> + <Card className="shadow-sm"> + <CardHeader> + <div className="grid grid-cols-[1fr_auto] gap-8"> + <div className="space-y-6"> + <div> + <h2 className="text-3xl font-semibold tracking-tight">Nodes</h2> + <p className="text-sm text-muted-foreground mt-1"> + View and manage Loki nodes in your cluster with their current + status and configuration + </p> + </div> + <NodeFilters + nameFilter={nameFilter} + targetFilter={targetFilter} + selectedStates={selectedStates} + onNameFilterChange={setNameFilter} + onTargetFilterChange={setTargetFilter} + onStatesChange={setSelectedStates} + onRefresh={refresh} + availableTargets={getAvailableTargets()} + isLoading={isLoading} + /> + </div> + <div className="flex items-center"> + <div className="w-[250px]"> + <TargetDistributionChart nodes={filterNodes()} /> + </div> + </div> + </div> + </CardHeader> + <CardContent> + <div className="space-y-4"> + {error && ( + <Alert variant="destructive"> + <AlertCircle className="h-4 w-4" /> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + )} + + {isLoading && ( + <div className="flex items-center justify-center py-4"> + <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div> + <span className="ml-2 text-sm text-muted-foreground"> + Loading... + </span> + </div> + )} + + {!isLoading && !error && ( + <NodeList + nodes={filterNodes()} + sortField={sortField} + sortDirection={sortDirection} + onSort={handleSort} + /> + )} + </div> + </CardContent> + </Card> + </PageContainer> + ); +}; + +export default function NodesPageWithErrorBoundary() { + return ( + <ErrorBoundary> + <NodesPage /> + </ErrorBoundary> + ); +} diff --git a/pkg/ui/frontend/src/pages/partition-ring.tsx b/pkg/ui/frontend/src/pages/partition-ring.tsx new file mode 100644 index 0000000000000..645f1b0d84e2d --- /dev/null +++ b/pkg/ui/frontend/src/pages/partition-ring.tsx @@ -0,0 +1,359 @@ +import { useState, useCallback, useMemo } from "react"; +import { usePartitionRing } from "@/hooks/use-partition-ring"; +import { + PartitionRingTable, + SortField, +} from "@/components/ring/partition-ring-table"; +import { getStateColors, parseZoneFromOwner } from "@/lib/ring-utils"; +import { useToast } from "@/hooks/use-toast"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { RefreshLoop } from "@/components/common/refresh-loop"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { cn } from "@/lib/utils"; +import { Loader2, ArrowRightCircle } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { PartitionStateDistributionChart } from "@/components/ring/partition-state-distribution-chart"; +import { PartitionRingFilters } from "@/components/ring/partition-ring-filters"; +import { BaseRing } from "./base-ring"; + +const STATE_OPTIONS = [ + { value: 1, label: "Pending" }, + { value: 2, label: "Active" }, + { value: 3, label: "Inactive" }, + { value: 4, label: "Deleted" }, +] as const; + +export default function PartitionRing() { + const [selectedPartitions, setSelectedPartitions] = useState<Set<number>>( + new Set() + ); + const [sortField, setSortField] = useState<SortField>("id"); + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc"); + const [idFilter, setIdFilter] = useState<string[]>([]); + const [stateFilter, setStateFilter] = useState<string[]>([]); + const [zoneFilter, setZoneFilter] = useState<string[]>([]); + const [ownerFilter, setOwnerFilter] = useState(""); + const [isStateChangeLoading, setIsStateChangeLoading] = useState(false); + const [selectedNewState, setSelectedNewState] = useState<string>(); + const [isStateChangeDialogOpen, setIsStateChangeDialogOpen] = useState(false); + const { toast } = useToast(); + + const { + partitions, + error: partitionError, + isLoading: isPartitionsLoading, + fetchPartitions, + changePartitionState, + uniqueStates, + uniqueZones, + } = usePartitionRing({ isPaused: selectedPartitions.size > 0 }); + + // Denormalize partitions by owner + const denormalizedPartitions = useMemo(() => { + return partitions.flatMap((partition) => + partition.owner_ids.map((owner) => ({ + ...partition, + owner_id: owner, + owner_ids: [owner], + zone: parseZoneFromOwner(owner), + })) + ); + }, [partitions]); + + // Handle sorting + const handleSort = useCallback((field: SortField) => { + setSortField((currentField) => { + if (currentField === field) { + setSortDirection((currentDirection) => + currentDirection === "asc" ? "desc" : "asc" + ); + return field; + } + setSortDirection("asc"); + return field; + }); + }, []); + + // Handle partition selection + const togglePartition = useCallback((partitionId: number) => { + setSelectedPartitions((prev) => { + const newSet = new Set(prev); + if (newSet.has(partitionId)) { + newSet.delete(partitionId); + } else { + newSet.add(partitionId); + } + return newSet; + }); + }, []); + + // Filter partitions + const filteredPartitions = useMemo(() => { + return denormalizedPartitions.filter((partition) => { + const matchesId = + idFilter.length === 0 || idFilter.includes(partition.id.toString()); + const matchesState = + stateFilter.length === 0 || + stateFilter.includes(partition.state.toString()); + const matchesZone = + zoneFilter.length === 0 || zoneFilter.includes(partition.zone); + const matchesOwner = ownerFilter + ? partition.owner_id.toLowerCase().includes(ownerFilter.toLowerCase()) + : true; + + return matchesId && matchesState && matchesZone && matchesOwner; + }); + }, [denormalizedPartitions, idFilter, stateFilter, zoneFilter, ownerFilter]); + + // Get selected partition details + const selectedPartitionDetails = useMemo( + () => + denormalizedPartitions.filter((partition) => + selectedPartitions.has(partition.id) + ), + [denormalizedPartitions, selectedPartitions] + ); + + // Handle state change + const handleStateChange = useCallback(async () => { + if (selectedPartitions.size === 0 || !selectedNewState) return; + + try { + setIsStateChangeLoading(true); + const newState = parseInt(selectedNewState, 10); + const { success, total } = await changePartitionState( + selectedPartitionDetails.map((p) => p.id), + selectedNewState + ); + + if (success > 0 && total === success) { + toast({ + title: "State Change Success", + description: `Successfully changed state for ${success} partition${ + success !== 1 ? "s" : "" + } to ${STATE_OPTIONS.find((opt) => opt.value === newState)?.label}`, + }); + await fetchPartitions(); + } else if (success < total) { + toast({ + title: "State Change Failed", + variant: "destructive", + description: `Failed to change state for ${ + total - success + } partition${total - success !== 1 ? "s" : ""}.`, + }); + } + + setSelectedPartitions(new Set()); + setSelectedNewState(undefined); + } catch (err) { + toast({ + title: "Error", + description: + "An unexpected error occurred while changing partition states.", + }); + } finally { + setIsStateChangeLoading(false); + setIsStateChangeDialogOpen(false); + } + }, [ + selectedPartitions, + selectedNewState, + selectedPartitionDetails, + changePartitionState, + fetchPartitions, + toast, + ]); + + // Table props + const tableProps = { + partitions: filteredPartitions, + selectedPartitions, + onSelectPartition: togglePartition, + sortField, + sortDirection, + onSort: handleSort, + onStateChange: handleStateChange, + }; + + if (partitionError) { + return <BaseRing error={partitionError} ringName={"partition-ingester"} />; + } + + return ( + <div className="container space-y-6 p-6"> + <Card> + <CardHeader> + <div className="grid grid-cols-[1fr_auto] gap-8"> + <div className="space-y-6"> + <div> + <CardTitle className="text-3xl font-semibold tracking-tight"> + Partition Ring Members + </CardTitle> + <p className="text-sm text-muted-foreground mt-1"> + View and manage partition ring instances with their current + status and configuration + </p> + </div> + <div className="flex items-center justify-between min-h-[32px]"> + <RefreshLoop + onRefresh={fetchPartitions} + isPaused={selectedPartitions.size > 0} + isLoading={isPartitionsLoading} + /> + {selectedPartitions.size > 0 && ( + <div className="flex items-center gap-4"> + <span className="text-sm text-muted-foreground"> + {selectedPartitions.size} partition + {selectedPartitions.size !== 1 ? "s" : ""} selected + </span> + <Select + value={selectedNewState} + onValueChange={setSelectedNewState} + > + <SelectTrigger className="w-[160px]"> + <SelectValue placeholder="Select new state" /> + </SelectTrigger> + <SelectContent> + {STATE_OPTIONS.map((option) => ( + <SelectItem + key={option.value} + value={option.value.toString()} + > + {option.label} + </SelectItem> + ))} + </SelectContent> + </Select> + <Button + onClick={() => setIsStateChangeDialogOpen(true)} + disabled={isStateChangeLoading || !selectedNewState} + size="sm" + variant="outline" + > + {isStateChangeLoading && ( + <Loader2 className="mr-2 h-4 w-4 animate-spin" /> + )} + Change State + </Button> + </div> + )} + </div> + </div> + <div className="flex items-center"> + <div className="w-[250px]"> + <PartitionStateDistributionChart partitions={partitions} /> + </div> + </div> + </div> + </CardHeader> + <CardContent className="space-y-6"> + <PartitionRingFilters + idFilter={idFilter} + onIdFilterChange={setIdFilter} + stateFilter={stateFilter} + onStateFilterChange={setStateFilter} + zoneFilter={zoneFilter} + onZoneFilterChange={setZoneFilter} + ownerFilter={ownerFilter} + onOwnerFilterChange={setOwnerFilter} + uniqueStates={uniqueStates} + uniqueZones={uniqueZones} + partitions={partitions} + /> + <div className="rounded-md border bg-card"> + <PartitionRingTable {...tableProps} /> + </div> + </CardContent> + </Card> + + <Dialog + open={isStateChangeDialogOpen} + onOpenChange={setIsStateChangeDialogOpen} + > + <DialogContent> + <DialogHeader> + <DialogTitle>Confirm State Change</DialogTitle> + <DialogDescription> + Are you sure you want to change the state of these partitions? + </DialogDescription> + </DialogHeader> + <div className="max-h-[300px] overflow-y-auto"> + <div className="space-y-2"> + {Array.from( + new Set(selectedPartitionDetails.map((p) => p.id)) + ).map((partitionId) => { + const partition = partitions.find((p) => p.id === partitionId); + if (!partition) return null; + return ( + <div + key={partitionId} + className="flex items-center justify-between p-2 rounded-md bg-muted" + > + <div className="flex items-center gap-2"> + <span className="font-medium"> + Partition {partitionId} + </span> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium", + getStateColors(partition.state) + )} + > + { + STATE_OPTIONS.find( + (opt) => opt.value === partition.state + )?.label + } + </span> + <ArrowRightCircle className="h-4 w-4 text-muted-foreground" /> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium", + getStateColors(parseInt(selectedNewState || "0", 10)) + )} + > + { + STATE_OPTIONS.find( + (opt) => + opt.value === parseInt(selectedNewState!, 10) + )?.label + } + </span> + </div> + </div> + ); + })} + </div> + </div> + <DialogFooter> + <Button + variant="outline" + onClick={() => setIsStateChangeDialogOpen(false)} + disabled={isStateChangeLoading} + > + Cancel + </Button> + <Button onClick={handleStateChange} disabled={isStateChangeLoading}> + {isStateChangeLoading ? "Changing States..." : "Confirm Changes"} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + </div> + ); +} diff --git a/pkg/ui/frontend/src/pages/regular-ring.tsx b/pkg/ui/frontend/src/pages/regular-ring.tsx new file mode 100644 index 0000000000000..3acfe432f2fdf --- /dev/null +++ b/pkg/ui/frontend/src/pages/regular-ring.tsx @@ -0,0 +1,336 @@ +import { useState, useCallback, useMemo } from "react"; +import { RingType } from "@/types/ring"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Loader2 } from "lucide-react"; +import { AVAILABLE_RINGS, useRing } from "@/hooks/use-ring"; +import { + RingInstanceTable, + SortField, +} from "@/components/ring/ring-instance-table"; +import { RingFilters } from "@/components/ring/ring-filters"; +import { cn } from "@/lib/utils"; +import { getStateColors } from "@/lib/ring-utils"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { RingStateDistributionChart } from "@/components/ring/ring-state-distribution-chart"; +import { RefreshLoop } from "@/components/common/refresh-loop"; +import { BaseRing } from "./base-ring"; +import { useToast } from "@/hooks/use-toast"; + +interface RegularRingProps { + ringName: RingType; +} + +export function RegularRing({ ringName }: RegularRingProps) { + const [selectedInstances, setSelectedInstances] = useState<Set<string>>( + new Set() + ); + const [isForgetLoading, setIsForgetLoading] = useState(false); + const [forgetProgress, setForgetProgress] = useState<number>(0); + const [sortField, setSortField] = useState<SortField>("id"); + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc"); + const [idFilter, setIdFilter] = useState(""); + const [stateFilter, setStateFilter] = useState<string[]>([]); + const [zoneFilter, setZoneFilter] = useState<string[]>([]); + const [isForgetDialogOpen, setIsForgetDialogOpen] = useState(false); + + const { + ring, + error, + isLoading, + fetchRing, + forgetInstances, + uniqueStates, + uniqueZones, + isTokenBased, + } = useRing({ ringName, isPaused: selectedInstances.size > 0 }); + + // Get selected instance details + const selectedInstanceDetails = useMemo(() => { + if (!ring?.shards) return []; + return ring.shards.filter((instance) => selectedInstances.has(instance.id)); + }, [ring?.shards, selectedInstances]); + + // Handle sorting + const handleSort = useCallback((field: SortField) => { + setSortField((currentField) => { + if (currentField === field) { + setSortDirection((currentDirection) => + currentDirection === "asc" ? "desc" : "asc" + ); + return field; + } + setSortDirection("asc"); + return field; + }); + }, []); + + // Handle instance selection + const toggleInstance = useCallback((instanceId: string) => { + setSelectedInstances((prev) => { + const newSet = new Set(prev); + if (newSet.has(instanceId)) { + newSet.delete(instanceId); + } else { + newSet.add(instanceId); + } + return newSet; + }); + }, []); + + const { toast } = useToast(); + + // Handle forget instances + const handleForget = useCallback(async () => { + if (selectedInstances.size === 0) return; + + try { + setIsForgetLoading(true); + setForgetProgress(0); + + const { success, total } = await forgetInstances( + Array.from(selectedInstances) + ); + if (success > 0) { + await fetchRing(); + setSelectedInstances(new Set()); + } + + if (success < total) { + toast({ + title: "Failed to forget instances", + description: `Failed to forget ${total - success} instance(s)`, + variant: "destructive", + }); + } + } catch (err) { + toast({ + title: "Failed to forget instances", + description: `${error}`, + variant: "destructive", + }); + } finally { + setIsForgetLoading(false); + setIsForgetDialogOpen(false); + } + }, [selectedInstances, forgetInstances, fetchRing, toast, error]); + + // Filter and sort instances + const sortedInstances = useMemo(() => { + if (!ring?.shards) return []; + + return ring.shards + .filter((instance) => { + const matchesId = instance.id + .toLowerCase() + .includes(idFilter.toLowerCase()); + const matchesState = + stateFilter.length === 0 || stateFilter.includes(instance.state); + const matchesZone = + zoneFilter.length === 0 || zoneFilter.includes(instance.zone); + return matchesId && matchesState && matchesZone; + }) + .sort((a, b) => { + let comparison = 0; + switch (sortField) { + case "id": + comparison = a.id.localeCompare(b.id); + break; + case "state": + comparison = a.state.localeCompare(b.state); + break; + case "address": + comparison = a.address.localeCompare(b.address); + break; + case "zone": + comparison = (a.zone || "").localeCompare(b.zone || ""); + break; + case "timestamp": + comparison = + new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(); + break; + case "tokens": + comparison = a.tokens.length - b.tokens.length; + break; + case "ownership": + comparison = parseFloat(a.ownership) - parseFloat(b.ownership); + break; + } + return sortDirection === "asc" ? comparison : -comparison; + }); + }, [ + ring?.shards, + idFilter, + stateFilter, + zoneFilter, + sortField, + sortDirection, + ]); + + if (error) { + return <BaseRing error={error} ringName={ringName} />; + } + + return ( + <div className="container space-y-6 p-6"> + <Card> + <CardHeader> + <div className="grid grid-cols-[1fr_auto] gap-8"> + <div className="space-y-6"> + <div> + <CardTitle className="text-3xl font-semibold tracking-tight"> + {AVAILABLE_RINGS.find((r) => r.id === ringName)?.title || ""}{" "} + Ring Members + </CardTitle> + <p className="text-sm text-muted-foreground mt-1"> + View and manage ring instances with their current status and + configuration + </p> + </div> + <div className="flex items-center justify-between min-h-[32px]"> + <RefreshLoop + onRefresh={fetchRing} + isPaused={selectedInstances.size > 0} + isLoading={isLoading} + /> + {selectedInstances.size > 0 && ( + <div className="flex items-center gap-4"> + <span className="text-sm text-muted-foreground"> + {selectedInstances.size} instance + {selectedInstances.size !== 1 ? "s" : ""} selected + </span> + <Button + onClick={() => setIsForgetDialogOpen(true)} + disabled={isForgetLoading} + size="sm" + variant="outline" + className={cn( + "border-red-200 bg-red-50 text-red-900 hover:bg-red-100 hover:text-red-900", + "dark:border-red-800 dark:bg-red-950 dark:text-red-200 dark:hover:bg-red-900", + "disabled:hover:bg-red-50 dark:disabled:hover:bg-red-950" + )} + > + {isForgetLoading && ( + <> + <Loader2 className="mr-2 h-4 w-4 animate-spin" /> + {forgetProgress > 0 && ( + <span className="mr-2"> + {forgetProgress}/{selectedInstances.size} + </span> + )} + </> + )} + Forget Selected + </Button> + </div> + )} + </div> + </div> + <div className="flex items-center"> + <div className="w-[250px]"> + {ring?.shards && ( + <RingStateDistributionChart instances={ring.shards} /> + )} + </div> + </div> + </div> + </CardHeader> + <CardContent className="space-y-6"> + <RingFilters + idFilter={idFilter} + onIdFilterChange={setIdFilter} + stateFilter={stateFilter} + onStateFilterChange={setStateFilter} + zoneFilter={zoneFilter} + onZoneFilterChange={setZoneFilter} + uniqueStates={uniqueStates} + uniqueZones={uniqueZones} + /> + <div className="rounded-md border bg-card"> + <RingInstanceTable + instances={sortedInstances} + selectedInstances={selectedInstances} + onSelectInstance={toggleInstance} + sortField={sortField} + sortDirection={sortDirection} + onSort={handleSort} + showTokens={isTokenBased} + /> + </div> + </CardContent> + </Card> + + <Dialog open={isForgetDialogOpen} onOpenChange={setIsForgetDialogOpen}> + <DialogContent> + <DialogHeader> + <DialogTitle>Confirm Forget Instances</DialogTitle> + <DialogDescription> + Are you sure you want to forget the following instances? This + action cannot be undone. + </DialogDescription> + </DialogHeader> + <div className="max-h-[300px] overflow-y-auto"> + <div className="space-y-2"> + {selectedInstanceDetails.map((instance) => ( + <div + key={instance.id} + className="flex items-center justify-between p-2 rounded-md bg-muted" + > + <div className="flex items-center gap-2"> + <span className="font-medium">{instance.id}</span> + <span + className={cn( + "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium", + getStateColors(instance.state) + )} + > + {instance.state} + </span> + </div> + <span className="text-sm text-muted-foreground"> + {instance.address} + </span> + </div> + ))} + </div> + </div> + <DialogFooter> + <Button + variant="outline" + onClick={() => setIsForgetDialogOpen(false)} + disabled={isForgetLoading} + > + Cancel + </Button> + <Button + variant="outline" + onClick={handleForget} + disabled={isForgetLoading} + className={cn( + "border-red-200 bg-red-50 text-red-900 hover:bg-red-100 hover:text-red-900", + "dark:border-red-800 dark:bg-red-950 dark:text-red-200 dark:hover:bg-red-900", + "disabled:hover:bg-red-50 dark:disabled:hover:bg-red-950" + )} + > + {isForgetLoading ? ( + <> + <Loader2 className="mr-2 h-4 w-4 animate-spin" /> + Forgetting... + </> + ) : ( + "Forget Instances" + )} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + </div> + ); +} diff --git a/pkg/ui/frontend/src/pages/ring.tsx b/pkg/ui/frontend/src/pages/ring.tsx new file mode 100644 index 0000000000000..d2d4074e99725 --- /dev/null +++ b/pkg/ui/frontend/src/pages/ring.tsx @@ -0,0 +1,24 @@ +import { useParams } from "react-router-dom"; +import { RingType, RingTypes } from "@/types/ring"; +import { RegularRing } from "./regular-ring"; +import PartitionRing from "./partition-ring"; +import { BaseRing } from "./base-ring"; + +export default function Ring() { + const { ringName } = useParams<{ ringName: RingType }>(); + + const isValidRing = Object.values(RingTypes).includes(ringName as RingType); + + // If no ring is selected, show the base ring component or redirect to first available ring + if (!ringName || !isValidRing) { + return <BaseRing />; + } + + // If this is a partition ring, render the partition ring component + if (ringName === RingTypes.PARTITION_INGESTER) { + return <PartitionRing />; + } + + // Otherwise, show the regular ring component + return <RegularRing ringName={ringName} />; +} diff --git a/pkg/ui/frontend/src/providers/query-provider.tsx b/pkg/ui/frontend/src/providers/query-provider.tsx new file mode 100644 index 0000000000000..58a366cf51169 --- /dev/null +++ b/pkg/ui/frontend/src/providers/query-provider.tsx @@ -0,0 +1,26 @@ +import * as React from "react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + refetchOnWindowFocus: false, + retry: false, + staleTime: 5 * 60 * 1000, // 5 minutes + }, + }, +}); + +interface QueryProviderProps { + children: React.ReactNode; +} + +export function QueryProvider({ children }: QueryProviderProps) { + return ( + <QueryClientProvider client={queryClient}> + {children} + <ReactQueryDevtools initialIsOpen={false} /> + </QueryClientProvider> + ); +} diff --git a/pkg/ui/frontend/src/types/cluster.ts b/pkg/ui/frontend/src/types/cluster.ts new file mode 100644 index 0000000000000..142e80d3dec03 --- /dev/null +++ b/pkg/ui/frontend/src/types/cluster.ts @@ -0,0 +1,50 @@ +export interface BuildInfo { + version: string; + revision: string; + branch: string; + buildUser: string; + buildDate: string; + goVersion: string; +} + +export interface ServiceState { + service: string; + status: string; +} + +export type NodeState = + | "New" + | "Starting" + | "Running" + | "Stopping" + | "Terminated" + | "Failed"; + +export const ALL_NODE_STATES: NodeState[] = [ + "New", + "Starting", + "Running", + "Stopping", + "Terminated", + "Failed", +]; + +export interface Member { + addr: string; + state: string; + isSelf: boolean; + target: string; + services: ServiceState[]; + build: BuildInfo; + error?: string; + ready?: { + isReady: boolean; + message: string; + }; +} + +export interface Cluster { + members: { [key: string]: Member }; +} + +export const ALL_VALUES_TARGET = "all-values"; diff --git a/pkg/dataobj/explorer/ui/src/types/metadata.ts b/pkg/ui/frontend/src/types/explorer.ts similarity index 76% rename from pkg/dataobj/explorer/ui/src/types/metadata.ts rename to pkg/ui/frontend/src/types/explorer.ts index fd652cb1b5e75..bee6a511ddf46 100644 --- a/pkg/dataobj/explorer/ui/src/types/metadata.ts +++ b/pkg/ui/frontend/src/types/explorer.ts @@ -1,3 +1,17 @@ +export interface ExplorerFile { + name: string; + size: number; + lastModified: string; + downloadUrl: string; +} + +export interface ExplorerData { + current: string; + parent: string | null; + files: ExplorerFile[]; + folders: string[]; +} + export interface PageInfo { compressed_size: number; uncompressed_size: number; diff --git a/pkg/ui/frontend/src/types/ring.ts b/pkg/ui/frontend/src/types/ring.ts new file mode 100644 index 0000000000000..fa8b89be97c70 --- /dev/null +++ b/pkg/ui/frontend/src/types/ring.ts @@ -0,0 +1,60 @@ +export interface RingInstance { + id: string; + state: string; + address: string; + timestamp: string; + registered_timestamp: string; + read_only: boolean; + read_only_updated_timestamp: string; + zone: string; + tokens: number[]; + ownership: string; +} + +export interface RingResponse { + shards: RingInstance[]; + now: string; +} + +export const RingTypes: Record<string, string> = { + INGESTER: "ingester", + PARTITION_INGESTER: "partition-ingester", + DISTRIBUTOR: "distributor", + PATTERN_INGESTER: "pattern-ingester", + QUERY_SCHEDULER: "query-scheduler", + COMPACTOR: "compactor", + RULER: "ruler", + INDEX_GATEWAY: "index-gateway", +} as const; + +export type RingType = keyof typeof RingTypes; + +export interface PartitionInstance { + id: number; + corrupted: boolean; + state: number; + state_timestamp: string; + owner_ids: string[]; + tokens: number[]; + owner_id?: string; + zone?: string; + uncompressedRate?: number; + compressedRate?: number; + previousUncompressedRate?: number; + previousCompressedRate?: number; +} + +export interface PartitionRingResponse { + partitions: PartitionInstance[]; + now: string; +} + +export const PartitionStates = { + 0: "Unknown", + 1: "Pending", + 2: "Active", + 3: "Inactive", + 4: "Deleted", +} as const; + +export type PartitionState = keyof typeof PartitionStates; diff --git a/pkg/ui/frontend/src/util.ts b/pkg/ui/frontend/src/util.ts new file mode 100644 index 0000000000000..c0335c77f66bd --- /dev/null +++ b/pkg/ui/frontend/src/util.ts @@ -0,0 +1,9 @@ +/** + * Extracts the basename from the current URL by matching everything up to and including /ui/ + * @returns The basename string, defaults to "/ui/" if no match is found + */ +export function getBasename(): string { + const pathname = window.location.pathname; + const match = pathname.match(/(.*\/ui\/)/); + return match?.[1] || "/ui/"; +} diff --git a/pkg/ui/frontend/src/vite-env.d.ts b/pkg/ui/frontend/src/vite-env.d.ts new file mode 100644 index 0000000000000..11f02fe2a0061 --- /dev/null +++ b/pkg/ui/frontend/src/vite-env.d.ts @@ -0,0 +1 @@ +/// <reference types="vite/client" /> diff --git a/pkg/ui/frontend/tailwind.config.js b/pkg/ui/frontend/tailwind.config.js new file mode 100644 index 0000000000000..dfa7001df8dec --- /dev/null +++ b/pkg/ui/frontend/tailwind.config.js @@ -0,0 +1,96 @@ +/** @type {import('tailwindcss').Config} */ +export default { + darkMode: ["class"], + content: ["./src/**/*.{js,jsx,ts,tsx}"], + theme: { + container: { + center: true, + padding: '2rem', + screens: { + '2xl': '1400px' + } + }, + extend: { + keyframes: { + 'accordion-down': { + from: { + height: 0 + }, + to: { + height: 'var(--radix-accordion-content-height)' + } + }, + 'accordion-up': { + from: { + height: 'var(--radix-accordion-content-height)' + }, + to: { + height: 0 + } + } + }, + animation: { + 'accordion-down': 'accordion-down 0.2s ease-out', + 'accordion-up': 'accordion-up 0.2s ease-out' + }, + borderRadius: { + lg: 'var(--radius)', + md: 'calc(var(--radius) - 2px)', + sm: 'calc(var(--radius) - 4px)' + }, + colors: { + border: 'hsl(var(--border))', + input: 'hsl(var(--input))', + ring: 'hsl(var(--ring))', + background: 'hsl(var(--background))', + foreground: 'hsl(var(--foreground))', + primary: { + DEFAULT: 'hsl(var(--primary))', + foreground: 'hsl(var(--primary-foreground))' + }, + secondary: { + DEFAULT: 'hsl(var(--secondary))', + foreground: 'hsl(var(--secondary-foreground))' + }, + destructive: { + DEFAULT: 'hsl(var(--destructive))', + foreground: 'hsl(var(--destructive-foreground))' + }, + muted: { + DEFAULT: 'hsl(var(--muted))', + foreground: 'hsl(var(--muted-foreground))' + }, + accent: { + DEFAULT: 'hsl(var(--accent))', + foreground: 'hsl(var(--accent-foreground))' + }, + popover: { + DEFAULT: 'hsl(var(--popover))', + foreground: 'hsl(var(--popover-foreground))' + }, + card: { + DEFAULT: 'hsl(var(--card))', + foreground: 'hsl(var(--card-foreground))' + }, + chart: { + '1': 'hsl(var(--chart-1))', + '2': 'hsl(var(--chart-2))', + '3': 'hsl(var(--chart-3))', + '4': 'hsl(var(--chart-4))', + '5': 'hsl(var(--chart-5))' + }, + sidebar: { + DEFAULT: 'hsl(var(--sidebar-background))', + foreground: 'hsl(var(--sidebar-foreground))', + primary: 'hsl(var(--sidebar-primary))', + 'primary-foreground': 'hsl(var(--sidebar-primary-foreground))', + accent: 'hsl(var(--sidebar-accent))', + 'accent-foreground': 'hsl(var(--sidebar-accent-foreground))', + border: 'hsl(var(--sidebar-border))', + ring: 'hsl(var(--sidebar-ring))' + } + } + } + }, + plugins: [require("tailwindcss-animate")], +}; diff --git a/pkg/ui/frontend/tsconfig.json b/pkg/ui/frontend/tsconfig.json new file mode 100644 index 0000000000000..a4493c742bc25 --- /dev/null +++ b/pkg/ui/frontend/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["src"], + "references": [{ "path": "./tsconfig.node.json" }] + } diff --git a/pkg/ui/frontend/tsconfig.node.json b/pkg/ui/frontend/tsconfig.node.json new file mode 100644 index 0000000000000..0ad00838a17f8 --- /dev/null +++ b/pkg/ui/frontend/tsconfig.node.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "baseUrl": ".", + "paths": { + "@/*": [ + "./src/*" + ] + } + }, + "include": [ + "vite.config.ts" + ] +} diff --git a/pkg/ui/frontend/vite.config.ts b/pkg/ui/frontend/vite.config.ts new file mode 100644 index 0000000000000..a7d55f6f64ab7 --- /dev/null +++ b/pkg/ui/frontend/vite.config.ts @@ -0,0 +1,83 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; +import path from "path"; + +export default defineConfig({ + plugins: [react()], + base: "/ui/", + css: { + postcss: "./postcss.config.js", + }, + build: { + outDir: "dist", + emptyOutDir: true, + cssCodeSplit: false, + rollupOptions: { + output: { + manualChunks: { + // Core React libraries + "react-core": ["react", "react-dom"], + + // Routing related + "react-router": ["react-router-dom", "use-react-router-breadcrumbs"], + + // Form and validation libraries + "form-libs": ["react-hook-form", "@hookform/resolvers", "zod"], + + // Radix UI components - split into smaller chunks + "radix-core": [ + "@radix-ui/react-slot", + "@radix-ui/react-label", + "@radix-ui/react-tooltip", + "@radix-ui/react-popover", + ], + "radix-navigation": [ + "@radix-ui/react-dropdown-menu", + "@radix-ui/react-tabs", + "@radix-ui/react-scroll-area", + ], + "radix-inputs": [ + "@radix-ui/react-checkbox", + "@radix-ui/react-switch", + "@radix-ui/react-select", + "@radix-ui/react-toggle", + "@radix-ui/react-toggle-group", + ], + "radix-layout": [ + "@radix-ui/react-dialog", + "@radix-ui/react-collapsible", + "@radix-ui/react-separator", + "@radix-ui/react-hover-card", + ], + + // Data visualization and charts + "data-viz": ["recharts"], + + // Date handling + "date-utils": ["date-fns", "react-datepicker"], + + // Icons and UI utilities + "ui-icons": ["lucide-react", "react-icons"], + "ui-utils": ["class-variance-authority", "clsx", "tailwind-merge"], + + // Theme and styling + "theme-utils": ["next-themes", "tailwindcss-animate"], + + // Query management + "query-management": ["@tanstack/react-query"], + }, + }, + }, + }, + resolve: { + alias: { + "@": path.resolve(__dirname, "./src"), + }, + }, + server: { + proxy: { + "/ui/api/": "http://localhost:3100", + "/loki/api/": "http://localhost:3100", + }, + }, +}); diff --git a/pkg/ui/handler.go b/pkg/ui/handler.go new file mode 100644 index 0000000000000..f2c47d74f56cb --- /dev/null +++ b/pkg/ui/handler.go @@ -0,0 +1,179 @@ +// Package ui provides HTTP handlers for the Loki UI and cluster management interface. +package ui + +import ( + "embed" + "encoding/json" + "fmt" + "io/fs" + "net/http" + "net/http/httputil" + "strings" + + "github.com/go-kit/log/level" + "github.com/gorilla/mux" + + "github.com/grafana/loki/v3/pkg/analytics" +) + +const ( + proxyScheme = "http" + prefixPath = "/ui" + proxyPath = prefixPath + "/api/v1/proxy/{nodename}/" + clusterPath = prefixPath + "/api/v1/cluster/nodes" + clusterSelfPath = prefixPath + "/api/v1/cluster/nodes/self/details" + analyticsPath = prefixPath + "/api/v1/analytics" + notFoundPath = prefixPath + "/api/v1/404" + contentTypeJSON = "application/json" +) + +//go:embed frontend/dist +var uiFS embed.FS + +// RegisterHandler registers all UI API routes with the provided router. +func (s *Service) RegisterHandler() { + // Register the node handler + route, handler := s.node.Handler() + s.router.PathPrefix(route).Handler(handler) + + s.router.Path(analyticsPath).Handler(analytics.Handler()) + s.router.Path(clusterPath).Handler(s.clusterMembersHandler()) + s.router.Path(clusterSelfPath).Handler(s.clusterSelfHandler()) + + s.router.PathPrefix(proxyPath).Handler(s.clusterProxyHandler()) + s.router.PathPrefix(notFoundPath).Handler(s.notFoundHandler()) + + fsHandler := http.FileServer(http.FS(s.uiFS)) + s.router.PathPrefix(prefixPath + "/").Handler(http.StripPrefix(prefixPath+"/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/") + // Don't redirect for root UI path + if path == "" || path == "/" || path == "404" { + r.URL.Path = "/" + fsHandler.ServeHTTP(w, r) + return + } + if _, err := s.uiFS.Open(path); err != nil { + r.URL.Path = "/" + fsHandler.ServeHTTP(w, r) + return + } + fsHandler.ServeHTTP(w, r) + }))) + s.router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/ui/404?path="+r.URL.Path, http.StatusTemporaryRedirect) + }) +} + +func (s *Service) initUIFs() error { + var err error + s.uiFS, err = fs.Sub(uiFS, "frontend/dist") + if err != nil { + return err + } + return nil +} + +// clusterProxyHandler returns a handler that proxies requests to the target node. +func (s *Service) clusterProxyHandler() http.Handler { + proxy := &httputil.ReverseProxy{ + Transport: s.client.Transport, + Director: func(r *http.Request) { + r.URL.Scheme = proxyScheme + vars := mux.Vars(r) + nodeName := vars["nodename"] + if nodeName == "" { + level.Error(s.logger).Log("msg", "node name not found in URL") + s.redirectToNotFound(r, nodeName) + return + } + + peer, err := s.findPeerByName(nodeName) + if err != nil { + level.Warn(s.logger).Log("msg", "node not found in cluster state", "node", nodeName, "err", err) + s.redirectToNotFound(r, nodeName) + return + } + + // Calculate the path without the proxy prefix + trimPrefix := fmt.Sprintf("/ui/api/v1/proxy/%s", nodeName) + newPath := strings.TrimPrefix(r.URL.Path, trimPrefix) + if newPath == "" { + newPath = "/" + } + + // Rewrite the URL to forward to the target node + r.URL.Host = peer.Addr + r.URL.Path = newPath + r.RequestURI = "" // Must be cleared according to Go docs + + level.Debug(s.logger).Log( + "msg", "proxying request", + "node", nodeName, + "target", r.URL.String(), + "original_path", r.URL.Path, + ) + }, + ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { + level.Error(s.logger).Log("msg", "proxy error", "err", err, "path", r.URL.Path) + s.writeJSONError(w, http.StatusBadGateway, err.Error()) + }, + } + return proxy +} + +func (s *Service) clusterMembersHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + state, err := s.fetchClusterMembers(r.Context()) + if err != nil { + level.Error(s.logger).Log("msg", "failed to fetch cluster state", "err", err) + s.writeJSONError(w, http.StatusInternalServerError, "failed to fetch cluster state") + return + } + w.Header().Set("Content-Type", contentTypeJSON) + if err := json.NewEncoder(w).Encode(state); err != nil { + level.Error(s.logger).Log("msg", "failed to encode cluster state", "err", err) + s.writeJSONError(w, http.StatusInternalServerError, "failed to encode response") + return + } + }) +} + +func (s *Service) clusterSelfHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + state, err := s.fetchSelfDetails(r.Context()) + if err != nil { + level.Error(s.logger).Log("msg", "failed to fetch node details", "err", err) + s.writeJSONError(w, http.StatusInternalServerError, "failed to fetch node details") + return + } + w.Header().Set("Content-Type", contentTypeJSON) + if err := json.NewEncoder(w).Encode(state); err != nil { + level.Error(s.logger).Log("msg", "failed to encode node details", "err", err) + s.writeJSONError(w, http.StatusInternalServerError, "failed to encode response") + return + } + }) +} + +func (s *Service) notFoundHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + node := r.URL.Query().Get("node") + s.writeJSONError(w, http.StatusNotFound, fmt.Sprintf("node %s not found", node)) + }) +} + +// redirectToNotFound updates the request URL to redirect to the not found handler +func (s *Service) redirectToNotFound(r *http.Request, nodeName string) { + r.URL.Path = notFoundPath + r.URL.RawQuery = "?node=" + nodeName +} + +// writeJSONError writes a JSON error response with the given status code and message +func (s *Service) writeJSONError(w http.ResponseWriter, code int, message string) { + w.Header().Set("Content-Type", contentTypeJSON) + w.WriteHeader(code) + if err := json.NewEncoder(w).Encode(map[string]string{"error": message}); err != nil { + level.Error(s.logger).Log("msg", "failed to encode error response", "err", err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} diff --git a/pkg/ui/service.go b/pkg/ui/service.go new file mode 100644 index 0000000000000..6cf4e11a04168 --- /dev/null +++ b/pkg/ui/service.go @@ -0,0 +1,174 @@ +package ui + +import ( + "context" + "crypto/tls" + "fmt" + "io/fs" + "net" + "net/http" + "strings" + "sync" + "time" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/gorilla/mux" + "github.com/grafana/ckit" + "github.com/grafana/ckit/peer" + "github.com/grafana/dskit/ring" + "github.com/grafana/dskit/services" + "golang.org/x/net/http2" + + util_log "github.com/grafana/loki/v3/pkg/util/log" +) + +// This allows to rate limit the number of updates when the cluster is frequently changing (e.g. during rollout). +const stateUpdateMinInterval = 5 * time.Second + +type Service struct { + services.Service + node *ckit.Node + router *mux.Router + uiFS fs.FS + + client *http.Client + localAddr string + + cfg Config + logger log.Logger +} + +func NewService(cfg Config, router *mux.Router, logger log.Logger) (*Service, error) { + addr, err := ring.GetInstanceAddr(cfg.AdvertiseAddr, cfg.InfNames, util_log.Logger, cfg.EnableIPv6) + if err != nil { + return nil, err + } + cfg.AdvertiseAddr = addr + + httpClient := &http.Client{ + Transport: &http2.Transport{ + AllowHTTP: true, + DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) { + return net.DialTimeout(network, addr, calcTimeout(ctx)) + }, + }, + } + advertiseAddr := fmt.Sprintf("%s:%d", cfg.AdvertiseAddr, cfg.AdvertisePort) + node, err := ckit.NewNode(httpClient, ckit.Config{ + Name: cfg.NodeName, + Log: logger, + AdvertiseAddr: advertiseAddr, + Label: cfg.ClusterName, + }) + if err != nil { + return nil, err + } + + svc := &Service{ + cfg: cfg, + logger: logger, + node: node, + router: router, + client: httpClient, + localAddr: advertiseAddr, + } + svc.Service = services.NewBasicService(nil, svc.run, svc.stop) + if err := svc.initUIFs(); err != nil { + return nil, err + } + svc.RegisterHandler() + return svc, nil +} + +func (s *Service) run(ctx context.Context) error { + if err := s.node.ChangeState(ctx, peer.StateParticipant); err != nil { + level.Error(s.logger).Log("msg", "failed to change state to participant", "err", err) + return err + } + peers, err := s.getBootstrapPeers() + if err != nil { + // Warn when failed to get peers on startup as it can result in a split brain. We do not fail hard here + // because it would complicate the process of bootstrapping a new cluster. + level.Warn(s.logger).Log("msg", "failed to get peers to join at startup; will create a new cluster", "err", err) + } + level.Info(s.logger).Log("msg", "starting cluster node", "peers_count", len(peers)) + if err := s.node.Start(peers); err != nil { + level.Warn(s.logger).Log("msg", "failed to connect to peers; bootstrapping a new cluster", "err", err) + + err := s.node.Start(nil) + if err != nil { + level.Error(s.logger).Log("msg", "failed to bootstrap a fresh cluster with no peers", "err", err) + } + } + + var wg sync.WaitGroup + if s.cfg.RejoinInterval > 0 { + ticker := time.NewTicker(s.cfg.RejoinInterval) + defer ticker.Stop() + + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + peers, err := s.getBootstrapPeers() + if err != nil { + level.Warn(s.logger).Log("msg", "failed to get peers to join; will try again", "err", err) + continue + } + level.Info(s.logger).Log("msg", "rejoining cluster", "peers_count", len(peers)) + if err := s.node.Start(peers); err != nil { + level.Warn(s.logger).Log("msg", "failed to connect to peers; will try again", "err", err) + continue + } + } + } + }() + } + + <-ctx.Done() + wg.Wait() + return nil +} + +func (s *Service) stop(_ error) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := s.node.ChangeState(ctx, peer.StateTerminating); err != nil { + level.Error(s.logger).Log("msg", "failed to change state to terminating", "err", err) + } + return s.node.Stop() +} + +// findPeerByName returns the peer with the given name visible to the node. +func (s *Service) findPeerByName(name string) (peer.Peer, error) { + for _, p := range s.node.Peers() { + if strings.EqualFold(p.Name, name) { + return p, nil + } + } + return peer.Peer{}, fmt.Errorf("peer not found: %s", name) +} + +// TODO(rfratto): consider making the max timeout configurable. +// Set a maximum timeout for establishing the connection. If our +// context has a deadline earlier than our timeout, we shrink the +// timeout to it. +func calcTimeout(ctx context.Context) time.Duration { + timeout := 30 * time.Second + if dur, ok := deadlineDuration(ctx); ok && dur < timeout { + timeout = dur + } + return timeout +} + +func deadlineDuration(ctx context.Context) (d time.Duration, ok bool) { + if t, ok := ctx.Deadline(); ok { + return time.Until(t), true + } + return 0, false +} diff --git a/tools/dev/kafka/loki-local-config.debug.yaml b/tools/dev/kafka/loki-local-config.debug.yaml index 59394cd7b628e..7a30216a36586 100644 --- a/tools/dev/kafka/loki-local-config.debug.yaml +++ b/tools/dev/kafka/loki-local-config.debug.yaml @@ -15,7 +15,6 @@ common: rules_directory: /tmp/loki/rules replication_factor: 1 ring: - instance_id: local kvstore: store: inmemory @@ -58,6 +57,10 @@ pattern_ingester: metric_aggregation: loki_address: localhost:3100 +compactor: + retention_enabled: true + delete_request_store: filesystem + ruler: alertmanager_url: http://localhost:9093 diff --git a/vendor/github.com/grafana/ckit/.gitignore b/vendor/github.com/grafana/ckit/.gitignore new file mode 100644 index 0000000000000..fdc225da666a3 --- /dev/null +++ b/vendor/github.com/grafana/ckit/.gitignore @@ -0,0 +1,4 @@ +.idea/ +.vscode/ +.DS_Store +vendor/ diff --git a/vendor/github.com/grafana/ckit/.golangci.yml b/vendor/github.com/grafana/ckit/.golangci.yml new file mode 100644 index 0000000000000..855e709cc750d --- /dev/null +++ b/vendor/github.com/grafana/ckit/.golangci.yml @@ -0,0 +1,70 @@ +# Full list of configuration options: https://golangci-lint.run/usage/configuration/ + +run: + timeout: 10m + +output: + sort-results: true + +linters: + enable: + - errcheck # Report unchecked errors + - goconst # Find repeated strings that could be replaced by constant + - gofmt # Check whether code was gofmt-ed + - goimports # Check imports were formatted with gofmt + - revive # Broad set of rules; replaces deprecated golint + - gosimple # Check whether code can be simplified + - ineffassign # Detect when assignment to variable is never used + - misspell # Report on commonly misspelled English words + - unconvert # Remove unnecessary type conversions + - unparam # Detect unused function parameters + - govet # `go vet` + - unused # Detect unused constants/variables/functions/types + - typecheck # Ensure code typechecks + - makezero # Detect misuse of make with non-zero length and append + - tenv # Use testing.(*T).Setenv instead of os.Setenv + - whitespace # Report unnecessary blank lines + +issues: + # We want to use our own exclusion rules and ignore all the defaults. + exclude-use-default: false + + exclude-rules: + # It's fine if tests ignore errors. + - path: _test.go + linters: + - errcheck + + exclude: + # Ignoring errors on Close, Log, and removing files is OK in most cases. + - "Error return value of `(.*\\.Close|.*\\.Log|os.Remove)` is not checked" + +# Linter settings options: https://golangci-lint.run/usage/linters/ +linters-settings: + whitespace: + # While there normally shouldn't be extra redundant leading/trailing + # whitespace, if statement conditions and function headers that cross + # multiple lines are an exception. + # + # if true || + # false { + # + # // ... ^ must have empty line above + # } + # + # func foo( + # a int, + # ) { + # + # // ... ^ must have empty line above + # } + # + # This helps readers easily separate where the multi-line if/function ends + # at a glance. + multi-if: true + multi-func: true + + revive: + rules: + - name: package-comments + disabled: true diff --git a/vendor/github.com/grafana/ckit/CODEOWNERS b/vendor/github.com/grafana/ckit/CODEOWNERS new file mode 100644 index 0000000000000..2bdb5b2c682b7 --- /dev/null +++ b/vendor/github.com/grafana/ckit/CODEOWNERS @@ -0,0 +1 @@ +* @rfratto @tpaschalis diff --git a/vendor/github.com/grafana/ckit/LICENSE b/vendor/github.com/grafana/ckit/LICENSE new file mode 100644 index 0000000000000..261eeb9e9f8b2 --- /dev/null +++ b/vendor/github.com/grafana/ckit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/grafana/ckit/Makefile b/vendor/github.com/grafana/ckit/Makefile new file mode 100644 index 0000000000000..cab9e8d420bc4 --- /dev/null +++ b/vendor/github.com/grafana/ckit/Makefile @@ -0,0 +1,6 @@ +test: + go test -v ./... + +lint: + golangci-lint run -v + diff --git a/vendor/github.com/grafana/ckit/README.md b/vendor/github.com/grafana/ckit/README.md new file mode 100644 index 0000000000000..347f3a6c346a2 --- /dev/null +++ b/vendor/github.com/grafana/ckit/README.md @@ -0,0 +1,66 @@ +# ckit + +[![Go Reference](https://pkg.go.dev/badge/github.com/grafana/ckit.svg)](https://pkg.go.dev/github.com/grafana/ckit) + +ckit (clustering toolkit) is a lightweight package for creating clusters that +use [consistent hashing][] for workload distribution. + +ckit works by gossiping member state over HTTP/2, and locally generating +hashing algorithms based on the state of nodes in the cluster. Because gossip +is used, the hashing algorithms are eventually consistent as cluster state +takes time to converge. + +> **NOTE**: ckit is still in development; breaking changes to the API may +> happen. + +[consistent hashing]: https://en.wikipedia.org/wiki/Consistent_hashing + +## Features + +* Low-overhead: on a 151 node cluster, ckit uses ~20MB of memory and ~50Bps of + network traffic per node. + +* HTTP/2 transport: nodes communicate over plain HTTP/2 without needing to open + up extra ports. + +## Packages + +ckit has two main packages: + +* The top-level package handles establishing a cluster. +* The `shard` package handles creating consistent hashing algorithms based on + cluster state. + +There are also some utility packages: + +* The `advertise` package contains utilities for a node to determine what IP + address to advertise to its peers. +* The `memconn` package contains utilities for a node to create an in-memory + connection to itself without using the network. + +## Comparison to grafana/dskit + +[grafana/dskit][dskit] is a mature library with utilities for building +distributed systems in general. Its clustering mechanism works by gossiping a +32-bit hash ring over the network. In comparison, ckit locally computes 64-bit +hash rings. + +dskit was built for Grafana Labs' time-series databases, while ckit was +initially built for Grafana Agent, with the intent of building something with +less operational overhead. + +Compared to ckit, the dskit library: + +* Is more mature, and is used at scale with Grafana Mimir, Grafana Loki, and + Grafana Tempo. + +* Gossips hash rings over the network, leading to more complexity and more + network overhead. + +* Uses a 32-bit hash ring for distributing work; ckit has multiple 64-bit + hashing algorithms to choose from. + +* Requires a separate listener for gossip traffic; ckit allows reusing your + existing HTTP/2-capable server. + +[dskit]: https://github.com/grafana/dskit diff --git a/vendor/github.com/grafana/ckit/ckit.go b/vendor/github.com/grafana/ckit/ckit.go new file mode 100644 index 0000000000000..304a44b39afbe --- /dev/null +++ b/vendor/github.com/grafana/ckit/ckit.go @@ -0,0 +1,8 @@ +// Package ckit is a cluster toolkit for creating distributed systems. Nodes +// use gossip over HTTP/2 to maintain a list of all Nodes registered in the +// cluster. +// +// Nodes can optionally synchronize their state with a Sharder, which is used +// to perform consistent hashing and shard ownership of keys across the +// cluster. +package ckit diff --git a/vendor/github.com/grafana/ckit/internal/chash/chash.go b/vendor/github.com/grafana/ckit/internal/chash/chash.go new file mode 100644 index 0000000000000..c8f59c382ff6b --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/chash/chash.go @@ -0,0 +1,14 @@ +// Package chash implements an set of low-level consistent hashing algorithms. +// A higher level API is exposed by the shard package. +package chash + +// Hash is a consistent hashing algorithm. Implementations of Hash are +// goroutine safe. +type Hash interface { + // Get will retrieve the n owners for key. Get will return an error if there + // are not at least n nodes. + Get(key uint64, n int) ([]string, error) + + // SetNodes updates the set of nodes used for hashing. + SetNodes(nodes []string) +} diff --git a/vendor/github.com/grafana/ckit/internal/chash/multiprobe.go b/vendor/github.com/grafana/ckit/internal/chash/multiprobe.go new file mode 100644 index 0000000000000..b1cfbd0cc8ce4 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/chash/multiprobe.go @@ -0,0 +1,136 @@ +package chash + +import ( + "fmt" + "math" + "sort" + "strconv" + "sync" + + "github.com/cespare/xxhash/v2" +) + +// Multiprobe implements a multi-probe hash: https://arxiv.org/abs/1505.00062 +// Multiprobe is optimized for a median peak-to-average load ratio of 1.05. +// It performs a lookup in O(K * log N) time, where K is 21. +func Multiprobe() Hash { + return &multiprobe{} +} + +type multiprobe struct { + mut sync.RWMutex + tokens []ringToken +} + +func (mp *multiprobe) Get(key uint64, n int) ([]string, error) { + mp.mut.RLock() + defer mp.mut.RUnlock() + + if n > len(mp.tokens) { + return nil, fmt.Errorf("not enough nodes: need at least %d, have %d", n, len(mp.tokens)) + } else if n == 0 { + return []string{}, nil + } + + var ( + h1 = secondKey(key) + h2 = secondKey(h1) + + K = 21 + ) + + var ( + closestIdx int // closest node + closestDist uint64 = math.MaxUint64 + ) + + // TODO(rfratto): this is a little slow. Instead of iterating over the full + // set of tokens, we could partition tokens by bit prefix and iterate over + // the partition instead. This may help speed up lookups at lower numbers of + // nodes. + // + // If the bit prefix was the high 4 bits, that would result in 16 buckets. + // With 100 nodes, that would roughly be 7 nodes per bucket, moving the + // lookup time to O(21 * log(100)) to O(21 * log(7)) (roughly 139 to 59, + // a 57% improvement). + for k := 0; k < K; k++ { + h := h1 + uint64(k)*h2 + + idx := findClosest(mp.tokens, h) + tok := mp.tokens[idx] + + dist := distance(tok.token, h) + if dist < closestDist { + closestIdx = idx + closestDist = dist + } + } + + var ( + res = make([]string, n) + ) + for i := 0; i < n; i++ { + // NOTE(rfratto): Only closestIdx is guaranteed to be the closest + // token in terms of distance. We don't account for distance when + // searching for the other nodes for replication. In practice this + // shouldn't harm distribution much. + res[i] = mp.tokens[wrapIndex(closestIdx+i, len(mp.tokens))].node + } + return res, nil +} + +func secondKey(key1 uint64) uint64 { + dig := xxhash.New() + _, _ = dig.Write(strconv.AppendUint(nil, key1, 16)) + return dig.Sum64() +} + +// findClosest returns the index of the tok whose distance to "to" is the +// smallest. +func findClosest(tok []ringToken, to uint64) int { + found := sort.Search(len(tok), func(i int) bool { + return tok[i].token >= to + }) + + var ( + idxA = wrapIndex(found-1, len(tok)) + idxB = wrapIndex(found+0, len(tok)) + + distA = distance(tok[idxA].token, to) + distB = distance(tok[idxB].token, to) + ) + + if distA <= distB { + return idxA + } + return idxB +} + +func wrapIndex(i int, len int) int { + if i < 0 { + return len - 1 + } + return i % len +} + +func distance(a, b uint64) uint64 { + if a < b { + return b - a + } + return a - b +} + +func (mp *multiprobe) SetNodes(nodes []string) { + newTokens := make([]ringToken, len(nodes)) + for i, n := range nodes { + newTokens[i] = ringToken{ + node: n, + token: xxhash.Sum64String(n), + } + } + sort.Sort(byRingToken(newTokens)) + + mp.mut.Lock() + defer mp.mut.Unlock() + mp.tokens = newTokens +} diff --git a/vendor/github.com/grafana/ckit/internal/chash/rendezvous.go b/vendor/github.com/grafana/ckit/internal/chash/rendezvous.go new file mode 100644 index 0000000000000..366f8a498632e --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/chash/rendezvous.go @@ -0,0 +1,78 @@ +package chash + +import ( + "fmt" + "sort" + "sync" + + "github.com/cespare/xxhash/v2" +) + +// Rendezvous returns a rendezvous hashing algorithm (HRW, Highest Random +// Weight). Rendezvous is optimized for excellent load distribution, but +// has a runtime complexity of O(N). +func Rendezvous() Hash { + return &rendezvous{} +} + +type rendezvous struct { + mut sync.RWMutex + hashes map[string]uint64 + nodes []string +} + +func (r *rendezvous) Get(key uint64, n int) ([]string, error) { + r.mut.RLock() + defer r.mut.RUnlock() + + if n > len(r.nodes) { + return nil, fmt.Errorf("not enough nodes: need at least %d, have %d", n, len(r.nodes)) + } else if n == 0 { + return []string{}, nil + } + + var ( + res = make([]string, n) + hashes = make([]ringToken, len(r.nodes)) + ) + + // Get the hash for all nodes, sort them, and then got the lowest three. This + // uses more memory but runs in O(N) time instead of O(N * log n). + for i, node := range r.nodes { + hashes[i] = ringToken{ + node: node, + token: xorshiftMult64(key ^ r.hashes[node]), + } + } + sort.Sort(byRingToken(hashes)) + + for i := 0; i < n; i++ { + res[i] = hashes[i].node + } + return res, nil +} + +func (r *rendezvous) SetNodes(nodes []string) { + var ( + newHashes = make(map[string]uint64, len(nodes)) + newNodes = make([]string, len(nodes)) + ) + for i, n := range nodes { + newHashes[n] = xxhash.Sum64String(n) + newNodes[i] = n + } + sort.Strings(newNodes) + + r.mut.Lock() + defer r.mut.Unlock() + r.hashes = newHashes + r.nodes = newNodes +} + +// https://vigna.di.unimi.it/ftp/papers/xorshift.pdf +func xorshiftMult64(x uint64) uint64 { + x ^= x >> 12 // a + x ^= x << 25 // b + x ^= x >> 27 // c + return x * 2685821657736338717 +} diff --git a/vendor/github.com/grafana/ckit/internal/chash/ring.go b/vendor/github.com/grafana/ckit/internal/chash/ring.go new file mode 100644 index 0000000000000..f229df8fb6470 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/chash/ring.go @@ -0,0 +1,124 @@ +package chash + +import ( + "fmt" + "sort" + "sync" + "unsafe" + + "github.com/cespare/xxhash/v2" +) + +// Ring implements a ring consistent hash. numTokens determines how many tokens +// each node should have. Tokens are mapped to the unit circle, and then +// ownership of a key is determined by finding the next token on the unit +// circle. If two nodes have the same token, the node that lexicographically +// comes first will be used as the first owner. +// +// Ring hash is extremely fast, running in O(log N) time, but increases in +// memory usage as numTokens increases. Low values of numTokens will cause poor +// distribution; 256 or 512 is a good starting point. +func Ring(numTokens int) Hash { + return &ringHash{numTokens: numTokens} +} + +type ringHash struct { + mut sync.RWMutex + numTokens int + + // Tokens for all nodes. Must be sorted at all times. + numNodes int + tokens []ringToken +} + +type ringToken struct { + node string + token uint64 +} + +func (r *ringHash) Get(key uint64, n int) ([]string, error) { + r.mut.RLock() + defer r.mut.RUnlock() + + if n > r.numNodes { + return nil, fmt.Errorf("not enough nodes: need at least %d, have %d", n, r.numNodes) + } else if n == 0 { + return []string{}, nil + } + + idx := sort.Search(len(r.tokens), func(i int) bool { + return r.tokens[i].token >= key + }) + if idx == len(r.tokens) { + // Wrap around if we hit the end of the list. + idx = 0 + } + + var ( + res = make([]string, 0, n) + cache = make(map[string]struct{}) + ) + + for { + owner := r.tokens[idx].node + if _, found := cache[owner]; !found { + res = append(res, owner) + cache[owner] = struct{}{} + } + + // Increment idx with wraparound. + idx = (idx + 1) % len(r.tokens) + + if len(res) == n { + break + } + } + + return res, nil +} + +func (r *ringHash) SetNodes(nodes []string) { + toks := make([]ringToken, 0, len(nodes)*r.numTokens) + for _, node := range nodes { + dig := xxhash.New() + _, _ = dig.Write(unsafeSlice(node)) + + // We'll continually append extra data to kb to generate all the tokens for + // our node. This data doesn't have to be singificant, so we'll use the + // token number truncated to a byte. + tokData := []byte{0} + + for t := 0; t < r.numTokens; t++ { + tokData[0] = byte(t) + _, _ = dig.Write(tokData) + + toks = append(toks, ringToken{ + node: node, + token: dig.Sum64(), + }) + } + } + sort.Sort(byRingToken(toks)) + + r.mut.Lock() + defer r.mut.Unlock() + r.numNodes = len(nodes) + r.tokens = toks +} + +// unsafeSlice returns s as a byte slice without making a copy. +func unsafeSlice(s string) []byte { + return *((*[]byte)(unsafe.Pointer(&s))) +} + +type byRingToken []ringToken + +func (b byRingToken) Len() int { return len(b) } +func (b byRingToken) Swap(i, j int) { b[i], b[j] = b[j], b[i] } + +func (b byRingToken) Less(i, j int) bool { + if b[i].token == b[j].token { + return b[i].node < b[j].node + } + return b[i].token < b[j].token +} diff --git a/vendor/github.com/grafana/ckit/internal/gossiphttp/message.go b/vendor/github.com/grafana/ckit/internal/gossiphttp/message.go new file mode 100644 index 0000000000000..d0c02f5cbe024 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/gossiphttp/message.go @@ -0,0 +1,71 @@ +package gossiphttp + +import ( + "encoding/binary" + "fmt" + "io" + "math" + "sync" +) + +const ( + // magic is the first byte sent with every message. + magic = 0xcc + headerSize = 3 +) + +var headerPool = &sync.Pool{ + New: func() any { + return &header{ + data: make([]byte, headerSize), + } + }, +} + +type header struct { + data []byte +} + +// readMessage reads a message from an [io.Reader]. +func readMessage(r io.Reader) ([]byte, error) { + header := headerPool.Get().(*header) + defer headerPool.Put(header) + if _, err := io.ReadFull(r, header.data); err != nil { + return nil, err + } + + var ( + gotMagic = header.data[0] + dataLength = binary.BigEndian.Uint16(header.data[1:]) + ) + + if gotMagic != magic { + return nil, fmt.Errorf("invalid magic (%x)", gotMagic) + } + + data := make([]byte, dataLength) + if _, err := io.ReadFull(r, data); err != nil { + return nil, err + } + return data, nil +} + +// writeMessage writes a message to an [io.Writer]. +func writeMessage(w io.Writer, message []byte) error { + header := headerPool.Get().(*header) + defer headerPool.Put(header) + + if len(message) > math.MaxUint16 { + return fmt.Errorf("message length %d exceeds size limit %d", len(message), math.MaxUint16) + } + + header.data[0] = magic + binary.BigEndian.PutUint16(header.data[1:], uint16(len(message))) + + if _, err := w.Write(header.data); err != nil { + return err + } + + _, err := w.Write(message) + return err +} diff --git a/vendor/github.com/grafana/ckit/internal/gossiphttp/metrics.go b/vendor/github.com/grafana/ckit/internal/gossiphttp/metrics.go new file mode 100644 index 0000000000000..f0c86edbaf078 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/gossiphttp/metrics.go @@ -0,0 +1,94 @@ +package gossiphttp + +import ( + "github.com/grafana/ckit/internal/metricsutil" + "github.com/prometheus/client_golang/prometheus" +) + +type metrics struct { + metricsutil.Container + + packetRxTotal prometheus.Counter + packetRxBytesTotal prometheus.Counter + packetTxTotal prometheus.Counter + packetTxBytesTotal prometheus.Counter + packetTxFailedTotal prometheus.Counter + + openStreams prometheus.Gauge + streamRxTotal prometheus.Counter + streamRxBytesTotal prometheus.Counter + streamRxFailedTotal prometheus.Counter + streamTxTotal prometheus.Counter + streamTxBytesTotal prometheus.Counter + streamTxFailedTotal prometheus.Counter +} + +func newMetrics() *metrics { + var m metrics + + m.packetRxTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "cluster_transport_rx_packets_total", + Help: "Total number of HTTP/2 gossip transport packets read", + }) + m.packetRxBytesTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "cluster_transport_rx_bytes_total", + Help: "Total number of HTTP/2 gossip transport bytes read", + }) + m.packetTxTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "cluster_transport_tx_packets_total", + Help: "Total number of HTTP/2 gossip transport packets written (failed or otherwise)", + }) + m.packetTxBytesTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "cluster_transport_tx_bytes_total", + Help: "Total number of HTTP/2 gossip transport bytes written (failed or otherwise)", + }) + m.packetTxFailedTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_tx_packets_failed_total", + Help: "Total number of failed HTTP/2 gossip transport packets", + }) + + m.openStreams = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_streams", + Help: "Current number of HTTP/2 transport data streams", + }) + m.streamRxTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_rx_packets_total", + Help: "Total number of HTTP/2 gossip transport stream packets read", + }) + m.streamRxBytesTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_rx_bytes_total", + Help: "Total number of HTTP/2 gossip transport stream bytes read", + }) + m.streamRxFailedTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_rx_packets_failed_total", + Help: "Total number of HTTP/2 gossip transport stream packets failed to read", + }) + m.streamTxTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_tx_packets_total", + Help: "Total number of HTTP/2 gossip transport stream packets written", + }) + m.streamTxBytesTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_tx_bytes_total", + Help: "Total number of HTTP/2 gossip transport stream bytes written", + }) + m.streamTxFailedTotal = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_transport_stream_tx_packets_failed_total", + Help: "Total number of failed HTTP/2 gossip transport stream packets", + }) + + m.Add( + m.packetRxTotal, + m.packetRxBytesTotal, + m.packetTxTotal, + m.packetTxBytesTotal, + m.packetTxFailedTotal, + m.openStreams, + m.streamRxTotal, + m.streamRxBytesTotal, + m.streamTxTotal, + m.streamTxBytesTotal, + m.streamTxFailedTotal, + ) + + return &m +} diff --git a/vendor/github.com/grafana/ckit/internal/gossiphttp/stream_conn.go b/vendor/github.com/grafana/ckit/internal/gossiphttp/stream_conn.go new file mode 100644 index 0000000000000..5070b75940822 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/gossiphttp/stream_conn.go @@ -0,0 +1,212 @@ +package gossiphttp + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "os" + "sync" + "time" +) + +// streamClient is implemented by http2Stream. +type streamClient interface { + Send([]byte) error + Recv() ([]byte, error) +} + +// packetsClientConn implements a bidirectional communication channel with a +// remote peer exchanging gossiphttp messages. +type packetsClientConn struct { + cli streamClient + onClose func() + closed chan struct{} + metrics *metrics + + localAddr, remoteAddr net.Addr + + readCnd *sync.Cond // Used to wake sleeping readers. + spawnReader sync.Once // Used to lazily launch a cli reader. + readMessages chan readResult // Messages read from the cli reader. + readTimeout time.Time // Read deadline. + readTimeoutCancel context.CancelFunc // Cancels read deadline and wakes up goroutines. + readBuffer bytes.Buffer // Data buffer ready for immediate reading. + + writeMut sync.Mutex +} + +type readResult struct { + Message []byte + Error error +} + +func (c *packetsClientConn) Read(b []byte) (n int, err error) { + defer func() { + c.metrics.streamRxTotal.Inc() + c.metrics.streamRxBytesTotal.Add(float64(n)) + if err != nil { + c.metrics.streamRxFailedTotal.Inc() + } + }() + + // Lazily spawn a background goroutine to reaed from our stream client. + c.spawnReader.Do(func() { + go func() { + defer close(c.readMessages) + + for { + msg, err := c.cli.Recv() + c.readCnd.Broadcast() // Wake up sleeping goroutines. + + res := readResult{Message: msg, Error: err} + select { + case c.readMessages <- res: + case <-c.closed: + return + } + + if err != nil { + return + } + } + }() + }) + + for n == 0 { + n2, err := c.readOrBlock(b) + if err != nil { + return n2, err + } + n += n2 + } + return n, nil +} + +func (c *packetsClientConn) readOrBlock(b []byte) (n int, err error) { + c.readCnd.L.Lock() + defer c.readCnd.L.Unlock() + if !c.readTimeout.IsZero() && !time.Now().Before(c.readTimeout) { + return 0, os.ErrDeadlineExceeded + } + + // Read from the existing buffer first. + n, err = c.readBuffer.Read(b) + if err != nil && !errors.Is(err, io.EOF) { + return + } else if n != 0 { + return + } + + // We've emptied our buffer. Pull the next message in or wait for a message + // to be available. + select { + case msg, ok := <-c.readMessages: + if !ok { + return n, io.EOF + } + switch { + case msg.Error != nil: + return n, msg.Error + case msg.Message == nil: + return n, fmt.Errorf("nil message") + default: + _, err = c.readBuffer.Write(msg.Message) + return n, err + } + default: + c.readCnd.Wait() // Wait for something to be written or for the timeout to fire. + return 0, nil + } +} + +func (c *packetsClientConn) Write(b []byte) (n int, err error) { + defer func() { + c.metrics.streamTxTotal.Inc() + c.metrics.streamTxBytesTotal.Add(float64(n)) + if err != nil { + c.metrics.streamTxFailedTotal.Inc() + } + }() + + c.writeMut.Lock() + defer c.writeMut.Unlock() + + err = c.cli.Send(b) + if err != nil { + return 0, err + } + return len(b), nil +} + +func (c *packetsClientConn) Close() error { + c.writeMut.Lock() + defer c.writeMut.Unlock() + + select { + case <-c.closed: + // no-op: already closed + return nil + default: + close(c.closed) + + if c.onClose != nil { + c.onClose() + } + + return c.cli.(*http2Stream).r.Close() + } +} + +func (c *packetsClientConn) LocalAddr() net.Addr { + return c.localAddr +} + +func (c *packetsClientConn) RemoteAddr() net.Addr { + return c.remoteAddr +} + +func (c *packetsClientConn) SetDeadline(t time.Time) error { + return c.SetReadDeadline(t) +} + +func (c *packetsClientConn) SetReadDeadline(t time.Time) error { + c.readCnd.L.Lock() + defer c.readCnd.L.Unlock() + + c.readTimeout = t + + // There should only be one deadline goroutine at a time, so cancel it if it + // already exists. + if c.readTimeoutCancel != nil { + c.readTimeoutCancel() + c.readTimeoutCancel = nil + } + c.readTimeoutCancel = c.deadlineTimer(t) + return nil +} + +func (c *packetsClientConn) deadlineTimer(t time.Time) context.CancelFunc { + if t.IsZero() { + // Deadline of zero means to wait forever. + return nil + } + if t.Before(time.Now()) { + c.readCnd.Broadcast() + } + ctx, cancel := context.WithDeadline(context.Background(), t) + go func() { + <-ctx.Done() + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + c.readCnd.Broadcast() + } + }() + return cancel +} + +func (c *packetsClientConn) SetWriteDeadline(t time.Time) error { + // no-op: writes finish immediately + return nil +} diff --git a/vendor/github.com/grafana/ckit/internal/gossiphttp/transport.go b/vendor/github.com/grafana/ckit/internal/gossiphttp/transport.go new file mode 100644 index 0000000000000..cefb873ca6605 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/gossiphttp/transport.go @@ -0,0 +1,582 @@ +// Package gossiphttp implements an HTTP/2 transport for gossip. +// +// # Protocol +// +// Peers send two types of messages to each other: +// +// 1. /api/v1/ckit/transport/message sends a stream of messages to a peer. The +// receiver does not respond with any messages. +// +// 2. /api/v1/ckit/transport/stream opens a bidirectional communication +// channel to a peer, where both peers may send messages to each other. Once +// either peer closes the connection, the stream is terminated. +// +// Both requests expect the Content-Type header to be set to +// application/x.ckit. +// +// Requests MUST be delivered over HTTP/2. HTTP/1.X requests will be rejected +// with HTTP 505 HTTP Version Not Supported. +// +// # Message Format +// +// All messages sent between peers have the same format: +// +// +------------------------+ +// | Magic = 0xCC <1 byte> | +// |------------------------| +// | Data length <2 bytes> | +// |------------------------| +// | Data <n bytes> | +// +------------------------+ +// +// It is recommended that the message data size kept within the UDP MTU size, +// normally 1400 bytes. The message data size must not exeed 65,535 bytes. +package gossiphttp + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "sync" + "sync/atomic" + "time" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/grafana/ckit/internal/queue" + "github.com/hashicorp/memberlist" + "github.com/prometheus/client_golang/prometheus" +) + +// packetBufferSize is the maximum amount of packets that can be held in +// memory. Packets buffers are an LRU cache, so the oldest non-dequeued packet +// is discarded after a bufer is full. +const packetBufferSize = 1000 + +const ( + contentTypeHeader = "Content-Type" + // ckitContentType is the value of the Content Type header that gossiphttp + // messages must use. + ckitContentType = "application/x.ckit" +) + +// API endpoints used for messaging. +var ( + baseRoute = "/api/v1/ckit/transport/" + + // messageEndpoint is used to send one or more messages to a peer. + messageEndpoint = baseRoute + "message" + + // streamEndpoint is used to open a communication stream to a peer where they + // can exchange larger amounts of information. + streamEndpoint = baseRoute + "stream" +) + +// Options controls the gossiphttp transport. +type Options struct { + // Optional logger to use. + Log log.Logger + + // Client to use for communicating to peers. Required. The Transport used + // by the client must be able to handle HTTP/2 requests for any peer. + // + // Note that TLS is not required for communication between peers. The + // Client.Transport should be able to fall back to h2c for HTTP/2 traffic + // when connections over HTTPS are not used. + Client *http.Client + + // Timeout to use when sending a packet. + PacketTimeout time.Duration + + // UseHTTPS defines whether TLS should be used for communication between + // peers. + UseHTTPS bool +} + +// Transport is an HTTP/2 implementation of memberlist.Transport. Call +// NewTransport to create one. +type Transport struct { + log log.Logger + opts Options + metrics *metrics + + // memberlist is designed for UDP, which is nearly non-blocking for writes. + // We need to be able to emulate the same performance of passing messages, so + // we write messages to buffered queues which are processed in the + // background. + inPacketQueue, outPacketQueue *queue.Queue + + inPacketCh chan *memberlist.Packet + streamCh chan net.Conn + + // Incoming packets and streams should be rejected when the transport is + // closed. + closedMut sync.RWMutex + exited chan struct{} + cancel context.CancelFunc + hasExited atomic.Bool + + // Generated after calling FinalAdvertiseAddr + localAddr net.Addr +} + +var ( + _ memberlist.Transport = (*Transport)(nil) + _ memberlist.NodeAwareTransport = (*Transport)(nil) +) + +// http2Stream implements the streamClient interface and allows for sending and +// receiving messages in a bidirectional streaming connection. +type http2Stream struct { + r io.ReadCloser + w io.Writer +} + +// Send sends b over an http2Stream connection. +func (sc *http2Stream) Send(b []byte) error { + return writeMessage(sc.w, b) +} + +// Recv reads from an http2Stream connection. +func (sc *http2Stream) Recv() ([]byte, error) { + return readMessage(sc.r) +} + +var _ io.WriteCloser = (*flushWriter)(nil) + +// flushWriter wraps an io.Writer with an http.Flusher to flush buffered data +// to a streaming HTTP/2 connection's request body. +type flushWriter struct { + w io.Writer + f http.Flusher +} + +func (w *flushWriter) Write(data []byte) (int, error) { + n, err := w.w.Write(data) + w.f.Flush() + return n, err +} + +func (w *flushWriter) Close() error { return nil } + +// NewTransport returns a new Transport. Transports must be attached to an HTTP +// server so their endpoints are invoked. See [Handler] for more information. +func NewTransport(opts Options) (*Transport, prometheus.Collector, error) { + if opts.Client == nil { + return nil, nil, fmt.Errorf("HTTP client must be provided") + } + + l := opts.Log + if l == nil { + l = log.NewNopLogger() + } + + ctx, cancel := context.WithCancel(context.Background()) + + t := &Transport{ + log: l, + opts: opts, + metrics: newMetrics(), + + inPacketQueue: queue.New(packetBufferSize), + outPacketQueue: queue.New(packetBufferSize), + + inPacketCh: make(chan *memberlist.Packet), + streamCh: make(chan net.Conn), + + exited: make(chan struct{}), + cancel: cancel, + } + + t.metrics.Add(prometheus.NewGaugeFunc( + prometheus.GaugeOpts{ + Name: "cluster_transport_rx_packet_queue_length", + Help: "Current number of unprocessed incoming packets", + }, + func() float64 { return float64(t.inPacketQueue.Size()) }, + )) + t.metrics.Add(prometheus.NewGaugeFunc( + prometheus.GaugeOpts{ + Name: "cluster_transport_tx_packet_queue_length", + Help: "Current number of unprocessed outgoing packets", + }, + func() float64 { return float64(t.outPacketQueue.Size()) }, + )) + + go t.run(ctx) + + return t, t.metrics, nil +} + +func (t *Transport) run(ctx context.Context) { + defer close(t.exited) + + var wg sync.WaitGroup + wg.Add(2) + defer wg.Wait() + + // Close our queues before shutting down. This must be done before calling + // wg.Wait as it will cause the goroutines to exit. + defer func() { _ = t.inPacketQueue.Close() }() + defer func() { _ = t.outPacketQueue.Close() }() + + // Process queue of incoming packets + go func() { + defer wg.Done() + + for { + v, err := t.inPacketQueue.Dequeue(ctx) + if err != nil { + return + } + + pkt := v.(*memberlist.Packet) + t.metrics.packetRxTotal.Inc() + t.metrics.packetRxBytesTotal.Add(float64(len(pkt.Buf))) + + select { + case <-ctx.Done(): + case t.inPacketCh <- pkt: + } + } + }() + + // Process queue of outgoing packets + go func() { + defer wg.Done() + + for { + v, err := t.outPacketQueue.Dequeue(ctx) + if err != nil { + return + } + + pkt := v.(*outPacket) + t.metrics.packetTxTotal.Inc() + t.metrics.packetTxBytesTotal.Add(float64(len(pkt.Data))) + t.writeToSync(pkt.Data, pkt.Addr) + } + }() + + <-ctx.Done() +} + +// Handler returns the base HTTP route and handler for the Transport. +func (t *Transport) Handler() (route string, handler http.Handler) { + mux := http.NewServeMux() + mux.Handle(messageEndpoint, http.HandlerFunc(t.handleMessage)) + mux.Handle(streamEndpoint, http.HandlerFunc(t.handleStream)) + return baseRoute, mux +} + +// handleMessage is used for single-packet communication. +func (t *Transport) handleMessage(w http.ResponseWriter, r *http.Request) { + if t.hasExited.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + if r.ProtoMajor != 2 { + w.WriteHeader(http.StatusHTTPVersionNotSupported) + return + } + if r.Header.Get(contentTypeHeader) != ckitContentType { + w.WriteHeader(http.StatusBadRequest) + return + } + + var ( + recvTime = time.Now() + remoteAddr = parseRemoteAddr(r.RemoteAddr) + ) + + // Read each message until the request body has been fully consumed. Each + // message is converted into a single packet. + for { + msg, err := readMessage(r.Body) + if errors.Is(err, io.EOF) { + break + } else if err != nil { + level.Warn(t.log).Log("msg", "error reading packet from peer", "err", err) + w.WriteHeader(http.StatusBadRequest) + return + } + + t.metrics.packetRxTotal.Inc() + t.metrics.packetRxBytesTotal.Add(float64(len(msg))) + + // Enqueue the packet to be processed in the background. This allows + // HTTP calls to have as low of a latency as possible to help keep + // things moving along. + t.inPacketQueue.Enqueue(&memberlist.Packet{ + Buf: msg, + From: remoteAddr, + Timestamp: recvTime, + }) + } + + w.WriteHeader(http.StatusOK) +} + +// parseRemoteAddr parses a ip:port string into a net.Addr. If the addr cannot +// be parsed, a default implementation for an "unknown" net.Addr is returned. +func parseRemoteAddr(addr string) net.Addr { + remoteHost, remoteService, err := net.SplitHostPort(addr) + if err != nil { + return unknownAddr{} + } + + remoteIP := net.ParseIP(remoteHost) + if remoteIP == nil { + return unknownAddr{} + } + + remotePort, err := net.LookupPort("tcp", remoteService) + if err != nil { + return unknownAddr{} + } + + return &net.TCPAddr{ + IP: remoteIP, + Port: remotePort, + } +} + +// handleStream is used for streaming bidirectional communication. +func (t *Transport) handleStream(w http.ResponseWriter, r *http.Request) { + if t.hasExited.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + if r.ProtoMajor != 2 { + w.WriteHeader(http.StatusHTTPVersionNotSupported) + return + } + flusher, ok := w.(http.Flusher) + if !ok { + w.WriteHeader(http.StatusHTTPVersionNotSupported) + return + } + + if r.Header.Get(contentTypeHeader) != ckitContentType { + w.WriteHeader(http.StatusBadRequest) + return + } + + w.WriteHeader(http.StatusOK) + flusher.Flush() + + waitClosed := make(chan struct{}) + + var readMut sync.Mutex + readCnd := sync.NewCond(&readMut) + + t.metrics.openStreams.Inc() + defer t.metrics.openStreams.Dec() + + packetsClient := &http2Stream{ + r: r.Body, + w: &flushWriter{w: w, f: flusher}, + } + + conn := &packetsClientConn{ + cli: packetsClient, + onClose: func() { close(waitClosed) }, + closed: make(chan struct{}), + metrics: t.metrics, + + localAddr: t.localAddr, + remoteAddr: parseRemoteAddr(r.RemoteAddr), + + readCnd: readCnd, + readMessages: make(chan readResult), + } + + t.streamCh <- conn + <-waitClosed +} + +// WriteToAddress implements NodeAwareTransport. +func (t *Transport) WriteToAddress(b []byte, addr memberlist.Address) (time.Time, error) { + return t.WriteTo(b, addr.Addr) +} + +// DialAddressTimeout implements NodeAwareTransport. +func (t *Transport) DialAddressTimeout(addr memberlist.Address, timeout time.Duration) (net.Conn, error) { + return t.DialTimeout(addr.Addr, timeout) +} + +// FinalAdvertiseAddr returns the address this peer uses to advertise its +// connections. +func (t *Transport) FinalAdvertiseAddr(ip string, port int) (net.IP, int, error) { + if ip == "" { + return nil, 0, fmt.Errorf("no configured advertise address") + } else if port == 0 { + return nil, 0, fmt.Errorf("missing real listen port") + } + + advertiseIP := net.ParseIP(ip) + if advertiseIP == nil { + return nil, 0, fmt.Errorf("failed to parse advertise ip %q", ip) + } + + // Convert to IPv4 if possible. + if ip4 := advertiseIP.To4(); ip4 != nil { + advertiseIP = ip4 + } + + t.localAddr = &net.TCPAddr{IP: advertiseIP, Port: port} + return advertiseIP, port, nil +} + +type outPacket struct { + Data []byte + Addr string +} + +// WriteTo enqueues a message b to be sent to the peer specified by addr. The +// message is delivered in the background asynchronously by the transport. +func (t *Transport) WriteTo(b []byte, addr string) (time.Time, error) { + t.outPacketQueue.Enqueue(&outPacket{Data: b, Addr: addr}) + return time.Now(), nil +} + +// PacketCh returns a channel of packets received from remote peers. +func (t *Transport) PacketCh() <-chan *memberlist.Packet { + return t.inPacketCh +} + +// DialTimeout opens a bidirectional communication channel to the specified +// peer address. +func (t *Transport) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) { + ctx := context.Background() + var cancel context.CancelFunc + if timeout > 0 { + ctx, cancel = context.WithTimeout(ctx, timeout) + } + + scheme := "http" + if t.opts.UseHTTPS { + scheme = "https" + } + + var readMut sync.Mutex + readCnd := sync.NewCond(&readMut) + + pr, pw := io.Pipe() + + req := &http.Request{ + Method: http.MethodPost, + URL: &url.URL{ + Scheme: scheme, + Host: addr, + Path: streamEndpoint, + }, + Header: http.Header{}, + Proto: "HTTP/2", + ProtoMajor: 2, + ProtoMinor: 0, + Body: pr, + } + req.Header.Set(contentTypeHeader, ckitContentType) + req = req.WithContext(ctx) + + resp, err := t.opts.Client.Do(req) + if err != nil { + if cancel != nil { + cancel() + } + return nil, err + } + + t.metrics.openStreams.Inc() + + packetsClient := &http2Stream{ + r: resp.Body, + w: pw, + } + + return &packetsClientConn{ + cli: packetsClient, + + onClose: func() { + t.metrics.openStreams.Dec() + if cancel != nil { + cancel() + } + }, + closed: make(chan struct{}), + metrics: t.metrics, + + localAddr: t.localAddr, + remoteAddr: parseRemoteAddr(addr), + + readCnd: readCnd, + readMessages: make(chan readResult), + }, nil +} + +// StreamCh returns a channel of bidirectional communication channels opened by +// remote peers. +func (t *Transport) StreamCh() <-chan net.Conn { + return t.streamCh +} + +// Shutdown terminates the transport. +func (t *Transport) Shutdown() error { + t.closedMut.Lock() + defer t.closedMut.Unlock() + t.cancel() + t.hasExited.Store(true) + <-t.exited + return nil +} + +func (t *Transport) writeToSync(b []byte, addr string) { + ctx := context.Background() + if t.opts.PacketTimeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, t.opts.PacketTimeout) + defer cancel() + } + + scheme := "http" + if t.opts.UseHTTPS { + scheme = "https" + } + + bb := bytes.NewBuffer(nil) + err := writeMessage(bb, b) + if err != nil { + level.Debug(t.log).Log("msg", "failed to encode message", "err", err) + t.metrics.packetTxFailedTotal.Inc() + return + } + + req := &http.Request{ + Method: http.MethodPost, + URL: &url.URL{ + Scheme: scheme, + Host: addr, + Path: messageEndpoint, + }, + Header: http.Header{}, + Proto: "HTTP/2", + ProtoMajor: 2, + ProtoMinor: 0, + Body: io.NopCloser(bb), + } + req.Header.Set(contentTypeHeader, ckitContentType) + req = req.WithContext(ctx) + + req.Header.Set("Content-Type", ckitContentType) + resp, err := t.opts.Client.Do(req) + if err != nil || resp.StatusCode != http.StatusOK { + level.Debug(t.log).Log("msg", "failed to send message", "err", err) + t.metrics.packetTxFailedTotal.Inc() + } +} diff --git a/vendor/github.com/grafana/ckit/internal/gossiphttp/unknown_addr.go b/vendor/github.com/grafana/ckit/internal/gossiphttp/unknown_addr.go new file mode 100644 index 0000000000000..0d522f6c2d3f5 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/gossiphttp/unknown_addr.go @@ -0,0 +1,10 @@ +package gossiphttp + +import "net" + +type unknownAddr struct{} + +var _ net.Addr = unknownAddr{} + +func (unknownAddr) Network() string { return "tcp" } +func (unknownAddr) String() string { return "unknown" } diff --git a/vendor/github.com/grafana/ckit/internal/lamport/lamport.go b/vendor/github.com/grafana/ckit/internal/lamport/lamport.go new file mode 100644 index 0000000000000..7f410a835064e --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/lamport/lamport.go @@ -0,0 +1,57 @@ +package lamport + +import "sync/atomic" + +var globalClock Clock + +// Now returns the current Time. The time will not be changed. +func Now() Time { return globalClock.Now() } + +// Tick increases the current Time by 1 and returns it. +func Tick() Time { return globalClock.Tick() } + +// Observe ensures that the time past t by at least. Must be called when +// receiving a message from a remote machine to roughly synchronize +// clocks between processes. +func Observe(t Time) { globalClock.Observe(t) } + +// Clock implements a lamport clock. The current time can be retrieved by +// calling Now. The Clock must be manually incremented either by calling Tick +// or Observe. +type Clock struct { + time atomic.Uint64 +} + +// Time is the value of a Clock. +type Time uint64 + +// Now returns the current Time of c. The time is not changed. +func (c *Clock) Now() Time { + return Time(c.time.Load()) +} + +// Tick increases c's Time by 1 and returns the new value. +func (c *Clock) Tick() Time { + return Time(c.time.Add(1)) +} + +// Observe ensures that c's time is past t. Observe must be called when +// receiving a message from a remote machine that contains a Time, and is used +// to roughly synchronize clocks between machines. +func (c *Clock) Observe(t Time) { +Retry: + // If t is behind us, we don't need to do anything. + now := c.time.Load() + if uint64(t) < now { + return + } + + // Move our clock past t. + if !c.time.CompareAndSwap(now, uint64(t+1)) { + // Retry if the CAS failed, which can happen when many observations are + // happening concurrently. Either this will eventually succeed or another + // call to Observe will move the current time past t and we'll be able + // to do the early stop. + goto Retry + } +} diff --git a/vendor/github.com/grafana/ckit/internal/messages/broadcast.go b/vendor/github.com/grafana/ckit/internal/messages/broadcast.go new file mode 100644 index 0000000000000..016793e6e04f1 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/messages/broadcast.go @@ -0,0 +1,40 @@ +package messages + +import "github.com/hashicorp/memberlist" + +// Broadcast converts m into a memberlist Broadcast. m should not change once +// being converted into a Broadcast. +// +// onDone will be called once the message has been broadcasted or invalidated. +func Broadcast(m Message, onDone func()) (memberlist.Broadcast, error) { + bb, err := Encode(m) + if err != nil { + return nil, err + } + + return &broadcastWrapper{inner: m, data: bb, onDone: onDone}, nil +} + +type broadcastWrapper struct { + inner Message + data []byte + onDone func() +} + +func (bw *broadcastWrapper) Invalidates(b memberlist.Broadcast) bool { + other, ok := b.(*broadcastWrapper) + if !ok { + return false + } + return bw.inner.Invalidates(other.inner) +} + +func (bw *broadcastWrapper) Message() []byte { + return bw.data +} + +func (bw *broadcastWrapper) Finished() { + if bw.onDone != nil { + bw.onDone() + } +} diff --git a/vendor/github.com/grafana/ckit/internal/messages/messages.go b/vendor/github.com/grafana/ckit/internal/messages/messages.go new file mode 100644 index 0000000000000..b74d81675d4ce --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/messages/messages.go @@ -0,0 +1,105 @@ +// Package messages allows for encoding and decoding messages to broadcast over +// gossip. +package messages + +import ( + "bytes" + "encoding/binary" + "fmt" + + "github.com/hashicorp/go-msgpack/codec" +) + +// magicHeader is added to the start of every message. +const magicHeader uint16 = 0x1201 + +// Type of the message. Encoded along with the payload to be able to determine +// what message was sent during decoding. +type Type uint8 + +// Types for messages. +const ( + TypeInvalid Type = iota // TypeInvalid is an invalid type. + TypeState // TypeState is used for a State broadcast +) + +var knownTypes = map[Type]string{ + TypeInvalid: "invalid", + TypeState: "state", +} + +// String returns the string representation of t. +func (t Type) String() string { + val, ok := knownTypes[t] + if !ok { + return fmt.Sprintf("<invalid type %d>", t) + } + return val +} + +// Message is a payload that can be gossiped to other peers. +type Message interface { + // Type returns the Type of the message. Type must be a known, valid type. + Type() Type + + // Invalidates should return true if this message takes precedence over m. + Invalidates(m Message) bool + + // Cache should return true if this Message should be cached into the local + // state. Messages in the local state will be synchronized with peers over + // time, and is useful for anti-entropy. + Cache() bool +} + +// Encode encodes m into a byte slice that can be broadcast to other peers. +// Encode will panic if the Type of m is invalid or unknown. +func Encode(m Message) (raw []byte, err error) { + ty := m.Type() + if _, known := knownTypes[ty]; !known || ty == TypeInvalid { + panic("ty must be a known, valid type") + } + + buf := bytes.NewBuffer(nil) + + // Write magic header and type + _ = binary.Write(buf, binary.BigEndian, magicHeader) + buf.WriteByte(uint8(ty)) + + // Then add the message + var handle codec.MsgpackHandle + enc := codec.NewEncoder(buf, &handle) + err = enc.Encode(m) + return buf.Bytes(), err +} + +// Parse parses an encoded buffer returned by Encode. The resulting buf can be +// passed to Decode. Returns an error if the magic header or type is invalid. +// +// buf will be a slice referencing data in raw; do not modify raw until you are +// finished with the message. +func Parse(raw []byte) (buf []byte, ty Type, err error) { + if len(raw) < 3 { + return nil, TypeInvalid, fmt.Errorf("payload too small for message") + } + + magic := binary.BigEndian.Uint16(raw[0:2]) + if magic != magicHeader { + return nil, TypeInvalid, fmt.Errorf("invalid magic header %x", magic) + } + + ty = Type(raw[2]) + if _, known := knownTypes[ty]; !known || ty == TypeInvalid { + return nil, TypeInvalid, fmt.Errorf("invalid message type %d", ty) + } + + buf = raw[3:] + return +} + +// Decode decodes a message from Parse. +func Decode(buf []byte, m Message) error { + r := bytes.NewReader(buf) + var handle codec.MsgpackHandle + dec := codec.NewDecoder(r, &handle) + return dec.Decode(m) +} diff --git a/vendor/github.com/grafana/ckit/internal/messages/state.go b/vendor/github.com/grafana/ckit/internal/messages/state.go new file mode 100644 index 0000000000000..d9473229882de --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/messages/state.go @@ -0,0 +1,40 @@ +package messages + +import ( + "fmt" + + "github.com/grafana/ckit/internal/lamport" + "github.com/grafana/ckit/peer" +) + +// State represents a State change broadcast from a node. +type State struct { + // Name of the node this state change is for. + NodeName string + // New State of the node. + NewState peer.State + // Time the state was generated. + Time lamport.Time +} + +// String returns the string representation of the State message. +func (s State) String() string { + return fmt.Sprintf("%s @%d: %s", s.NodeName, s.Time, s.NewState) +} + +var _ Message = (*State)(nil) + +// Type implements Message. +func (s *State) Type() Type { return TypeState } + +// Invalidates implements Message. +func (s *State) Invalidates(m Message) bool { + other, ok := m.(*State) + if !ok { + return false + } + return s.NodeName == other.NodeName && s.Time > other.Time +} + +// Cache implements Message. +func (s *State) Cache() bool { return true } diff --git a/vendor/github.com/grafana/ckit/internal/metricsutil/container.go b/vendor/github.com/grafana/ckit/internal/metricsutil/container.go new file mode 100644 index 0000000000000..c9fffba85495b --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/metricsutil/container.go @@ -0,0 +1,30 @@ +package metricsutil + +import "github.com/prometheus/client_golang/prometheus" + +// Container wraps around a set of prometheus.Collectors and exposes them as a +// single prometheus.Collector. +type Container struct { + cs []prometheus.Collector +} + +var _ prometheus.Collector = (*Container)(nil) + +// Add registers a new Collector into the Container. +func (c *Container) Add(cs ...prometheus.Collector) { + c.cs = append(c.cs, cs...) +} + +// Describe implements prometheus.Collector. +func (c *Container) Describe(ch chan<- *prometheus.Desc) { + for _, cl := range c.cs { + cl.Describe(ch) + } +} + +// Collect implements prometheus.Collector. +func (c *Container) Collect(ch chan<- prometheus.Metric) { + for _, cl := range c.cs { + cl.Collect(ch) + } +} diff --git a/vendor/github.com/grafana/ckit/internal/metricsutil/info.go b/vendor/github.com/grafana/ckit/internal/metricsutil/info.go new file mode 100644 index 0000000000000..1781c4154f4b2 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/metricsutil/info.go @@ -0,0 +1,85 @@ +package metricsutil + +import ( + "fmt" + "sync" + + "github.com/prometheus/client_golang/prometheus" +) + +// InfoOpts is an alias for prometheus.Opts. See there for doc comments. +type InfoOpts prometheus.Opts + +// InfoCollector is a Collector that represents a constant value with a set of +// changing labels. +type InfoCollector struct { + desc *prometheus.Desc + + valuesMut sync.RWMutex + names, values []string +} + +var ( + _ prometheus.Collector = (*InfoCollector)(nil) +) + +// NewInfoCollector creates a new info metric with dynamic values. Call Set to +// change the specific value for a label. All labels are always reported, and +// are initialized to empty strings by default. +func NewInfoCollector(opts InfoOpts, labelNames ...string) *InfoCollector { + var ( + names = make([]string, len(labelNames)) + values = make([]string, len(labelNames)) + ) + + copy(names, labelNames) + + desc := prometheus.NewDesc( + prometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), + opts.Help, + names, + nil, + ) + + return &InfoCollector{ + desc: desc, + + names: names, + values: values, + } +} + +// Set updates the value for a given label. +func (ic *InfoCollector) Set(labelName, labelValue string) error { + for i, name := range ic.names { + if name != labelName { + continue + } + + ic.valuesMut.Lock() + ic.values[i] = labelValue + ic.valuesMut.Unlock() + return nil + } + + return fmt.Errorf("label name %q does not exist", labelName) +} + +// MustSet calls Set and panics if it returns an error. +func (ic *InfoCollector) MustSet(labelName, labelValue string) { + if err := ic.Set(labelName, labelValue); err != nil { + panic(err) + } +} + +// Describe implements prometheus.Collector. +func (ic *InfoCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- ic.desc +} + +// Collect implements prometheus.Collector. +func (ic *InfoCollector) Collect(ch chan<- prometheus.Metric) { + ic.valuesMut.RLock() + defer ic.valuesMut.RUnlock() + ch <- prometheus.MustNewConstMetric(ic.desc, prometheus.GaugeValue, 1, ic.values...) +} diff --git a/vendor/github.com/grafana/ckit/internal/queue/queue.go b/vendor/github.com/grafana/ckit/internal/queue/queue.go new file mode 100644 index 0000000000000..7fc295848ec17 --- /dev/null +++ b/vendor/github.com/grafana/ckit/internal/queue/queue.go @@ -0,0 +1,148 @@ +// Package queue implements a non-blocking message queue. +package queue + +import ( + "context" + "io" + "sort" + "sync" + "sync/atomic" + + "github.com/grafana/ckit/internal/lamport" +) + +// Unbounded indicates the Queue does not have a limit. +const Unbounded int = -1 + +// Queue implements a multi-producer, single consumer event queue. +type Queue struct { + sema *sync.Cond + elements []entry + closed bool + + dequeueInUse uint32 + + clock lamport.Clock + limit int +} + +type entry struct { + Value interface{} + Time lamport.Time +} + +// New creates a new Queue. +func New(limit int) *Queue { + return &Queue{ + sema: &sync.Cond{L: &sync.Mutex{}}, + limit: limit, + } +} + +// Dequeue blocks until ctx is canceled or an item can be dequeued. Dequeue +// will panic if there are multiple concurrent callers. +func (q *Queue) Dequeue(ctx context.Context) (interface{}, error) { + if !atomic.CompareAndSwapUint32(&q.dequeueInUse, 0, 1) { + panic("cannot call dequeue concurrently") + } + defer atomic.StoreUint32(&q.dequeueInUse, 0) + + parentCtx := ctx + ctx, cancel := context.WithCancel(parentCtx) + defer cancel() + + // Ensure that if context is canceled we wake ourselves up so we can + // exit. + go func() { + <-ctx.Done() + if parentCtx.Err() != nil { + // We only need to signal if the parent context canceled; otherwise its + // our local context and we're already exiting normally. + q.sema.Signal() + } + }() + + q.sema.L.Lock() + for ctx.Err() == nil && !q.closed && len(q.elements) == 0 { + q.sema.Wait() + } + defer q.sema.L.Unlock() + + if ctx.Err() != nil { + return nil, ctx.Err() + } else if q.closed { + return nil, io.EOF + } + + element := q.elements[0] + q.elements = q.elements[1:] + return element.Value, nil +} + +// TryDequeue will return an element from q if one exists. +func (q *Queue) TryDequeue() (interface{}, bool) { + if !atomic.CompareAndSwapUint32(&q.dequeueInUse, 0, 1) { + panic("cannot call dequeue concurrently") + } + defer atomic.StoreUint32(&q.dequeueInUse, 0) + + q.sema.L.Lock() + defer q.sema.L.Unlock() + + if len(q.elements) > 0 { + element := q.elements[0] + q.elements = q.elements[1:] + return element.Value, true + } + + return nil, false +} + +// Enqueue queues an item. Messages are guaranteed to be dequeued in call order. +// If the queue has reached its limit, the oldest message will be discarded. +func (q *Queue) Enqueue(v interface{}) { + element := entry{Time: q.clock.Tick(), Value: v} + + q.sema.L.Lock() + defer q.sema.L.Unlock() + + if q.closed { + // The queue is closed: quit immediately + return + } + + // Perform a sorted insert into the slice. + insert := sort.Search(len(q.elements), func(i int) bool { + return q.elements[i].Time > element.Time + }) + if insert == len(q.elements) { + q.elements = append(q.elements, element) + } else { + q.elements = append(q.elements[:insert], append([]entry{element}, q.elements[insert:]...)...) + } + + // Remove the first element if we've grown too big. + if q.limit != Unbounded && len(q.elements) > q.limit { + q.elements = q.elements[1:] + } + + q.sema.Signal() +} + +// Size of the elements in the queue. +func (q *Queue) Size() int { + q.sema.L.Lock() + defer q.sema.L.Unlock() + return len(q.elements) +} + +// Close the queue, preventing any more messages from being sent. Dequeue will +// return io.EOF. +func (q *Queue) Close() error { + q.sema.L.Lock() + defer q.sema.L.Unlock() + q.closed = true + q.elements = nil + q.sema.Signal() + return nil +} diff --git a/vendor/github.com/grafana/ckit/logging.go b/vendor/github.com/grafana/ckit/logging.go new file mode 100644 index 0000000000000..a670ddc463e41 --- /dev/null +++ b/vendor/github.com/grafana/ckit/logging.go @@ -0,0 +1,59 @@ +package ckit + +import ( + "bytes" + "io" + golog "log" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" +) + +var ( + errPrefix = []byte("[ERR]") + warnPrefix = []byte("[WARN]") + infoPrefix = []byte("[INFO]") + debugPrefix = []byte("[DEBUG]") + memberListPrefix = []byte("memberlist: ") +) + +// memberListOutputLogger will do best-effort classification of the logging level that memberlist uses in its log lines +// and use the corresponding level when logging with logger. It will drop redundant `[<level>] memberlist:` parts. +// This helps us surface only desired log messages from memberlist. If classification fails, info level is used as +// a fallback. See tests for detailed behaviour. +type memberListOutputLogger struct { + logger log.Logger +} + +var _ io.Writer = (*memberListOutputLogger)(nil) + +func newMemberListLogger(logger log.Logger) *golog.Logger { + return golog.New(&memberListOutputLogger{logger: logger}, "", 0) +} + +func (m *memberListOutputLogger) Write(p []byte) (int, error) { + var err error + + sanitizeFn := func(dropPrefix []byte, msg []byte) string { + noLevel := bytes.TrimSpace(bytes.TrimPrefix(msg, dropPrefix)) + return string(bytes.TrimPrefix(noLevel, memberListPrefix)) + } + + switch { + case bytes.HasPrefix(p, errPrefix): + err = level.Error(m.logger).Log("msg", sanitizeFn(errPrefix, p)) + case bytes.HasPrefix(p, warnPrefix): + err = level.Warn(m.logger).Log("msg", sanitizeFn(warnPrefix, p)) + case bytes.HasPrefix(p, infoPrefix): + err = level.Info(m.logger).Log("msg", sanitizeFn(infoPrefix, p)) + case bytes.HasPrefix(p, debugPrefix): + err = level.Debug(m.logger).Log("msg", sanitizeFn(debugPrefix, p)) + default: + err = level.Info(m.logger).Log("msg", sanitizeFn(nil, p)) + } + + if err != nil { + return 0, err + } + return len(p), nil +} diff --git a/vendor/github.com/grafana/ckit/metrics.go b/vendor/github.com/grafana/ckit/metrics.go new file mode 100644 index 0000000000000..97a06e1db8cc6 --- /dev/null +++ b/vendor/github.com/grafana/ckit/metrics.go @@ -0,0 +1,145 @@ +package ckit + +import ( + "github.com/grafana/ckit/internal/metricsutil" + "github.com/hashicorp/memberlist" + "github.com/prometheus/client_golang/prometheus" +) + +// Possible label values for metrics.gossipEventsTotal +const ( + eventStateChange = "state_change_message" + eventUnkownMessage = "unknown_message" + eventGetLocalState = "get_local_state" + eventMergeRemoteState = "merge_remote_state" + eventNodeJoin = "node_join" + eventNodeLeave = "node_leave" + eventNodeUpdate = "node_update" + eventNodeConflict = "node_conflict" +) + +const clusterNameLabel = "cluster_name" + +// metrics holds the set of metrics for a Node. Additional Collectors can be +// registered by calling Add. +type metrics struct { + metricsutil.Container + + gossipEventsTotal *prometheus.CounterVec + nodePeers *prometheus.GaugeVec + nodeUpdating prometheus.Gauge + nodeUpdateDuration prometheus.Histogram + nodeObservers prometheus.Gauge + nodeInfo *metricsutil.InfoCollector +} + +var _ prometheus.Collector = (*metrics)(nil) + +func newMetrics(clusterName string) *metrics { + var m metrics + + m.gossipEventsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "cluster_node_gossip_received_events_total", + Help: "Total number of gossip messages handled by the node.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, []string{"event"}) + + m.nodePeers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Name: "cluster_node_peers", + Help: "Current number of healthy peers by state", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, []string{"state"}) + + m.nodeUpdating = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_node_updating", + Help: "1 if the node is currently processing a change to the cluster state.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }) + + m.nodeUpdateDuration = prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "cluster_node_update_duration_seconds", + Help: "Histogram of the latency it took to process a change to the cluster state.", + Buckets: prometheus.DefBuckets, + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }) + + m.nodeObservers = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "cluster_node_update_observers", + Help: "Number of internal observers waiting for changes to cluster state.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }) + + m.nodeInfo = metricsutil.NewInfoCollector(metricsutil.InfoOpts{ + Name: "cluster_node_info", + Help: "Info about the local node. Label values will change as the node changes state.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, "state") + + m.Add( + m.gossipEventsTotal, + m.nodePeers, + m.nodeUpdating, + m.nodeUpdateDuration, + m.nodeObservers, + m.nodeInfo, + ) + + return &m +} + +func newMemberlistCollector(ml *memberlist.Memberlist, clusterName string) prometheus.Collector { + var container metricsutil.Container + + gossipProtoVersion := prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "cluster_node_gossip_proto_version", + Help: "Gossip protocol version used by nodes to maintain the cluster", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, func() float64 { + // NOTE(rfratto): while this is static at the time of writing, the internal + // documentation for memberlist claims that ProtocolVersion may one day be + // updated at runtime. + return float64(ml.ProtocolVersion()) + }) + + gossipHealthScore := prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "cluster_node_gossip_health_score", + Help: "Health value of a node; lower values means healthier. 0 is the minimum.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, func() float64 { + return float64(ml.GetHealthScore()) + }) + + gossipPeers := prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "cluster_node_gossip_alive_peers", + Help: "How many alive gossip peers a node has, including the local node.", + ConstLabels: prometheus.Labels{ + clusterNameLabel: clusterName, + }, + }, func() float64 { + return float64(ml.NumMembers()) + }) + + container.Add( + gossipProtoVersion, + gossipHealthScore, + gossipPeers, + ) + + return &container +} diff --git a/vendor/github.com/grafana/ckit/node.go b/vendor/github.com/grafana/ckit/node.go new file mode 100644 index 0000000000000..9404ed8078fbb --- /dev/null +++ b/vendor/github.com/grafana/ckit/node.go @@ -0,0 +1,840 @@ +package ckit + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "sort" + "sync" + "time" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/hashicorp/go-msgpack/codec" + "github.com/hashicorp/memberlist" + "github.com/prometheus/client_golang/prometheus" + + "github.com/grafana/ckit/internal/gossiphttp" + "github.com/grafana/ckit/internal/lamport" + "github.com/grafana/ckit/internal/messages" + "github.com/grafana/ckit/internal/queue" + "github.com/grafana/ckit/peer" + "github.com/grafana/ckit/shard" +) + +var ( + // ErrStopped is returned by invoking methods against Node when it is + // stopped. + ErrStopped = errors.New("node stopped") +) + +// StateTransitionError is returned when a node requests an invalid state +// transition. +type StateTransitionError struct { + From, To peer.State +} + +// Error implements error. +func (e StateTransitionError) Error() string { + return fmt.Sprintf("invalid transition from %s to %s", e.From, e.To) +} + +// Config configures a Node within the cluster. +type Config struct { + // Name of the Node. Must be unique across the cluster. Required. + Name string + + // host:port address other nodes should use to connect to this Node. + // Required. + AdvertiseAddr string + + // Optional logger to use. + Log log.Logger + + // Optional sharder to synchronize cluster changes to. Synchronization of the + // Sharder happens prior to Observers being notified of changes. + Sharder shard.Sharder + + // Optional identifier to prevent clusters from accidentally merging. + // Nodes are prevented from joining a cluster with an explicit label if + // they do not share the same label. + Label string + + // EnableTLS optionally specifies whether TLS should be + // used for communication between peers. + // Defaults to false. + EnableTLS bool +} + +func (c *Config) validate() error { + if len(c.Name) == 0 { + return fmt.Errorf("node name is required") + } + + if len(c.AdvertiseAddr) == 0 { + return fmt.Errorf("advertise address is required") + } + + if c.Log == nil { + c.Log = log.NewNopLogger() + } + + return nil +} + +// A Node is a participant in a cluster. Nodes keep track of all of their peers +// and emit events to Observers when the cluster state changes. +type Node struct { + log log.Logger + cfg Config + ml *memberlist.Memberlist + broadcasts memberlist.TransmitLimitedQueue // Make sure peerMut isn't held when updating + notifyObserversQueue *queue.Queue + m *metrics + baseRoute string + handler http.Handler + + // The clock for the node. Nodes have their own clock for the sake of + // testing; using the global clock could cause clock synchronization issues + // to be missed if you use multiple in-process nodes. + clock lamport.Clock + + stateMut sync.RWMutex + localState peer.State + + shutdownMut sync.Mutex + runCancel context.CancelFunc + stopped bool + + observersMut sync.Mutex + observers []Observer + + // peerStates is updated any time a messages.State broadcast is received, and + // may have keys for node names that do not exist in the peers map. These + // keys get gradually cleaned up during local state synchronization. + // + // Use peers for the definitive list of current peers. + + // TODO(rfratto): should this block be replaced with a single struct that + // supports updating peers in-place? + + peerMut sync.RWMutex + peerStates map[string]messages.State // State lookup for a node name + peers map[string]peer.Peer // Current list of peers & their states + peerCache []peer.Peer // Slice version of peers; keep in sync with peers +} + +// NewNode creates an unstarted Node to participulate in a cluster. An error +// will be returned if the provided config is invalid. +// +// Before starting the Node, the caller has to wire up the Node's HTTP handlers +// on the base route provided by the Handler method. +// +// If Node is intended to be reachable over non-TLS HTTP/2 connections, then +// the http.Server the routes are registered on must make use of the +// golang.org/x/net/http2/h2c package to enable upgrading incoming plain HTTP +// connections to HTTP/2. +// +// Similarly, if the Node is intended to initiate non-TLS outgoing connections, +// the provided cli should be configured properly (with AllowHTTP set to true +// and using a custom DialTLS function to create a non-TLS net.Conn). +func NewNode(cli *http.Client, cfg Config) (*Node, error) { + if err := cfg.validate(); err != nil { + return nil, err + } + + advertiseAddr, advertisePortString, err := net.SplitHostPort(cfg.AdvertiseAddr) + if err != nil { + return nil, fmt.Errorf("failed to read advertise address: %w", err) + } + + advertiseIP, err := net.ResolveIPAddr("ip", advertiseAddr) + if err != nil { + return nil, fmt.Errorf("failed to lookup advertise address %q: %w", advertiseAddr, err) + } + + advertisePort, err := net.LookupPort("tcp", advertisePortString) + if err != nil { + return nil, fmt.Errorf("failed to parse advertise port %q: %w", advertisePortString, err) + } + + httpTransport, transportMetrics, err := gossiphttp.NewTransport(gossiphttp.Options{ + Log: cfg.Log, + Client: cli, + PacketTimeout: 1 * time.Second, + UseHTTPS: cfg.EnableTLS, + }) + if err != nil { + return nil, fmt.Errorf("failed to build transport: %w", err) + } + + baseRoute, handler := httpTransport.Handler() + + mlc := memberlist.DefaultLANConfig() + mlc.Name = cfg.Name + mlc.Transport = httpTransport + mlc.AdvertiseAddr = advertiseIP.String() + mlc.AdvertisePort = advertisePort + mlc.Label = cfg.Label + + if cfg.Log != nil { + mlc.Logger = newMemberListLogger(log.With(cfg.Log, "subsystem", "memberlist")) + } else { + mlc.LogOutput = io.Discard + } + + n := &Node{ + log: cfg.Log, + cfg: cfg, + m: newMetrics(mlc.Label), + + notifyObserversQueue: queue.New(1), + + peerStates: make(map[string]messages.State), + peers: make(map[string]peer.Peer), + + baseRoute: baseRoute, + handler: handler, + } + + nd := &nodeDelegate{Node: n} + mlc.Events = nd + mlc.Delegate = nd + mlc.Conflict = nd + + ml, err := memberlist.Create(mlc) + if err != nil { + return nil, fmt.Errorf("failed to create memberlist: %w", err) + } + + n.ml = ml + n.broadcasts.NumNodes = func() int { return len(n.Peers()) } + n.broadcasts.RetransmitMult = mlc.RetransmitMult + + // Include some extra metrics. + n.m.Add( + newMemberlistCollector(ml, mlc.Label), + transportMetrics, + prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "cluster_node_lamport_time", + Help: "The current lamport time of the node.", + }, func() float64 { + return float64(n.clock.Now()) + }), + ) + + return n, nil +} + +// Metrics returns a prometheus.Collector that can be used to collect metrics +// about the Node. +func (n *Node) Metrics() prometheus.Collector { return n.m } + +// Handler returns the base route and http.Handler used by the Node for +// communicating over HTTP/2. +// +// The base route and handler must be configured properly by registering them +// with an HTTP server before starting the Node. +func (n *Node) Handler() (string, http.Handler) { return n.baseRoute, n.handler } + +// Start starts the Node with a set of peers to connect to. Start may be called +// multiple times to add additional peers into the memberlist. +// +// Start may not be called after [Stop] has been called. +func (n *Node) Start(peers []string) error { + n.shutdownMut.Lock() + defer n.shutdownMut.Unlock() + + if n.stopped { + // n.ml can't be re-used after we stopped, so we need to force error the + // Start. + // + // TODO: maybe create a new n.ml instead? + return ErrStopped + } + + if n.runCancel == nil { + ctx, cancel := context.WithCancel(context.Background()) + go n.run(ctx) + n.runCancel = cancel + } + + _, err := n.ml.Join(peers) + if err != nil { + return fmt.Errorf("failed to join memberlist: %w", err) + } + + // Broadcast our current state of the node to all peers now that our lamport + // clock is roughly synchronized. + return n.broadcastCurrentState() +} + +func (n *Node) run(ctx context.Context) { + var lastPeers []peer.Peer + + for { + v, err := n.notifyObserversQueue.Dequeue(ctx) + if err != nil { + break + } + peers := v.([]peer.Peer) + + // Ignore events if the peer set hasn't changed. + if peersEqual(lastPeers, peers) { + continue + } + lastPeers = peers + + n.notifyObservers(peers) + } +} + +// broadcastCurrentState queues a message to send the current state of the node +// to the cluster. This should be done after joining a new set of nodes once +// the lamport clock is synchronized. +func (n *Node) broadcastCurrentState() error { + n.stateMut.RLock() + defer n.stateMut.RUnlock() + + stateMsg := messages.State{ + NodeName: n.cfg.Name, + NewState: n.localState, + Time: n.clock.Tick(), + } + + // Treat the stateMsg as if it was received externally to track our own state + // along with other nodes. + n.handleStateMessage(stateMsg) + + bcast, err := messages.Broadcast(&stateMsg, nil) + if err != nil { + return err + } + n.broadcasts.QueueBroadcast(bcast) + return nil +} + +// Stop stops the Node, removing it from the cluster. Callers should first +// first transition to StateTerminating to gracefully leave the cluster. +// Observers will no longer be notified about cluster changes after Stop +// returns. +func (n *Node) Stop() error { + n.shutdownMut.Lock() + defer n.shutdownMut.Unlock() + + if n.runCancel != nil { + n.runCancel() + n.runCancel = nil + } + + if n.stopped { + // n.ml.Leave will panic if being called twice. We'll be defensive and + // prevent anything from happening here. + return nil + } + n.stopped = true + + // TODO(rfratto): configurable leave timeout + leaveTimeout := time.Second * 5 + if err := n.ml.Leave(leaveTimeout); err != nil { + level.Error(n.log).Log("msg", "failed to broadcast leave message to cluster", "err", err) + } + return n.ml.Shutdown() +} + +// CurrentState returns n's current State. Other nodes may not have the same +// State value for n as the current state propagates throughout the cluster. +func (n *Node) CurrentState() peer.State { + n.stateMut.RLock() + defer n.stateMut.RUnlock() + + return n.localState +} + +// ChangeState changes the state of the node. ChangeState will block until the +// message has been broadcast or until the provided ctx is canceled. Canceling +// the context does not stop the message from being broadcast; it just stops +// waiting for it. +// +// The "to" state must be valid to move to from the current state. Acceptable +// transitions are: +// +// StateViewer -> StateParticipant +// StateParticipant -> StateTerminating +// +// Nodes intended to only be viewers should never transition to another state. +func (n *Node) ChangeState(ctx context.Context, to peer.State) error { + n.stateMut.Lock() + defer n.stateMut.Unlock() + + t := stateTransition{From: n.localState, To: to} + if _, valid := validStateTransitions[t]; !valid { + return StateTransitionError(t) + } + + level.Debug(n.log).Log("msg", "changing node state", "from", n.localState, "to", to) + return n.waitChangeState(ctx, to) +} + +type stateTransition struct{ From, To peer.State } + +var validStateTransitions = map[stateTransition]struct{}{ + {peer.StateViewer, peer.StateParticipant}: {}, + {peer.StateParticipant, peer.StateTerminating}: {}, +} + +func (n *Node) waitChangeState(ctx context.Context, to peer.State) error { + waitBroadcast := make(chan struct{}, 1) + afterBroadcast := func() { + select { + case waitBroadcast <- struct{}{}: + default: + } + } + + if err := n.changeState(to, afterBroadcast); err != nil { + return err + } + + // We need at least one remote peer to broadcast the state change to. If it's + // just us, we can return immediately. + n.peerMut.RLock() + hasPeers := len(n.peers) > 1 + n.peerMut.RUnlock() + + if !hasPeers { + return nil + } + + select { + case <-ctx.Done(): + return ctx.Err() + case <-waitBroadcast: + return nil + } +} + +func (n *Node) changeState(to peer.State, onDone func()) error { + n.localState = to + n.m.nodeInfo.MustSet("state", to.String()) + + stateMsg := messages.State{ + NodeName: n.cfg.Name, + NewState: n.localState, + Time: n.clock.Tick(), + } + + // Treat the stateMsg as if it was received externally to track our own state + // along with other nodes. + n.handleStateMessage(stateMsg) + + bcast, err := messages.Broadcast(&stateMsg, onDone) + if err != nil { + return err + } + n.broadcasts.QueueBroadcast(bcast) + return nil +} + +// handleStateMessage handles a state message from a peer. Returns true if the +// message hasn't been seen before. +// +// handleStateMessage must be called with n.stateMut held for reading. +func (n *Node) handleStateMessage(msg messages.State) (newMessage bool) { + n.clock.Observe(msg.Time) + + n.peerMut.Lock() + defer n.peerMut.Unlock() + + curr, exist := n.peerStates[msg.NodeName] + if exist && msg.Time <= curr.Time { + // Ignore a state message if we have the same or a newer one. + return false + } else if exist && msg.NodeName == n.cfg.Name { + level.Debug(n.log).Log("msg", "got stale message about self", "msg", msg) + + // A peer has a newer message about ourselves, likely from a previous + // instance of the process. We'll ignore the message and replace it with a + // newer message reflecting our current state. + msg = messages.State{ + NodeName: n.cfg.Name, + NewState: n.localState, + Time: n.clock.Tick(), + } + } else { + level.Debug(n.log).Log("msg", "handling state message", "msg", msg) + } + + n.peerStates[msg.NodeName] = msg + + if p, ok := n.peers[msg.NodeName]; ok { + p.State = msg.NewState + n.peers[msg.NodeName] = p + n.handlePeersChanged() + } + + return true +} + +// Peers returns all Peers currently known by n. The Peers list will include +// peers regardless of their current State. The returned slice should not be +// modified. +func (n *Node) Peers() []peer.Peer { + n.peerMut.RLock() + defer n.peerMut.RUnlock() + return n.peerCache +} + +// handlePeersChanged should be called when the peers map is updated. The peer +// cache will be updated before notifying observers that peers have changed. +// +// peerMut should be held when this function is called. +func (n *Node) handlePeersChanged() { + var ( + newPeers = make([]peer.Peer, 0, len(n.peers)) + + peerCountByState = make(map[peer.State]int, len(peer.AllStates)) + ) + + for _, peer := range n.peers { + newPeers = append(newPeers, peer) + peerCountByState[peer.State]++ + } + + // Update the metric based on the peers we just processed. + for _, state := range peer.AllStates { + count := peerCountByState[state] + n.m.nodePeers.WithLabelValues(state.String()).Set(float64(count)) + } + + // Sort the new peers by name. + sort.Slice(newPeers, func(i, j int) bool { + return newPeers[i].Name < newPeers[j].Name + }) + + // Notify the sharder first if it's set. + if n.cfg.Sharder != nil { + n.cfg.Sharder.SetPeers(newPeers) + } + + n.peerCache = newPeers + n.notifyObserversQueue.Enqueue(newPeers) +} + +// Observe registers o to be informed when the cluster changes. o will be +// notified when a new peer is discovered, an existing peer shuts down, or the +// state of a peer changes. Observers are invoked in the order they were +// registered. +// +// Observers are notified in the background about the most recent state of the +// cluster, ignoring intermediate changed events that occurred while a +// long-running observer is still processing an older change. +func (n *Node) Observe(o Observer) { + n.observersMut.Lock() + defer n.observersMut.Unlock() + n.observers = append(n.observers, o) + n.m.nodeObservers.Set(float64(len(n.observers))) +} + +func (n *Node) notifyObservers(peers []peer.Peer) { + n.observersMut.Lock() + defer n.observersMut.Unlock() + + n.m.nodeUpdating.Set(1) + defer n.m.nodeUpdating.Set(0) + + timer := prometheus.NewTimer(n.m.nodeUpdateDuration) + defer timer.ObserveDuration() + + newObservers := make([]Observer, 0, len(n.observers)) + for _, o := range n.observers { + rereg := o.NotifyPeersChanged(peers) + if rereg { + newObservers = append(newObservers, o) + } + } + + n.observers = newObservers + n.m.nodeObservers.Set(float64(len(n.observers))) +} + +// nodeDelegate is used to implement memberlist.*Delegate types without +// exposing their methods publicly. +type nodeDelegate struct { + *Node +} + +// Delegate types nodeDelegate should implement +var ( + _ memberlist.Delegate = (*nodeDelegate)(nil) + _ memberlist.EventDelegate = (*nodeDelegate)(nil) + _ memberlist.ConflictDelegate = (*nodeDelegate)(nil) +) + +// +// memberlist.Delegate methods +// + +func (nd *nodeDelegate) NodeMeta(limit int) []byte { + // Nodes don't have any additional metadata to send; return nil. + return nil +} + +func (nd *nodeDelegate) NotifyMsg(raw []byte) { + buf, ty, err := messages.Parse(raw) + if err != nil { + level.Error(nd.log).Log("msg", "failed to parse gossip message", "ty", ty, "err", err) + return + } + + switch ty { + case messages.TypeState: + nd.m.gossipEventsTotal.WithLabelValues(eventStateChange).Inc() + + var s messages.State + if err := messages.Decode(buf, &s); err != nil { + level.Error(nd.log).Log("msg", "failed to decode state message", "err", err) + return + } + + // nd.handleStateMessage must be called with stateMut held. + nd.stateMut.RLock() + defer nd.stateMut.RUnlock() + + if nd.handleStateMessage(s) { + // We should continue gossiping the message to other peers if we haven't + // seen it before. + // + // We can ignore errors from the broadcast here. It shouldn't fail to + // encode since we just decoded it successfully, but even if it did fail, + // messages would still converge eventually using push/pulls. + bcast, _ := messages.Broadcast(&s, nil) + nd.broadcasts.QueueBroadcast(bcast) + } + + default: + nd.m.gossipEventsTotal.WithLabelValues(eventUnkownMessage).Inc() + + level.Warn(nd.log).Log("msg", "unexpected gossip message", "ty", ty) + } +} + +func (nd *nodeDelegate) GetBroadcasts(overhead, limit int) [][]byte { + return nd.broadcasts.GetBroadcasts(overhead, limit) +} + +func (nd *nodeDelegate) LocalState(join bool) []byte { + nd.peerMut.RLock() + defer nd.peerMut.RUnlock() + + nd.m.gossipEventsTotal.WithLabelValues(eventGetLocalState).Inc() + + ls := localState{ + CurrentTime: nd.clock.Now(), + NodeStates: make([]messages.State, 0, len(nd.peers)), + } + + // Our local state will have one NodeState for each peer we're currently + // aware of. This is different from each state we're aware of, since our + // nodeStates map may track states for nodes we haven't seen. + // + // Returning states for known peers allows MergeRemoteState to clean up + // nodeStates and remove entries for nodes that neither peer knows about. + for p := range nd.peers { + if s, hasState := nd.peerStates[p]; hasState { + ls.NodeStates = append(ls.NodeStates, s) + continue + } + + ls.NodeStates = append(ls.NodeStates, messages.State{ + NodeName: p, + NewState: peer.StateViewer, + Time: lamport.Time(0), + }) + } + + bb, err := encodeLocalState(&ls) + if err != nil { + level.Error(nd.log).Log("msg", "failed to encode local state", "err", err) + return nil + } + return bb +} + +func (nd *nodeDelegate) MergeRemoteState(buf []byte, join bool) { + rs, err := decodeLocalState(buf) + if err != nil { + level.Error(nd.log).Log("msg", "failed to decode remote state", "join", join, "err", err) + return + } + nd.clock.Observe(rs.CurrentTime) + level.Debug(nd.log).Log("msg", "merging remote state", "remote_time", rs.CurrentTime) + + // We'll be doing a full sync of state messages that another peer knows + // about. After the end of the full sync, we'll want to gossip new messages + // we've discovered to our peers. + var newMessages = make([]messages.State, 0, len(rs.NodeStates)) + defer func() { + // This must be done after we unlock nd.peerMut, since QueueBroadcast will + // call nd.Peers. + for _, msg := range newMessages { + bcast, _ := messages.Broadcast(&msg, nil) + nd.broadcasts.QueueBroadcast(bcast) + } + }() + + nd.peerMut.Lock() + defer nd.peerMut.Unlock() + + nd.m.gossipEventsTotal.WithLabelValues(eventMergeRemoteState).Inc() + + var ( + peersChanged bool + + // Map of remote states by name to optimize lookups. + remoteStates = make(map[string]messages.State, len(rs.NodeStates)) + ) + + // Merge in node states that the remote peer kept. + for _, msg := range rs.NodeStates { + // We don't use handleStateMessage here so we can defer recalculating peers + // to the end of the merge. + remoteStates[msg.NodeName] = msg + + curr, exist := nd.peerStates[msg.NodeName] + if exist && msg.Time <= curr.Time { + // Ignore a state message if we have a newer one. + continue + } else if msg.NodeName == nd.cfg.Name { + level.Debug(nd.log).Log("msg", "got stale message about self", "msg", msg) + + // Our remote peer has a newer message about ourselves, likely from a + // previous instance of the process. We'll ignore the message and replace + // it with a newer message reflecting our current state. + msg = messages.State{ + NodeName: nd.cfg.Name, + NewState: nd.CurrentState(), + Time: nd.clock.Tick(), + } + } else { + level.Debug(nd.log).Log("msg", "handling state message", "msg", msg) + } + + nd.peerStates[msg.NodeName] = msg + + if p, ok := nd.peers[msg.NodeName]; ok { + p.State = msg.NewState + nd.peers[msg.NodeName] = p + peersChanged = true + } + + newMessages = append(newMessages, msg) + } + + // Clean up stale entries in peerStates. + for nodeName := range nd.peerStates { + // If nodeName exists, it is not a stale reference. + if _, peerExists := nd.peers[nodeName]; peerExists { + continue + } + + // We don't know about this peer. If the remote state also doesn't have an + // entry for this peer, we can treat it as stale and delete it. + _, peerExistsRemote := remoteStates[nodeName] + if !peerExistsRemote { + level.Debug(nd.log).Log("msg", "deleting stale reference to node", "node", nodeName) + delete(nd.peerStates, nodeName) + } + } + + if peersChanged { + nd.handlePeersChanged() + } +} + +type localState struct { + // CurrentTime is the current lamport time. + CurrentTime lamport.Time + // NodeStates holds the set of states for all peers of a node. States may + // have a lamport time of 0 for nodes that have not broadcast a state yet. + NodeStates []messages.State +} + +func encodeLocalState(ls *localState) ([]byte, error) { + buf := bytes.NewBuffer(nil) + var handle codec.MsgpackHandle + enc := codec.NewEncoder(buf, &handle) + err := enc.Encode(ls) + return buf.Bytes(), err +} + +func decodeLocalState(buf []byte) (*localState, error) { + var ls localState + + r := bytes.NewReader(buf) + var handle codec.MsgpackHandle + dec := codec.NewDecoder(r, &handle) + err := dec.Decode(&ls) + return &ls, err +} + +// +// memberlist.EventDelegate methods +// + +func (nd *nodeDelegate) NotifyJoin(node *memberlist.Node) { + nd.peerMut.Lock() + defer nd.peerMut.Unlock() + + nd.m.gossipEventsTotal.WithLabelValues(eventNodeJoin).Inc() + nd.updatePeer(nd.nodeToPeer(node)) +} + +// nodeToPeer converts a memberlist Node to a Peer. Should only be called with +// peerMut held. +func (nd *nodeDelegate) nodeToPeer(node *memberlist.Node) peer.Peer { + return peer.Peer{ + Name: node.Name, + Addr: node.Address(), + Self: node.Name == nd.cfg.Name, + State: nd.peerStates[node.Name].NewState, + } +} + +func (nd *nodeDelegate) NotifyLeave(node *memberlist.Node) { + nd.peerMut.Lock() + defer nd.peerMut.Unlock() + + nd.m.gossipEventsTotal.WithLabelValues(eventNodeLeave).Inc() + nd.removePeer(node.Name) +} + +func (nd *nodeDelegate) NotifyUpdate(node *memberlist.Node) { + nd.peerMut.Lock() + defer nd.peerMut.Unlock() + + nd.m.gossipEventsTotal.WithLabelValues(eventNodeUpdate).Inc() + nd.updatePeer(nd.nodeToPeer(node)) +} + +func (nd *nodeDelegate) updatePeer(p peer.Peer) { + nd.peers[p.Name] = p + nd.handlePeersChanged() +} + +func (nd *nodeDelegate) removePeer(name string) { + delete(nd.peers, name) + nd.handlePeersChanged() +} + +// +// memberlist.ConflictDelegate methods +// + +func (nd *nodeDelegate) NotifyConflict(existing, other *memberlist.Node) { + nd.m.gossipEventsTotal.WithLabelValues(eventNodeConflict).Inc() +} diff --git a/vendor/github.com/grafana/ckit/observer.go b/vendor/github.com/grafana/ckit/observer.go new file mode 100644 index 0000000000000..a9ceaa2c4da60 --- /dev/null +++ b/vendor/github.com/grafana/ckit/observer.go @@ -0,0 +1,71 @@ +package ckit + +import ( + "sort" + + "github.com/grafana/ckit/peer" +) + +// An Observer watches a Node, waiting for its peers to change. +type Observer interface { + // NotifyPeersChanged is invoked any time the set of Peers for a node + // changes. The slice of peers should not be modified. + // + // The real list of peers may have changed; call Node.Peers to get the + // current list. + // + // If NotifyPeersChanged returns false, the Observer will no longer receive + // any notifications. This can be used for single-use watches. + NotifyPeersChanged(peers []peer.Peer) (reregister bool) +} + +// FuncObserver implements Observer. +type FuncObserver func(peers []peer.Peer) (reregister bool) + +// NotifyPeersChanged implements Observer. +func (f FuncObserver) NotifyPeersChanged(peers []peer.Peer) (reregister bool) { return f(peers) } + +// ParticipantObserver wraps an observer and filters out events where the list +// of peers in the Participants state haven't changed. When the set of +// participants have changed, next.NotifyPeersChanged will be invoked with the +// full set of peers (i.e., not just participants). +func ParticipantObserver(next Observer) Observer { + return &participantObserver{next: next} +} + +type participantObserver struct { + lastParticipants []peer.Peer // Participants ordered by name + next Observer +} + +func (po *participantObserver) NotifyPeersChanged(peers []peer.Peer) (reregister bool) { + // Filter peers down to those in StateParticipant. + participants := make([]peer.Peer, 0, len(peers)) + for _, p := range peers { + if p.State == peer.StateParticipant { + participants = append(participants, p) + } + } + sort.Slice(participants, func(i, j int) bool { return participants[i].Name < participants[j].Name }) + + if peersEqual(participants, po.lastParticipants) { + return true + } + + po.lastParticipants = participants + return po.next.NotifyPeersChanged(peers) +} + +func peersEqual(a, b []peer.Peer) bool { + if len(a) != len(b) { + return false + } + + for i := 0; i < len(a); i++ { + if a[i] != b[i] { + return false + } + } + + return true +} diff --git a/vendor/github.com/grafana/ckit/peer/peer.go b/vendor/github.com/grafana/ckit/peer/peer.go new file mode 100644 index 0000000000000..d75a8fa84e238 --- /dev/null +++ b/vendor/github.com/grafana/ckit/peer/peer.go @@ -0,0 +1,58 @@ +// Package peer describes a ckit peer. +package peer + +import "encoding/json" + +// Peer is a discovered node within the cluster. +type Peer struct { + Name string // Name of the Peer. Unique across the cluster. + Addr string // host:port address of the peer. + Self bool // True if Peer is the local Node. + State State // State of the peer. +} + +// String returns the name of p. +func (p Peer) String() string { return p.Name } + +// MarshalJSON implements [json.Marshaler]. +func (p Peer) MarshalJSON() ([]byte, error) { + type peerStatusJSON struct { + Name string `json:"name"` + Addr string `json:"addr"` + Self bool `json:"isSelf"` + State string `json:"state"` + } + return json.Marshal(&peerStatusJSON{ + Name: p.Name, + Addr: p.Addr, + Self: p.Self, + State: p.State.String(), + }) +} + +// UnmarshalJSON implements [json.Unmarshaler]. +func (p *Peer) UnmarshalJSON(b []byte) error { + type peerStatusJSON struct { + Name string `json:"name"` + Addr string `json:"addr"` + Self bool `json:"isSelf"` + State string `json:"state"` + } + + var psj peerStatusJSON + + if err := json.Unmarshal(b, &psj); err != nil { + return err + } + state, err := toState(psj.State) + if err != nil { + return err + } + + p.Name = psj.Name + p.Addr = psj.Addr + p.Self = psj.Self + p.State = state + + return nil +} diff --git a/vendor/github.com/grafana/ckit/peer/state.go b/vendor/github.com/grafana/ckit/peer/state.go new file mode 100644 index 0000000000000..8a38922216fe7 --- /dev/null +++ b/vendor/github.com/grafana/ckit/peer/state.go @@ -0,0 +1,57 @@ +package peer + +import "fmt" + +// State is used by Nodes to inform their peers what their role is as part of +// gossip. +type State uint + +const ( + // StateViewer is the default state. Nodes in the Viewer state have a + // read-only view of the cluster, and are never considered owners when + // hashing. + StateViewer State = iota + + // StateParticipant marks a node as available to receive writes. It will be + // considered a potential owner while hashing read or write operations. + StateParticipant + + // StateTerminating is used when a Participant node is shutting down. + // Terminating nodes are considered potential owners while hashing read + // operations. + StateTerminating +) + +// AllStates holds a list of all valid states. +var AllStates = [...]State{ + StateViewer, + StateParticipant, + StateTerminating, +} + +// String returns the string representation of s. +func (s State) String() string { + switch s { + case StateViewer: + return "viewer" + case StateParticipant: + return "participant" + case StateTerminating: + return "terminating" + default: + return fmt.Sprintf("<unknown state %d>", s) + } +} + +func toState(s string) (State, error) { + switch s { + case "viewer": + return StateViewer, nil + case "participant": + return StateParticipant, nil + case "terminating": + return StateTerminating, nil + } + + return 0, fmt.Errorf("unknown state %q", s) +} diff --git a/vendor/github.com/grafana/ckit/shard/key.go b/vendor/github.com/grafana/ckit/shard/key.go new file mode 100644 index 0000000000000..904baffd236f0 --- /dev/null +++ b/vendor/github.com/grafana/ckit/shard/key.go @@ -0,0 +1,37 @@ +package shard + +import "github.com/cespare/xxhash/v2" + +// A Key is used to identify the set of owners for some given objects. Keys +// may be constructed from a string by calling StringKey or by writing data +// through a KeyBuilder. +type Key uint64 + +// KeyBuilder generate Keys for performing hash lookup. To generate a Key, +// first write to the KeyBuilder, then call Key. The KeyBuilder can be re-used +// afterwards by calling Reset. KeyBuilder can not be used concurrently. +// +// KeyBuilder implements io.Writer. +type KeyBuilder struct { + dig *xxhash.Digest +} + +// NewKeyBuilder returns a new KeyBuilder that can generate keys. +func NewKeyBuilder() *KeyBuilder { return &KeyBuilder{dig: xxhash.New()} } + +// Write appends b to kb's state. Write always returns len(b), nil. +func (kb *KeyBuilder) Write(b []byte) (n int, err error) { return kb.dig.Write(b) } + +// Reset resets kb's state. +func (kb *KeyBuilder) Reset() { kb.dig.Reset() } + +// Key computes the key from kb's current state. +func (kb *KeyBuilder) Key() Key { return Key(kb.dig.Sum64()) } + +// StringKey generates a Key directly from a string. It is equivalent to +// writing the input string to a new KeyBuilder. +func StringKey(s string) Key { + // Don't go through KeyBuilder here; use xxhash.Sum64String directly which is + // more efficient for this use case but still produces equivalent results. + return Key(xxhash.Sum64String(s)) +} diff --git a/vendor/github.com/grafana/ckit/shard/shard.go b/vendor/github.com/grafana/ckit/shard/shard.go new file mode 100644 index 0000000000000..fd72715095e89 --- /dev/null +++ b/vendor/github.com/grafana/ckit/shard/shard.go @@ -0,0 +1,175 @@ +// Package shard implements a set of consistent hashing algorithms to determine +// ownership of a key within a cluster. +package shard + +import ( + "fmt" + "sort" + "sync" + + "github.com/grafana/ckit/internal/chash" + "github.com/grafana/ckit/peer" +) + +// Op is used to signify how a hash is intended to be used. +type Op uint8 + +const ( + // OpRead is used for read-only lookups. Only nodes in the Participant + // or Terminating state are considered. + OpRead Op = iota + // OpReadWrite is used for read or write lookups. Only nodes in the + // Participant state are considered. + OpReadWrite +) + +// String returns a string representation of the Op. +func (ht Op) String() string { + switch ht { + case OpRead: + return "Read" + case OpReadWrite: + return "ReadWrite" + default: + return fmt.Sprintf("Op(%d)", ht) + } +} + +// A Sharder can lookup the owner for a specific key. +type Sharder interface { + // Lookup returns numOwners Peers for the provided key. The provided op + // is used to determine which peers may be considered potential owners. + // + // An error will be returned if the type of eligible peers for the provided + // op is less than numOwners. + Lookup(key Key, numOwners int, op Op) ([]peer.Peer, error) + + // Peers gets the current set of non-viewer peers used for sharding. + Peers() []peer.Peer + + // SetPeers updates the set of peers used for sharding. Peers will be ignored + // if they are a viewer. + SetPeers(ps []peer.Peer) +} + +// chasher wraps around two chash.Hash and adds logic for Op. +type chasher struct { + peersMut sync.RWMutex + peers map[string]peer.Peer // Set of all peers shared across both hashes + + read, readWrite chash.Hash +} + +func (ch *chasher) Peers() []peer.Peer { + ch.peersMut.RLock() + defer ch.peersMut.RUnlock() + + ps := make([]peer.Peer, 0, len(ch.peers)) + for _, p := range ch.peers { + ps = append(ps, p) + } + sort.Slice(ps, func(i, j int) bool { return ps[i].Name < ps[j].Name }) + + return ps +} + +func (ch *chasher) SetPeers(ps []peer.Peer) { + sort.Slice(ps, func(i, j int) bool { return ps[i].Name < ps[j].Name }) + + var ( + newPeers = make(map[string]peer.Peer, len(ps)) + newRead = make([]string, 0, len(ps)) + newReadWrite = make([]string, 0, len(ps)) + ) + + for _, p := range ps { + // NOTE(rfratto): newRead and newReadWrite remain in sorted order since we + // append to them from the already-sorted ps slice. + switch p.State { + case peer.StateParticipant: + newRead = append(newRead, p.Name) + newReadWrite = append(newReadWrite, p.Name) + newPeers[p.Name] = p + case peer.StateTerminating: + newRead = append(newRead, p.Name) + newPeers[p.Name] = p + } + } + + ch.peersMut.Lock() + defer ch.peersMut.Unlock() + + ch.peers = newPeers + ch.read.SetNodes(newRead) + ch.readWrite.SetNodes(newReadWrite) +} + +func (ch *chasher) Lookup(key Key, numOwners int, op Op) ([]peer.Peer, error) { + ch.peersMut.RLock() + defer ch.peersMut.RUnlock() + + var ( + names []string + err error + ) + + switch op { + case OpRead: + names, err = ch.read.Get(uint64(key), numOwners) + case OpReadWrite: + names, err = ch.readWrite.Get(uint64(key), numOwners) + default: + return nil, fmt.Errorf("unknown op %s", op) + } + if err != nil { + return nil, err + } + + res := make([]peer.Peer, len(names)) + for i, name := range names { + p, ok := ch.peers[name] + if !ok { + panic("Unexpected peer " + name) + } + res[i] = p + } + return res, nil +} + +// Multiprobe implements a multi-probe sharder: https://arxiv.org/abs/1505.00062 +// +// Multiprobe is optimized for a median peak-to-average load ratio of 1.05. It +// performs a lookup in O(K * log N) time, where K is 21. +func Multiprobe() Sharder { + return &chasher{ + read: chash.Multiprobe(), + readWrite: chash.Multiprobe(), + } +} + +// Rendezvous returns a rendezvous sharder (HRW, Highest Random Weight). +// +// Rendezvous is optimized for excellent load distribution, but has a runtime +// complexity of O(N). +func Rendezvous() Sharder { + return &chasher{ + read: chash.Rendezvous(), + readWrite: chash.Rendezvous(), + } +} + +// Ring implements a ring sharder. numTokens determines how many tokens each +// node should have. Tokens are mapped to the unit circle, and then ownership +// of a key is determined by finding the next token on the unit circle. If two +// nodes have the same token, the node that lexicographically comes first will +// be used as the first owner. +// +// Ring is extremely fast, running in O(log N) time, but increases in memory +// usage as numTokens increases. Low values of numTokens will cause poor +// distribution; 256 or 512 is a good starting point. +func Ring(numTokens int) Sharder { + return &chasher{ + read: chash.Ring(numTokens), + readWrite: chash.Ring(numTokens), + } +} diff --git a/vendor/github.com/hashicorp/go-msgpack/LICENSE b/vendor/github.com/hashicorp/go-msgpack/LICENSE index 95a0f0541cdaa..ccae99f6a9a30 100644 --- a/vendor/github.com/hashicorp/go-msgpack/LICENSE +++ b/vendor/github.com/hashicorp/go-msgpack/LICENSE @@ -1,22 +1,25 @@ -The MIT License (MIT) - -Copyright (c) 2012-2015 Ugorji Nwoke. +Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the author nor the names of its contributors may be used + to endorse or promote products derived from this software + without specific prior written permission. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go new file mode 100644 index 0000000000000..c14d810a73e81 --- /dev/null +++ b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go @@ -0,0 +1,143 @@ +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. + +/* +High Performance, Feature-Rich Idiomatic Go encoding library for msgpack and binc . + +Supported Serialization formats are: + + - msgpack: [https://github.com/msgpack/msgpack] + - binc: [http://github.com/ugorji/binc] + +To install: + + go get github.com/ugorji/go/codec + +The idiomatic Go support is as seen in other encoding packages in +the standard library (ie json, xml, gob, etc). + +Rich Feature Set includes: + + - Simple but extremely powerful and feature-rich API + - Very High Performance. + Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X. + This was achieved by taking extreme care on: + - managing allocation + - function frame size (important due to Go's use of split stacks), + - reflection use (and by-passing reflection for common types) + - recursion implications + - zero-copy mode (encoding/decoding to byte slice without using temp buffers) + - Correct. + Care was taken to precisely handle corner cases like: + overflows, nil maps and slices, nil value in stream, etc. + - Efficient zero-copying into temporary byte buffers + when encoding into or decoding from a byte slice. + - Standard field renaming via tags + - Encoding from any value + (struct, slice, map, primitives, pointers, interface{}, etc) + - Decoding into pointer to any non-nil typed value + (struct, slice, map, int, float32, bool, string, reflect.Value, etc) + - Supports extension functions to handle the encode/decode of custom types + - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler + - Schema-less decoding + (decode into a pointer to a nil interface{} as opposed to a typed non-nil value). + Includes Options to configure what specific map or slice type to use + when decoding an encoded list or map into a nil interface{} + - Provides a RPC Server and Client Codec for net/rpc communication protocol. + - Msgpack Specific: + - Provides extension functions to handle spec-defined extensions (binary, timestamp) + - Options to resolve ambiguities in handling raw bytes (as string or []byte) + during schema-less decoding (decoding into a nil interface{}) + - RPC Server/Client Codec for msgpack-rpc protocol defined at: + https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md + - Fast Paths for some container types: + For some container types, we circumvent reflection and its associated overhead + and allocation costs, and encode/decode directly. These types are: + []interface{} + []int + []string + map[interface{}]interface{} + map[int]interface{} + map[string]interface{} + +Extension Support + +Users can register a function to handle the encoding or decoding of +their custom types. + +There are no restrictions on what the custom type can be. Some examples: + + type BisSet []int + type BitSet64 uint64 + type UUID string + type MyStructWithUnexportedFields struct { a int; b bool; c []int; } + type GifImage struct { ... } + +As an illustration, MyStructWithUnexportedFields would normally be +encoded as an empty map because it has no exported fields, while UUID +would be encoded as a string. However, with extension support, you can +encode any of these however you like. + +RPC + +RPC Client and Server Codecs are implemented, so the codecs can be used +with the standard net/rpc package. + +Usage + +Typical usage model: + + // create and configure Handle + var ( + bh codec.BincHandle + mh codec.MsgpackHandle + ) + + mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) + + // configure extensions + // e.g. for msgpack, define functions and enable Time support for tag 1 + // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn) + + // create and use decoder/encoder + var ( + r io.Reader + w io.Writer + b []byte + h = &bh // or mh to use msgpack + ) + + dec = codec.NewDecoder(r, h) + dec = codec.NewDecoderBytes(b, h) + err = dec.Decode(&v) + + enc = codec.NewEncoder(w, h) + enc = codec.NewEncoderBytes(&b, h) + err = enc.Encode(v) + + //RPC Server + go func() { + for { + conn, err := listener.Accept() + rpcCodec := codec.GoRpc.ServerCodec(conn, h) + //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) + rpc.ServeCodec(rpcCodec) + } + }() + + //RPC Communication (client side) + conn, err = net.Dial("tcp", "localhost:5555") + rpcCodec := codec.GoRpc.ClientCodec(conn, h) + //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) + client := rpc.NewClientWithCodec(rpcCodec) + +Representative Benchmark Results + +Run the benchmark suite using: + go test -bi -bench=. -benchmem + +To run full benchmark suite (including against vmsgpack and bson), +see notes in ext_dep_test.go + +*/ +package codec diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/README.md b/vendor/github.com/hashicorp/go-msgpack/codec/README.md new file mode 100644 index 0000000000000..6c95d1bfd2081 --- /dev/null +++ b/vendor/github.com/hashicorp/go-msgpack/codec/README.md @@ -0,0 +1,174 @@ +# Codec + +High Performance and Feature-Rich Idiomatic Go Library providing +encode/decode support for different serialization formats. + +Supported Serialization formats are: + + - msgpack: [https://github.com/msgpack/msgpack] + - binc: [http://github.com/ugorji/binc] + +To install: + + go get github.com/ugorji/go/codec + +Online documentation: [http://godoc.org/github.com/ugorji/go/codec] + +The idiomatic Go support is as seen in other encoding packages in +the standard library (ie json, xml, gob, etc). + +Rich Feature Set includes: + + - Simple but extremely powerful and feature-rich API + - Very High Performance. + Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X. + This was achieved by taking extreme care on: + - managing allocation + - function frame size (important due to Go's use of split stacks), + - reflection use (and by-passing reflection for common types) + - recursion implications + - zero-copy mode (encoding/decoding to byte slice without using temp buffers) + - Correct. + Care was taken to precisely handle corner cases like: + overflows, nil maps and slices, nil value in stream, etc. + - Efficient zero-copying into temporary byte buffers + when encoding into or decoding from a byte slice. + - Standard field renaming via tags + - Encoding from any value + (struct, slice, map, primitives, pointers, interface{}, etc) + - Decoding into pointer to any non-nil typed value + (struct, slice, map, int, float32, bool, string, reflect.Value, etc) + - Supports extension functions to handle the encode/decode of custom types + - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler + - Schema-less decoding + (decode into a pointer to a nil interface{} as opposed to a typed non-nil value). + Includes Options to configure what specific map or slice type to use + when decoding an encoded list or map into a nil interface{} + - Provides a RPC Server and Client Codec for net/rpc communication protocol. + - Msgpack Specific: + - Provides extension functions to handle spec-defined extensions (binary, timestamp) + - Options to resolve ambiguities in handling raw bytes (as string or []byte) + during schema-less decoding (decoding into a nil interface{}) + - RPC Server/Client Codec for msgpack-rpc protocol defined at: + https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md + - Fast Paths for some container types: + For some container types, we circumvent reflection and its associated overhead + and allocation costs, and encode/decode directly. These types are: + []interface{} + []int + []string + map[interface{}]interface{} + map[int]interface{} + map[string]interface{} + +## Extension Support + +Users can register a function to handle the encoding or decoding of +their custom types. + +There are no restrictions on what the custom type can be. Some examples: + + type BisSet []int + type BitSet64 uint64 + type UUID string + type MyStructWithUnexportedFields struct { a int; b bool; c []int; } + type GifImage struct { ... } + +As an illustration, MyStructWithUnexportedFields would normally be +encoded as an empty map because it has no exported fields, while UUID +would be encoded as a string. However, with extension support, you can +encode any of these however you like. + +## RPC + +RPC Client and Server Codecs are implemented, so the codecs can be used +with the standard net/rpc package. + +## Usage + +Typical usage model: + + // create and configure Handle + var ( + bh codec.BincHandle + mh codec.MsgpackHandle + ) + + mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) + + // configure extensions + // e.g. for msgpack, define functions and enable Time support for tag 1 + // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn) + + // create and use decoder/encoder + var ( + r io.Reader + w io.Writer + b []byte + h = &bh // or mh to use msgpack + ) + + dec = codec.NewDecoder(r, h) + dec = codec.NewDecoderBytes(b, h) + err = dec.Decode(&v) + + enc = codec.NewEncoder(w, h) + enc = codec.NewEncoderBytes(&b, h) + err = enc.Encode(v) + + //RPC Server + go func() { + for { + conn, err := listener.Accept() + rpcCodec := codec.GoRpc.ServerCodec(conn, h) + //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) + rpc.ServeCodec(rpcCodec) + } + }() + + //RPC Communication (client side) + conn, err = net.Dial("tcp", "localhost:5555") + rpcCodec := codec.GoRpc.ClientCodec(conn, h) + //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) + client := rpc.NewClientWithCodec(rpcCodec) + +## Representative Benchmark Results + +A sample run of benchmark using "go test -bi -bench=. -benchmem": + + /proc/cpuinfo: Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz (HT) + + .............................................. + BENCHMARK INIT: 2013-10-16 11:02:50.345970786 -0400 EDT + To run full benchmark comparing encodings (MsgPack, Binc, JSON, GOB, etc), use: "go test -bench=." + Benchmark: + Struct recursive Depth: 1 + ApproxDeepSize Of benchmark Struct: 4694 bytes + Benchmark One-Pass Run: + v-msgpack: len: 1600 bytes + bson: len: 3025 bytes + msgpack: len: 1560 bytes + binc: len: 1187 bytes + gob: len: 1972 bytes + json: len: 2538 bytes + .............................................. + PASS + Benchmark__Msgpack____Encode 50000 54359 ns/op 14953 B/op 83 allocs/op + Benchmark__Msgpack____Decode 10000 106531 ns/op 14990 B/op 410 allocs/op + Benchmark__Binc_NoSym_Encode 50000 53956 ns/op 14966 B/op 83 allocs/op + Benchmark__Binc_NoSym_Decode 10000 103751 ns/op 14529 B/op 386 allocs/op + Benchmark__Binc_Sym___Encode 50000 65961 ns/op 17130 B/op 88 allocs/op + Benchmark__Binc_Sym___Decode 10000 106310 ns/op 15857 B/op 287 allocs/op + Benchmark__Gob________Encode 10000 135944 ns/op 21189 B/op 237 allocs/op + Benchmark__Gob________Decode 5000 405390 ns/op 83460 B/op 1841 allocs/op + Benchmark__Json_______Encode 20000 79412 ns/op 13874 B/op 102 allocs/op + Benchmark__Json_______Decode 10000 247979 ns/op 14202 B/op 493 allocs/op + Benchmark__Bson_______Encode 10000 121762 ns/op 27814 B/op 514 allocs/op + Benchmark__Bson_______Decode 10000 162126 ns/op 16514 B/op 789 allocs/op + Benchmark__VMsgpack___Encode 50000 69155 ns/op 12370 B/op 344 allocs/op + Benchmark__VMsgpack___Decode 10000 151609 ns/op 20307 B/op 571 allocs/op + ok ugorji.net/codec 30.827s + +To run full benchmark suite (including against vmsgpack and bson), +see notes in ext\_dep\_test.go + diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/binc.go b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go index fd9f489063a6a..2bb5e8fee8548 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/binc.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go @@ -1,16 +1,20 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec import ( "math" - "reflect" + // "reflect" + // "sync/atomic" "time" + //"fmt" ) const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning. +//var _ = fmt.Printf + // vd as low 4 bits (there are 16 slots) const ( bincVdSpecial byte = iota @@ -55,79 +59,31 @@ const ( // others not currently supported ) -func bincdesc(vd, vs byte) string { - switch vd { - case bincVdSpecial: - switch vs { - case bincSpNil: - return "nil" - case bincSpFalse: - return "false" - case bincSpTrue: - return "true" - case bincSpNan, bincSpPosInf, bincSpNegInf, bincSpZeroFloat: - return "float" - case bincSpZero: - return "uint" - case bincSpNegOne: - return "int" - default: - return "unknown" - } - case bincVdSmallInt, bincVdPosInt: - return "uint" - case bincVdNegInt: - return "int" - case bincVdFloat: - return "float" - case bincVdSymbol: - return "string" - case bincVdString: - return "string" - case bincVdByteArray: - return "bytes" - case bincVdTimestamp: - return "time" - case bincVdCustomExt: - return "ext" - case bincVdArray: - return "array" - case bincVdMap: - return "map" - default: - return "unknown" - } -} - type bincEncDriver struct { - e *Encoder - h *BincHandle - w *encWriterSwitch + w encWriter m map[string]uint16 // symbols - b [16]byte // scratch, used for encoding numbers - bigendian style - s uint16 // symbols sequencer - // c containerState - encDriverTrackContainerWriter - noBuiltInTypes - // encNoSeparator - _ [1]uint64 // padding + s uint32 // symbols sequencer + b [8]byte } -func (e *bincEncDriver) EncodeNil() { - e.w.writen1(bincVdSpecial<<4 | bincSpNil) +func (e *bincEncDriver) isBuiltinType(rt uintptr) bool { + return rt == timeTypId } -func (e *bincEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - } else { - bs := bincEncodeTime(t) +func (e *bincEncDriver) encodeBuiltin(rt uintptr, v interface{}) { + switch rt { + case timeTypId: + bs := encodeTime(v.(time.Time)) e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs))) e.w.writeb(bs) } } -func (e *bincEncDriver) EncodeBool(b bool) { +func (e *bincEncDriver) encodeNil() { + e.w.writen1(bincVdSpecial<<4 | bincSpNil) +} + +func (e *bincEncDriver) encodeBool(b bool) { if b { e.w.writen1(bincVdSpecial<<4 | bincSpTrue) } else { @@ -135,21 +91,21 @@ func (e *bincEncDriver) EncodeBool(b bool) { } } -func (e *bincEncDriver) EncodeFloat32(f float32) { +func (e *bincEncDriver) encodeFloat32(f float32) { if f == 0 { e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) return } e.w.writen1(bincVdFloat<<4 | bincFlBin32) - bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f)) + e.w.writeUint32(math.Float32bits(f)) } -func (e *bincEncDriver) EncodeFloat64(f float64) { +func (e *bincEncDriver) encodeFloat64(f float64) { if f == 0 { e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) return } - bigen.PutUint64(e.b[:8], math.Float64bits(f)) + bigen.PutUint64(e.b[:], math.Float64bits(f)) if bincDoPrune { i := 7 for ; i >= 0 && (e.b[i] == 0); i-- { @@ -163,7 +119,7 @@ func (e *bincEncDriver) EncodeFloat64(f float64) { } } e.w.writen1(bincVdFloat<<4 | bincFlBin64) - e.w.writeb(e.b[:8]) + e.w.writeb(e.b[:]) } func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) { @@ -182,71 +138,64 @@ func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) } } -func (e *bincEncDriver) EncodeInt(v int64) { - // const nbd byte = bincVdNegInt << 4 - if v >= 0 { +func (e *bincEncDriver) encodeInt(v int64) { + const nbd byte = bincVdNegInt << 4 + switch { + case v >= 0: e.encUint(bincVdPosInt<<4, true, uint64(v)) - } else if v == -1 { + case v == -1: e.w.writen1(bincVdSpecial<<4 | bincSpNegOne) - } else { + default: e.encUint(bincVdNegInt<<4, false, uint64(-v)) } } -func (e *bincEncDriver) EncodeUint(v uint64) { +func (e *bincEncDriver) encodeUint(v uint64) { e.encUint(bincVdPosInt<<4, true, v) } func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) { - if v == 0 { + switch { + case v == 0: e.w.writen1(bincVdSpecial<<4 | bincSpZero) - } else if pos && v >= 1 && v <= 16 { + case pos && v >= 1 && v <= 16: e.w.writen1(bincVdSmallInt<<4 | byte(v-1)) - } else if v <= math.MaxUint8 { + case v <= math.MaxUint8: e.w.writen2(bd|0x0, byte(v)) - } else if v <= math.MaxUint16 { + case v <= math.MaxUint16: e.w.writen1(bd | 0x01) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { + e.w.writeUint16(uint16(v)) + case v <= math.MaxUint32: e.encIntegerPrune(bd, pos, v, 4) - } else { + default: e.encIntegerPrune(bd, pos, v, 8) } } -func (e *bincEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(rv) - if bs == nil { - e.EncodeNil() - return - } - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) -} - -func (e *bincEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) -} - func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) { e.encLen(bincVdCustomExt<<4, uint64(length)) e.w.writen1(xtag) } -func (e *bincEncDriver) WriteArrayStart(length int) { +func (e *bincEncDriver) encodeArrayPreamble(length int) { e.encLen(bincVdArray<<4, uint64(length)) - e.c = containerArrayStart } -func (e *bincEncDriver) WriteMapStart(length int) { +func (e *bincEncDriver) encodeMapPreamble(length int) { e.encLen(bincVdMap<<4, uint64(length)) - e.c = containerMapStart } -func (e *bincEncDriver) EncodeSymbol(v string) { +func (e *bincEncDriver) encodeString(c charEncoding, v string) { + l := uint64(len(v)) + e.encBytesLen(c, l) + if l > 0 { + e.w.writestr(v) + } +} + +func (e *bincEncDriver) encodeSymbol(v string) { // if WriteSymbolsNoRefs { - // e.encodeString(cUTF8, v) + // e.encodeString(c_UTF8, v) // return // } @@ -255,11 +204,12 @@ func (e *bincEncDriver) EncodeSymbol(v string) { //(bd with embedded length, and single byte for string val). l := len(v) - if l == 0 { - e.encBytesLen(cUTF8, 0) + switch l { + case 0: + e.encBytesLen(c_UTF8, 0) return - } else if l == 1 { - e.encBytesLen(cUTF8, 1) + case 1: + e.encBytesLen(c_UTF8, 1) e.w.writen1(v[0]) return } @@ -272,72 +222,45 @@ func (e *bincEncDriver) EncodeSymbol(v string) { e.w.writen2(bincVdSymbol<<4, byte(ui)) } else { e.w.writen1(bincVdSymbol<<4 | 0x8) - bigenHelper{e.b[:2], e.w}.writeUint16(ui) + e.w.writeUint16(ui) } } else { e.s++ - ui = e.s + ui = uint16(e.s) //ui = uint16(atomic.AddUint32(&e.s, 1)) e.m[v] = ui var lenprec uint8 - if l <= math.MaxUint8 { + switch { + case l <= math.MaxUint8: // lenprec = 0 - } else if l <= math.MaxUint16 { + case l <= math.MaxUint16: lenprec = 1 - } else if int64(l) <= math.MaxUint32 { + case int64(l) <= math.MaxUint32: lenprec = 2 - } else { + default: lenprec = 3 } if ui <= math.MaxUint8 { e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui)) } else { e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec) - bigenHelper{e.b[:2], e.w}.writeUint16(ui) + e.w.writeUint16(ui) } - if lenprec == 0 { + switch lenprec { + case 0: e.w.writen1(byte(l)) - } else if lenprec == 1 { - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l)) - } else if lenprec == 2 { - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l)) - } else { - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l)) + case 1: + e.w.writeUint16(uint16(l)) + case 2: + e.w.writeUint32(uint32(l)) + default: + e.w.writeUint64(uint64(l)) } e.w.writestr(v) } } -func (e *bincEncDriver) EncodeString(c charEncoding, v string) { - if e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 0 || e.h.AsSymbols == 1) { - e.EncodeSymbol(v) - return - } - l := uint64(len(v)) - e.encBytesLen(c, l) - if l > 0 { - e.w.writestr(v) - } -} - -func (e *bincEncDriver) EncodeStringEnc(c charEncoding, v string) { - if e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 0 || e.h.AsSymbols == 1) { - e.EncodeSymbol(v) - return - } - l := uint64(len(v)) - e.encLen(bincVdString<<4, l) // e.encBytesLen(c, l) - if l > 0 { - e.w.writestr(v) - } - -} - -func (e *bincEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - if v == nil { - e.EncodeNil() - return - } +func (e *bincEncDriver) encodeStringBytes(c charEncoding, v []byte) { l := uint64(len(v)) e.encBytesLen(c, l) if l > 0 { @@ -345,21 +268,9 @@ func (e *bincEncDriver) EncodeStringBytes(c charEncoding, v []byte) { } } -func (e *bincEncDriver) EncodeStringBytesRaw(v []byte) { - if v == nil { - e.EncodeNil() - return - } - l := uint64(len(v)) - e.encLen(bincVdByteArray<<4, l) // e.encBytesLen(c, l) - if l > 0 { - e.w.writeb(v) - } -} - func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) { //TODO: support bincUnicodeOther (for now, just use string or bytearray) - if c == cRAW { + if c == c_RAW { e.encLen(bincVdByteArray<<4, length) } else { e.encLen(bincVdString<<4, length) @@ -375,90 +286,93 @@ func (e *bincEncDriver) encLen(bd byte, l uint64) { } func (e *bincEncDriver) encLenNumber(bd byte, v uint64) { - if v <= math.MaxUint8 { + switch { + case v <= math.MaxUint8: e.w.writen2(bd, byte(v)) - } else if v <= math.MaxUint16 { + case v <= math.MaxUint16: e.w.writen1(bd | 0x01) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { + e.w.writeUint16(uint16(v)) + case v <= math.MaxUint32: e.w.writen1(bd | 0x02) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v)) - } else { + e.w.writeUint32(uint32(v)) + default: e.w.writen1(bd | 0x03) - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v)) + e.w.writeUint64(uint64(v)) } } //------------------------------------ -type bincDecSymbol struct { - s string - b []byte - i uint16 -} - type bincDecDriver struct { - decDriverNoopContainerReader - noBuiltInTypes - - d *Decoder - h *BincHandle - r *decReaderSwitch - br bool // bytes reader + r decReader bdRead bool + bdType valueType bd byte vd byte vs byte - _ [3]byte // padding - // linear searching on this slice is ok, - // because we typically expect < 32 symbols in each stream. - s []bincDecSymbol - - // noStreamingCodec - // decNoSeparator - - b [(8 + 1) * 8]byte // scratch + b [8]byte + m map[uint32]string // symbols (use uint32 as key, as map optimizes for it) } -func (d *bincDecDriver) readNextBd() { +func (d *bincDecDriver) initReadNext() { + if d.bdRead { + return + } d.bd = d.r.readn1() d.vd = d.bd >> 4 d.vs = d.bd & 0x0f d.bdRead = true -} - -func (d *bincDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *bincDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - if d.vd == bincVdSpecial && d.vs == bincSpNil { - return valueTypeNil - } else if d.vd == bincVdByteArray { - return valueTypeBytes - } else if d.vd == bincVdString { - return valueTypeString - } else if d.vd == bincVdArray { - return valueTypeArray - } else if d.vd == bincVdMap { - return valueTypeMap + d.bdType = valueTypeUnset +} + +func (d *bincDecDriver) currentEncodedType() valueType { + if d.bdType == valueTypeUnset { + switch d.vd { + case bincVdSpecial: + switch d.vs { + case bincSpNil: + d.bdType = valueTypeNil + case bincSpFalse, bincSpTrue: + d.bdType = valueTypeBool + case bincSpNan, bincSpNegInf, bincSpPosInf, bincSpZeroFloat: + d.bdType = valueTypeFloat + case bincSpZero: + d.bdType = valueTypeUint + case bincSpNegOne: + d.bdType = valueTypeInt + default: + decErr("currentEncodedType: Unrecognized special value 0x%x", d.vs) + } + case bincVdSmallInt: + d.bdType = valueTypeUint + case bincVdPosInt: + d.bdType = valueTypeUint + case bincVdNegInt: + d.bdType = valueTypeInt + case bincVdFloat: + d.bdType = valueTypeFloat + case bincVdString: + d.bdType = valueTypeString + case bincVdSymbol: + d.bdType = valueTypeSymbol + case bincVdByteArray: + d.bdType = valueTypeBytes + case bincVdTimestamp: + d.bdType = valueTypeTimestamp + case bincVdCustomExt: + d.bdType = valueTypeExt + case bincVdArray: + d.bdType = valueTypeArray + case bincVdMap: + d.bdType = valueTypeMap + default: + decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.vd) + } } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset + return d.bdType } -func (d *bincDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } +func (d *bincDecDriver) tryDecodeAsNil() bool { if d.bd == bincVdSpecial<<4|bincSpNil { d.bdRead = false return true @@ -466,24 +380,24 @@ func (d *bincDecDriver) TryDecodeAsNil() bool { return false } -func (d *bincDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { +func (d *bincDecDriver) isBuiltinType(rt uintptr) bool { + return rt == timeTypId +} + +func (d *bincDecDriver) decodeBuiltin(rt uintptr, v interface{}) { + switch rt { + case timeTypId: + if d.vd != bincVdTimestamp { + decErr("Invalid d.vd. Expecting 0x%x. Received: 0x%x", bincVdTimestamp, d.vd) + } + tt, err := decodeTime(d.r.readn(int(d.vs))) + if err != nil { + panic(err) + } + var vt *time.Time = v.(*time.Time) + *vt = tt d.bdRead = false - return } - if d.vd != bincVdTimestamp { - d.d.errorf("cannot decode time - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - t, err := bincDecodeTime(d.r.readx(uint(d.vs))) - if err != nil { - panic(err) - } - d.bdRead = false - return } func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) { @@ -492,8 +406,7 @@ func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) { } else { l := d.r.readn1() if l > 8 { - d.d.errorf("cannot read float - at most 8 bytes used to represent float - received %v bytes", l) - return + decErr("At most 8 bytes used to represent float. Received: %v bytes", l) } for i := l; i < 8; i++ { d.b[i] = 0 @@ -503,17 +416,16 @@ func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) { } func (d *bincDecDriver) decFloat() (f float64) { - //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; } - if x := d.vs & 0x7; x == bincFlBin32 { - d.decFloatPre(d.vs, 4) + //if true { f = math.Float64frombits(d.r.readUint64()); break; } + switch vs := d.vs; vs & 0x7 { + case bincFlBin32: + d.decFloatPre(vs, 4) f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4]))) - } else if x == bincFlBin64 { - d.decFloatPre(d.vs, 8) + case bincFlBin64: + d.decFloatPre(vs, 8) f = math.Float64frombits(bigen.Uint64(d.b[0:8])) - } else { - d.d.errorf("read float - only float32 and float64 are supported - %s %x-%x/%s", - msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + default: + decErr("only float32 and float64 are supported. d.vd: 0x%x, d.vs: 0x%x", d.vd, d.vs) } return } @@ -524,148 +436,130 @@ func (d *bincDecDriver) decUint() (v uint64) { case 0: v = uint64(d.r.readn1()) case 1: - d.r.readb(d.b[6:8]) - v = uint64(bigen.Uint16(d.b[6:8])) + d.r.readb(d.b[6:]) + v = uint64(bigen.Uint16(d.b[6:])) case 2: d.b[4] = 0 - d.r.readb(d.b[5:8]) - v = uint64(bigen.Uint32(d.b[4:8])) + d.r.readb(d.b[5:]) + v = uint64(bigen.Uint32(d.b[4:])) case 3: - d.r.readb(d.b[4:8]) - v = uint64(bigen.Uint32(d.b[4:8])) + d.r.readb(d.b[4:]) + v = uint64(bigen.Uint32(d.b[4:])) case 4, 5, 6: - lim := 7 - d.vs - d.r.readb(d.b[lim:8]) - for i := uint8(0); i < lim; i++ { + lim := int(7 - d.vs) + d.r.readb(d.b[lim:]) + for i := 0; i < lim; i++ { d.b[i] = 0 } - v = uint64(bigen.Uint64(d.b[:8])) + v = uint64(bigen.Uint64(d.b[:])) case 7: - d.r.readb(d.b[:8]) - v = uint64(bigen.Uint64(d.b[:8])) + d.r.readb(d.b[:]) + v = uint64(bigen.Uint64(d.b[:])) default: - d.d.errorf("unsigned integers with greater than 64 bits of precision not supported") - return + decErr("unsigned integers with greater than 64 bits of precision not supported") } return } -func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) { - if !d.bdRead { - d.readNextBd() - } - vd, vs := d.vd, d.vs - if vd == bincVdPosInt { +func (d *bincDecDriver) decIntAny() (ui uint64, i int64, neg bool) { + switch d.vd { + case bincVdPosInt: ui = d.decUint() - } else if vd == bincVdNegInt { + i = int64(ui) + case bincVdNegInt: ui = d.decUint() + i = -(int64(ui)) neg = true - } else if vd == bincVdSmallInt { + case bincVdSmallInt: + i = int64(d.vs) + 1 ui = uint64(d.vs) + 1 - } else if vd == bincVdSpecial { - if vs == bincSpZero { + case bincVdSpecial: + switch d.vs { + case bincSpZero: //i = 0 - } else if vs == bincSpNegOne { + case bincSpNegOne: neg = true ui = 1 - } else { - d.d.errorf("integer decode fails - invalid special value from descriptor %x-%x/%s", - d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + i = -1 + default: + decErr("numeric decode fails for special value: d.vs: 0x%x", d.vs) } - } else { - d.d.errorf("integer can only be decoded from int/uint. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd) - return + default: + decErr("number can only be decoded from uint or int values. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd) } return } -func (d *bincDecDriver) DecodeInt64() (i int64) { - ui, neg := d.decCheckInteger() - i = chkOvf.SignedIntV(ui) - if neg { - i = -i - } +func (d *bincDecDriver) decodeInt(bitsize uint8) (i int64) { + _, i, _ = d.decIntAny() + checkOverflow(0, i, bitsize) d.bdRead = false return } -func (d *bincDecDriver) DecodeUint64() (ui uint64) { - ui, neg := d.decCheckInteger() +func (d *bincDecDriver) decodeUint(bitsize uint8) (ui uint64) { + ui, i, neg := d.decIntAny() if neg { - d.d.errorf("assigning negative signed value to unsigned integer type") - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } + checkOverflow(ui, 0, bitsize) d.bdRead = false return } -func (d *bincDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - vd, vs := d.vd, d.vs - if vd == bincVdSpecial { +func (d *bincDecDriver) decodeFloat(chkOverflow32 bool) (f float64) { + switch d.vd { + case bincVdSpecial: d.bdRead = false - if vs == bincSpNan { + switch d.vs { + case bincSpNan: return math.NaN() - } else if vs == bincSpPosInf { + case bincSpPosInf: return math.Inf(1) - } else if vs == bincSpZeroFloat || vs == bincSpZero { + case bincSpZeroFloat, bincSpZero: return - } else if vs == bincSpNegInf { + case bincSpNegInf: return math.Inf(-1) - } else { - d.d.errorf("float - invalid special value from descriptor %x-%x/%s", - d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + default: + decErr("Invalid d.vs decoding float where d.vd=bincVdSpecial: %v", d.vs) } - } else if vd == bincVdFloat { + case bincVdFloat: f = d.decFloat() - } else { - f = float64(d.DecodeInt64()) + default: + _, i, _ := d.decIntAny() + f = float64(i) } + checkOverflowFloat32(f, chkOverflow32) d.bdRead = false return } // bool can be decoded from bool only (single byte). -func (d *bincDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == (bincVdSpecial | bincSpFalse) { +func (d *bincDecDriver) decodeBool() (b bool) { + switch d.bd { + case (bincVdSpecial | bincSpFalse): // b = false - } else if bd == (bincVdSpecial | bincSpTrue) { + case (bincVdSpecial | bincSpTrue): b = true - } else { - d.d.errorf("bool - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + default: + decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd) } d.bdRead = false return } -func (d *bincDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } +func (d *bincDecDriver) readMapLen() (length int) { if d.vd != bincVdMap { - d.d.errorf("map - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + decErr("Invalid d.vd for map. Expecting 0x%x. Got: 0x%x", bincVdMap, d.vd) } length = d.decLen() d.bdRead = false return } -func (d *bincDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } +func (d *bincDecDriver) readArrayLen() (length int) { if d.vd != bincVdArray { - d.d.errorf("array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + decErr("Invalid d.vd for array. Expecting 0x%x. Got: 0x%x", bincVdArray, d.vd) } length = d.decLen() d.bdRead = false @@ -673,299 +567,189 @@ func (d *bincDecDriver) ReadArrayStart() (length int) { } func (d *bincDecDriver) decLen() int { - if d.vs > 3 { - return int(d.vs - 4) + if d.vs <= 3 { + return int(d.decUint()) } - return int(d.decLenNumber()) + return int(d.vs - 4) } -func (d *bincDecDriver) decLenNumber() (v uint64) { - if x := d.vs; x == 0 { - v = uint64(d.r.readn1()) - } else if x == 1 { - d.r.readb(d.b[6:8]) - v = uint64(bigen.Uint16(d.b[6:8])) - } else if x == 2 { - d.r.readb(d.b[4:8]) - v = uint64(bigen.Uint32(d.b[4:8])) - } else { - d.r.readb(d.b[:8]) - v = bigen.Uint64(d.b[:8]) - } - return -} - -func (d *bincDecDriver) decStringAndBytes(bs []byte, withString, zerocopy bool) ( - bs2 []byte, s string) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return - } - var slen = -1 - // var ok bool +func (d *bincDecDriver) decodeString() (s string) { switch d.vd { case bincVdString, bincVdByteArray: - slen = d.decLen() - if zerocopy { - if d.br { - bs2 = d.r.readx(uint(slen)) - } else if len(bs) == 0 { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.b[:]) - } else { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) - } - } else { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) - } - if withString { - s = string(bs2) + if length := d.decLen(); length > 0 { + s = string(d.r.readn(length)) } case bincVdSymbol: - // zerocopy doesn't apply for symbols, - // as the values must be stored in a table for later use. - // //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision, //extract symbol //if containsStringVal, read it and put in map //else look in map for string value - var symbol uint16 + var symbol uint32 vs := d.vs + //fmt.Printf(">>>> d.vs: 0b%b, & 0x8: %v, & 0x4: %v\n", d.vs, vs & 0x8, vs & 0x4) if vs&0x8 == 0 { - symbol = uint16(d.r.readn1()) + symbol = uint32(d.r.readn1()) } else { - symbol = uint16(bigen.Uint16(d.r.readx(2))) + symbol = uint32(d.r.readUint16()) } - if d.s == nil { - d.s = make([]bincDecSymbol, 0, 16) + if d.m == nil { + d.m = make(map[uint32]string, 16) } if vs&0x4 == 0 { - for i := range d.s { - j := &d.s[i] - if j.i == symbol { - bs2 = j.b - if withString { - if j.s == "" && bs2 != nil { - j.s = string(bs2) - } - s = j.s - } - break - } - } + s = d.m[symbol] } else { + var slen int switch vs & 0x3 { case 0: slen = int(d.r.readn1()) case 1: - slen = int(bigen.Uint16(d.r.readx(2))) + slen = int(d.r.readUint16()) case 2: - slen = int(bigen.Uint32(d.r.readx(4))) + slen = int(d.r.readUint32()) case 3: - slen = int(bigen.Uint64(d.r.readx(8))) + slen = int(d.r.readUint64()) } - // since using symbols, do not store any part of - // the parameter bs in the map, as it might be a shared buffer. - // bs2 = decByteSlice(d.r, slen, bs) - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil) - if withString { - s = string(bs2) - } - d.s = append(d.s, bincDecSymbol{i: symbol, s: s, b: bs2}) + s = string(d.r.readn(slen)) + d.m[symbol] = s } default: - d.d.errorf("string/bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + decErr("Invalid d.vd for string. Expecting string:0x%x, bytearray:0x%x or symbol: 0x%x. Got: 0x%x", + bincVdString, bincVdByteArray, bincVdSymbol, d.vd) } d.bdRead = false return } -func (d *bincDecDriver) DecodeString() (s string) { - // DecodeBytes does not accommodate symbols, whose impl stores string version in map. - // Use decStringAndBytes directly. - // return string(d.DecodeBytes(d.b[:], true, true)) - _, s = d.decStringAndBytes(d.b[:], true, true) - return -} - -func (d *bincDecDriver) DecodeStringAsBytes() (s []byte) { - s, _ = d.decStringAndBytes(d.b[:], false, true) - return -} - -func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return nil - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.vd == bincVdArray { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } +func (d *bincDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) { var clen int - if d.vd == bincVdString || d.vd == bincVdByteArray { + switch d.vd { + case bincVdString, bincVdByteArray: clen = d.decLen() - } else { - d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(uint(clen)) - } else if len(bs) == 0 { - bs = d.b[:] + default: + decErr("Invalid d.vd for bytes. Expecting string:0x%x or bytearray:0x%x. Got: 0x%x", + bincVdString, bincVdByteArray, d.vd) + } + if clen > 0 { + // if no contents in stream, don't update the passed byteslice + if len(bs) != clen { + if len(bs) > clen { + bs = bs[:clen] + } else { + bs = make([]byte, clen) + } + bsOut = bs + changed = true } + d.r.readb(bs) } - return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs) -} - -func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) - } + d.bdRead = false return } -func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.vd == bincVdCustomExt { +func (d *bincDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) { + switch d.vd { + case bincVdCustomExt: l := d.decLen() xtag = d.r.readn1() if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag) - return - } - if d.br { - xbs = d.r.readx(uint(l)) - } else { - xbs = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:]) + decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag) } - } else if d.vd == bincVdByteArray { - xbs = d.DecodeBytes(nil, true) - } else { - d.d.errorf("ext - expecting extensions or byte array - %s %x-%x/%s", - msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return + xbs = d.r.readn(l) + case bincVdByteArray: + xbs, _ = d.decodeBytes(nil) + default: + decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.vd) } d.bdRead = false return } -func (d *bincDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.naked() - var decodeFurther bool +func (d *bincDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) { + d.initReadNext() switch d.vd { case bincVdSpecial: switch d.vs { case bincSpNil: - n.v = valueTypeNil + vt = valueTypeNil case bincSpFalse: - n.v = valueTypeBool - n.b = false + vt = valueTypeBool + v = false case bincSpTrue: - n.v = valueTypeBool - n.b = true + vt = valueTypeBool + v = true case bincSpNan: - n.v = valueTypeFloat - n.f = math.NaN() + vt = valueTypeFloat + v = math.NaN() case bincSpPosInf: - n.v = valueTypeFloat - n.f = math.Inf(1) + vt = valueTypeFloat + v = math.Inf(1) case bincSpNegInf: - n.v = valueTypeFloat - n.f = math.Inf(-1) + vt = valueTypeFloat + v = math.Inf(-1) case bincSpZeroFloat: - n.v = valueTypeFloat - n.f = float64(0) + vt = valueTypeFloat + v = float64(0) case bincSpZero: - n.v = valueTypeUint - n.u = uint64(0) // int8(0) + vt = valueTypeUint + v = int64(0) // int8(0) case bincSpNegOne: - n.v = valueTypeInt - n.i = int64(-1) // int8(-1) + vt = valueTypeInt + v = int64(-1) // int8(-1) default: - d.d.errorf("cannot infer value - unrecognized special value from descriptor %x-%x/%s", - d.vd, d.vs, bincdesc(d.vd, d.vs)) + decErr("decodeNaked: Unrecognized special value 0x%x", d.vs) } case bincVdSmallInt: - n.v = valueTypeUint - n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1 + vt = valueTypeUint + v = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1 case bincVdPosInt: - n.v = valueTypeUint - n.u = d.decUint() + vt = valueTypeUint + v = d.decUint() case bincVdNegInt: - n.v = valueTypeInt - n.i = -(int64(d.decUint())) + vt = valueTypeInt + v = -(int64(d.decUint())) case bincVdFloat: - n.v = valueTypeFloat - n.f = d.decFloat() + vt = valueTypeFloat + v = d.decFloat() case bincVdSymbol: - n.v = valueTypeSymbol - n.s = d.DecodeString() + vt = valueTypeSymbol + v = d.decodeString() case bincVdString: - n.v = valueTypeString - n.s = d.DecodeString() + vt = valueTypeString + v = d.decodeString() case bincVdByteArray: - decNakedReadRawBytes(d, d.d, n, d.h.RawToString) + vt = valueTypeBytes + v, _ = d.decodeBytes(nil) case bincVdTimestamp: - n.v = valueTypeTime - tt, err := bincDecodeTime(d.r.readx(uint(d.vs))) + vt = valueTypeTimestamp + tt, err := decodeTime(d.r.readn(int(d.vs))) if err != nil { panic(err) } - n.t = tt + v = tt case bincVdCustomExt: - n.v = valueTypeExt + vt = valueTypeExt l := d.decLen() - n.u = uint64(d.r.readn1()) - if d.br { - n.l = d.r.readx(uint(l)) - } else { - n.l = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:]) - } + var re RawExt + re.Tag = d.r.readn1() + re.Data = d.r.readn(l) + v = &re + vt = valueTypeExt case bincVdArray: - n.v = valueTypeArray + vt = valueTypeArray decodeFurther = true case bincVdMap: - n.v = valueTypeMap + vt = valueTypeMap decodeFurther = true default: - d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) + decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.vd) } if !decodeFurther { d.bdRead = false } - if n.v == valueTypeUint && d.h.SignedInteger { - n.v = valueTypeInt - n.i = int64(n.u) - } + return } //------------------------------------ @@ -980,224 +764,23 @@ func (d *bincDecDriver) DecodeNaked() { // extended precision and decimal IEEE 754 floats are unsupported. // - Only UTF-8 strings supported. // Unicode_Other Binc types (UTF16, UTF32) are currently unsupported. -// //Note that these EXCEPTIONS are temporary and full support is possible and may happen soon. type BincHandle struct { BasicHandle - binaryEncodingType - noElemSeparators - - // AsSymbols defines what should be encoded as symbols. - // - // Encoding as symbols can reduce the encoded size significantly. - // - // However, during decoding, each string to be encoded as a symbol must - // be checked to see if it has been seen before. Consequently, encoding time - // will increase if using symbols, because string comparisons has a clear cost. - // - // Values: - // - 0: default: library uses best judgement - // - 1: use symbols - // - 2: do not use symbols - AsSymbols uint8 - - // AsSymbols: may later on introduce more options ... - // - m: map keys - // - s: struct fields - // - n: none - // - a: all: same as m, s, ... - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: binc -func (h *BincHandle) Name() string { return "binc" } - -// SetBytesExt sets an extension -func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) -} - -func (h *BincHandle) newEncDriver(e *Encoder) encDriver { - return &bincEncDriver{e: e, h: h, w: e.w} -} - -func (h *BincHandle) newDecDriver(d *Decoder) decDriver { - return &bincDecDriver{d: d, h: h, r: d.r, br: d.bytes} } -func (e *bincEncDriver) reset() { - e.w = e.e.w - e.s = 0 - e.c = 0 - e.m = nil +func (h *BincHandle) newEncDriver(w encWriter) encDriver { + return &bincEncDriver{w: w} } -func (d *bincDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.s = nil - d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0 +func (h *BincHandle) newDecDriver(r decReader) decDriver { + return &bincDecDriver{r: r} } -// var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} - -// EncodeTime encodes a time.Time as a []byte, including -// information on the instant in time and UTC offset. -// -// Format Description -// -// A timestamp is composed of 3 components: -// -// - secs: signed integer representing seconds since unix epoch -// - nsces: unsigned integer representing fractional seconds as a -// nanosecond offset within secs, in the range 0 <= nsecs < 1e9 -// - tz: signed integer representing timezone offset in minutes east of UTC, -// and a dst (daylight savings time) flag -// -// When encoding a timestamp, the first byte is the descriptor, which -// defines which components are encoded and how many bytes are used to -// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it -// is not encoded in the byte array explicitly*. -// -// Descriptor 8 bits are of the form `A B C DDD EE`: -// A: Is secs component encoded? 1 = true -// B: Is nsecs component encoded? 1 = true -// C: Is tz component encoded? 1 = true -// DDD: Number of extra bytes for secs (range 0-7). -// If A = 1, secs encoded in DDD+1 bytes. -// If A = 0, secs is not encoded, and is assumed to be 0. -// If A = 1, then we need at least 1 byte to encode secs. -// DDD says the number of extra bytes beyond that 1. -// E.g. if DDD=0, then secs is represented in 1 byte. -// if DDD=2, then secs is represented in 3 bytes. -// EE: Number of extra bytes for nsecs (range 0-3). -// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above) -// -// Following the descriptor bytes, subsequent bytes are: -// -// secs component encoded in `DDD + 1` bytes (if A == 1) -// nsecs component encoded in `EE + 1` bytes (if B == 1) -// tz component encoded in 2 bytes (if C == 1) -// -// secs and nsecs components are integers encoded in a BigEndian -// 2-complement encoding format. -// -// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to -// Least significant bit 0 are described below: -// -// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes). -// Bit 15 = have\_dst: set to 1 if we set the dst flag. -// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not. -// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format. -// -func bincEncodeTime(t time.Time) []byte { - //t := rv.Interface().(time.Time) - tsecs, tnsecs := t.Unix(), t.Nanosecond() - var ( - bd byte - btmp [8]byte - bs [16]byte - i int = 1 - ) - l := t.Location() - if l == time.UTC { - l = nil - } - if tsecs != 0 { - bd = bd | 0x80 - bigen.PutUint64(btmp[:], uint64(tsecs)) - f := pruneSignExt(btmp[:], tsecs >= 0) - bd = bd | (byte(7-f) << 2) - copy(bs[i:], btmp[f:]) - i = i + (8 - f) - } - if tnsecs != 0 { - bd = bd | 0x40 - bigen.PutUint32(btmp[:4], uint32(tnsecs)) - f := pruneSignExt(btmp[:4], true) - bd = bd | byte(3-f) - copy(bs[i:], btmp[f:4]) - i = i + (4 - f) - } - if l != nil { - bd = bd | 0x20 - // Note that Go Libs do not give access to dst flag. - _, zoneOffset := t.Zone() - //zoneName, zoneOffset := t.Zone() - zoneOffset /= 60 - z := uint16(zoneOffset) - bigen.PutUint16(btmp[:2], z) - // clear dst flags - bs[i] = btmp[0] & 0x3f - bs[i+1] = btmp[1] - i = i + 2 - } - bs[0] = bd - return bs[0:i] +func (_ *BincHandle) writeExt() bool { + return true } -// bincDecodeTime decodes a []byte into a time.Time. -func bincDecodeTime(bs []byte) (tt time.Time, err error) { - bd := bs[0] - var ( - tsec int64 - tnsec uint32 - tz uint16 - i byte = 1 - i2 byte - n byte - ) - if bd&(1<<7) != 0 { - var btmp [8]byte - n = ((bd >> 2) & 0x7) + 1 - i2 = i + n - copy(btmp[8-n:], bs[i:i2]) - //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it) - if bs[i]&(1<<7) != 0 { - copy(btmp[0:8-n], bsAll0xff) - //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff } - } - i = i2 - tsec = int64(bigen.Uint64(btmp[:])) - } - if bd&(1<<6) != 0 { - var btmp [4]byte - n = (bd & 0x3) + 1 - i2 = i + n - copy(btmp[4-n:], bs[i:i2]) - i = i2 - tnsec = bigen.Uint32(btmp[:]) - } - if bd&(1<<5) == 0 { - tt = time.Unix(tsec, int64(tnsec)).UTC() - return - } - // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name. - // However, we need name here, so it can be shown when time is printf.d. - // Zone name is in form: UTC-08:00. - // Note that Go Libs do not give access to dst flag, so we ignore dst bits - - i2 = i + 2 - tz = bigen.Uint16(bs[i:i2]) - // i = i2 - // sign extend sign bit into top 2 MSB (which were dst bits): - if tz&(1<<13) == 0 { // positive - tz = tz & 0x3fff //clear 2 MSBs: dst bits - } else { // negative - tz = tz | 0xc000 //set 2 MSBs: dst bits - } - tzint := int16(tz) - if tzint == 0 { - tt = time.Unix(tsec, int64(tnsec)).UTC() - } else { - // For Go Time, do not use a descriptive timezone. - // It's unnecessary, and makes it harder to do a reflect.DeepEqual. - // The Offset already tells what the offset should be, if not on UTC and unknown zone name. - // var zoneName = timeLocUTCName(tzint) - tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60)) - } - return +func (h *BincHandle) getBasicHandle() *BasicHandle { + return &h.BasicHandle } - -var _ decDriver = (*bincDecDriver)(nil) -var _ encDriver = (*bincEncDriver)(nil) diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/build.sh b/vendor/github.com/hashicorp/go-msgpack/codec/build.sh deleted file mode 100644 index dd79c13f81a26..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/build.sh +++ /dev/null @@ -1,267 +0,0 @@ -#!/bin/bash - -# Run all the different permutations of all the tests and other things -# This helps ensure that nothing gets broken. - -_tests() { - local gover=$( go version | cut -f 3 -d ' ' ) - # note that codecgen requires fastpath, so you cannot do "codecgen notfastpath" - local a=( "" "safe" "notfastpath" "notfastpath safe" "codecgen" "codecgen safe" ) - for i in "${a[@]}" - do - echo ">>>> TAGS: $i" - local i2=${i:-default} - case $gover in - go1.[0-6]*) go vet -printfuncs "errorf" "$@" && - go test ${zargs[*]} -vet off -tags "$i" "$@" ;; - *) go vet -printfuncs "errorf" "$@" && - go test ${zargs[*]} -vet off -tags "alltests $i" -run "Suite" -coverprofile "${i2// /-}.cov.out" "$@" ;; - esac - if [[ "$?" != 0 ]]; then return 1; fi - done - echo "++++++++ TEST SUITES ALL PASSED ++++++++" -} - - -# is a generation needed? -_ng() { - local a="$1" - if [[ ! -e "$a" ]]; then echo 1; return; fi - for i in `ls -1 *.go.tmpl gen.go values_test.go` - do - if [[ "$a" -ot "$i" ]]; then echo 1; return; fi - done -} - -_prependbt() { - cat > ${2} <<EOF -// +build generated - -EOF - cat ${1} >> ${2} - rm -f ${1} -} - -# _build generates fast-path.go and gen-helper.go. -_build() { - if ! [[ "${zforce}" || $(_ng "fast-path.generated.go") || $(_ng "gen-helper.generated.go") || $(_ng "gen.generated.go") ]]; then return 0; fi - - if [ "${zbak}" ]; then - _zts=`date '+%m%d%Y_%H%M%S'` - _gg=".generated.go" - [ -e "gen-helper${_gg}" ] && mv gen-helper${_gg} gen-helper${_gg}__${_zts}.bak - [ -e "fast-path${_gg}" ] && mv fast-path${_gg} fast-path${_gg}__${_zts}.bak - [ -e "gen${_gg}" ] && mv gen${_gg} gen${_gg}__${_zts}.bak - fi - rm -f gen-helper.generated.go fast-path.generated.go gen.generated.go \ - *safe.generated.go *_generated_test.go *.generated_ffjson_expose.go - - cat > gen.generated.go <<EOF -// +build codecgen.exec - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// DO NOT EDIT. THIS FILE IS AUTO-GENERATED FROM gen-dec-(map|array).go.tmpl - -const genDecMapTmpl = \` -EOF - cat >> gen.generated.go < gen-dec-map.go.tmpl - cat >> gen.generated.go <<EOF -\` - -const genDecListTmpl = \` -EOF - cat >> gen.generated.go < gen-dec-array.go.tmpl - cat >> gen.generated.go <<EOF -\` - -const genEncChanTmpl = \` -EOF - cat >> gen.generated.go < gen-enc-chan.go.tmpl - cat >> gen.generated.go <<EOF -\` -EOF - cat > gen-from-tmpl.codec.generated.go <<EOF -package codec -import "io" -func GenInternalGoFile(r io.Reader, w io.Writer) error { -return genInternalGoFile(r, w) -} -EOF - cat > gen-from-tmpl.generated.go <<EOF -//+build ignore - -package main - -import "${zpkg}" -import "os" - -func run(fnameIn, fnameOut string) { -println("____ " + fnameIn + " --> " + fnameOut + " ______") -fin, err := os.Open(fnameIn) -if err != nil { panic(err) } -defer fin.Close() -fout, err := os.Create(fnameOut) -if err != nil { panic(err) } -defer fout.Close() -err = codec.GenInternalGoFile(fin, fout) -if err != nil { panic(err) } -} - -func main() { -run("fast-path.go.tmpl", "fast-path.generated.go") -run("gen-helper.go.tmpl", "gen-helper.generated.go") -run("mammoth-test.go.tmpl", "mammoth_generated_test.go") -run("mammoth2-test.go.tmpl", "mammoth2_generated_test.go") -} -EOF - - sed -e 's+// __DO_NOT_REMOVE__NEEDED_FOR_REPLACING__IMPORT_PATH__FOR_CODEC_BENCH__+import . "github.com/ugorji/go/codec"+' \ - shared_test.go > bench/shared_test.go - - # explicitly return 0 if this passes, else return 1 - go run -tags "notfastpath safe codecgen.exec" gen-from-tmpl.generated.go && - rm -f gen-from-tmpl.*generated.go && - return 0 - return 1 -} - -_codegenerators() { - local c5="_generated_test.go" - local c7="$PWD/codecgen" - local c8="$c7/__codecgen" - local c9="codecgen-scratch.go" - - if ! [[ $zforce || $(_ng "values_codecgen${c5}") ]]; then return 0; fi - - # Note: ensure you run the codecgen for this codebase/directory i.e. ./codecgen/codecgen - true && - echo "codecgen ... " && - if [[ $zforce || ! -f "$c8" || "$c7/gen.go" -nt "$c8" ]]; then - echo "rebuilding codecgen ... " && ( cd codecgen && go build -o $c8 ${zargs[*]} . ) - fi && - $c8 -rt codecgen -t 'codecgen generated' -o values_codecgen${c5} -d 19780 $zfin $zfin2 && - cp mammoth2_generated_test.go $c9 && - $c8 -t '!notfastpath' -o mammoth2_codecgen${c5} -d 19781 mammoth2_generated_test.go && - rm -f $c9 && - echo "generators done!" -} - -_prebuild() { - echo "prebuild: zforce: $zforce" - local d="$PWD" - zfin="test_values.generated.go" - zfin2="test_values_flex.generated.go" - zpkg="github.com/ugorji/go/codec" - # zpkg=${d##*/src/} - # zgobase=${d%%/src/*} - # rm -f *_generated_test.go - rm -f codecgen-*.go && - _build && - cp $d/values_test.go $d/$zfin && - cp $d/values_flex_test.go $d/$zfin2 && - _codegenerators && - if [[ "$(type -t _codegenerators_external )" = "function" ]]; then _codegenerators_external ; fi && - if [[ $zforce ]]; then go install ${zargs[*]} .; fi && - echo "prebuild done successfully" - rm -f $d/$zfin $d/$zfin2 - unset zfin zfin2 zpkg -} - -_make() { - zforce=1 - (cd codecgen && go install ${zargs[*]} .) && _prebuild && go install ${zargs[*]} . - unset zforce -} - -_clean() { - rm -f gen-from-tmpl.*generated.go \ - codecgen-*.go \ - test_values.generated.go test_values_flex.generated.go -} - -_release() { - local reply - read -p "Pre-release validation takes a few minutes and MUST be run from within GOPATH/src. Confirm y/n? " -n 1 -r reply - echo - if [[ ! $reply =~ ^[Yy]$ ]]; then return 1; fi - - # expects GOROOT, GOROOT_BOOTSTRAP to have been set. - if [[ -z "${GOROOT// }" || -z "${GOROOT_BOOTSTRAP// }" ]]; then return 1; fi - # (cd $GOROOT && git checkout -f master && git pull && git reset --hard) - (cd $GOROOT && git pull) - local f=`pwd`/make.release.out - cat > $f <<EOF -========== `date` =========== -EOF - # # go 1.6 and below kept giving memory errors on Mac OS X during SDK build or go run execution, - # # that is fine, as we only explicitly test the last 3 releases and tip (2 years). - zforce=1 - for i in 1.10 1.11 1.12 master - do - echo "*********** $i ***********" >>$f - if [[ "$i" != "master" ]]; then i="release-branch.go$i"; fi - (false || - (echo "===== BUILDING GO SDK for branch: $i ... =====" && - cd $GOROOT && - git checkout -f $i && git reset --hard && git clean -f . && - cd src && ./make.bash >>$f 2>&1 && sleep 1 ) ) && - echo "===== GO SDK BUILD DONE =====" && - _prebuild && - echo "===== PREBUILD DONE with exit: $? =====" && - _tests "$@" - if [[ "$?" != 0 ]]; then return 1; fi - done - unset zforce - echo "++++++++ RELEASE TEST SUITES ALL PASSED ++++++++" -} - -_usage() { - cat <<EOF -primary usage: $0 - -[tmpfxnld] -> [tests, make, prebuild (force) (external), inlining diagnostics, mid-stack inlining, race detector] - -v -> verbose -EOF - if [[ "$(type -t _usage_run)" = "function" ]]; then _usage_run ; fi -} - -_main() { - if [[ -z "$1" ]]; then _usage; return 1; fi - local x - unset zforce - zargs=() - zbenchflags="" - OPTIND=1 - while getopts ":ctmnrgpfvlzdb:" flag - do - case "x$flag" in - 'xf') zforce=1 ;; - 'xv') zverbose=1 ;; - 'xl') zargs+=("-gcflags"); zargs+=("-l=4") ;; - 'xn') zargs+=("-gcflags"); zargs+=("-m=2") ;; - 'xd') zargs+=("-race") ;; - 'xb') x='b'; zbenchflags=${OPTARG} ;; - x\?) _usage; return 1 ;; - *) x=$flag ;; - esac - done - shift $((OPTIND-1)) - # echo ">>>> _main: extra args: $@" - case "x$x" in - 'xt') _tests "$@" ;; - 'xm') _make "$@" ;; - 'xr') _release "$@" ;; - 'xg') _go ;; - 'xp') _prebuild "$@" ;; - 'xc') _clean "$@" ;; - 'xz') _analyze "$@" ;; - 'xb') _bench "$@" ;; - esac - unset zforce zargs zbenchflags -} - -[ "." = `dirname $0` ] && _main "$@" - diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/cbor.go b/vendor/github.com/hashicorp/go-msgpack/codec/cbor.go deleted file mode 100644 index 7833f9d68f090..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/cbor.go +++ /dev/null @@ -1,767 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "math" - "reflect" - "time" -) - -const ( - cborMajorUint byte = iota - cborMajorNegInt - cborMajorBytes - cborMajorText - cborMajorArray - cborMajorMap - cborMajorTag - cborMajorOther -) - -const ( - cborBdFalse byte = 0xf4 + iota - cborBdTrue - cborBdNil - cborBdUndefined - cborBdExt - cborBdFloat16 - cborBdFloat32 - cborBdFloat64 -) - -const ( - cborBdIndefiniteBytes byte = 0x5f - cborBdIndefiniteString byte = 0x7f - cborBdIndefiniteArray byte = 0x9f - cborBdIndefiniteMap byte = 0xbf - cborBdBreak byte = 0xff -) - -// These define some in-stream descriptors for -// manual encoding e.g. when doing explicit indefinite-length -const ( - CborStreamBytes byte = 0x5f - CborStreamString byte = 0x7f - CborStreamArray byte = 0x9f - CborStreamMap byte = 0xbf - CborStreamBreak byte = 0xff -) - -const ( - cborBaseUint byte = 0x00 - cborBaseNegInt byte = 0x20 - cborBaseBytes byte = 0x40 - cborBaseString byte = 0x60 - cborBaseArray byte = 0x80 - cborBaseMap byte = 0xa0 - cborBaseTag byte = 0xc0 - cborBaseSimple byte = 0xe0 -) - -func cbordesc(bd byte) string { - switch bd { - case cborBdNil: - return "nil" - case cborBdFalse: - return "false" - case cborBdTrue: - return "true" - case cborBdFloat16, cborBdFloat32, cborBdFloat64: - return "float" - case cborBdIndefiniteBytes: - return "bytes*" - case cborBdIndefiniteString: - return "string*" - case cborBdIndefiniteArray: - return "array*" - case cborBdIndefiniteMap: - return "map*" - default: - switch { - case bd >= cborBaseUint && bd < cborBaseNegInt: - return "(u)int" - case bd >= cborBaseNegInt && bd < cborBaseBytes: - return "int" - case bd >= cborBaseBytes && bd < cborBaseString: - return "bytes" - case bd >= cborBaseString && bd < cborBaseArray: - return "string" - case bd >= cborBaseArray && bd < cborBaseMap: - return "array" - case bd >= cborBaseMap && bd < cborBaseTag: - return "map" - case bd >= cborBaseTag && bd < cborBaseSimple: - return "ext" - default: - return "unknown" - } - } -} - -// ------------------- - -type cborEncDriver struct { - noBuiltInTypes - encDriverNoopContainerWriter - e *Encoder - w *encWriterSwitch - h *CborHandle - x [8]byte - // _ [3]uint64 // padding -} - -func (e *cborEncDriver) EncodeNil() { - e.w.writen1(cborBdNil) -} - -func (e *cborEncDriver) EncodeBool(b bool) { - if b { - e.w.writen1(cborBdTrue) - } else { - e.w.writen1(cborBdFalse) - } -} - -func (e *cborEncDriver) EncodeFloat32(f float32) { - e.w.writen1(cborBdFloat32) - bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f)) -} - -func (e *cborEncDriver) EncodeFloat64(f float64) { - e.w.writen1(cborBdFloat64) - bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f)) -} - -func (e *cborEncDriver) encUint(v uint64, bd byte) { - if v <= 0x17 { - e.w.writen1(byte(v) + bd) - } else if v <= math.MaxUint8 { - e.w.writen2(bd+0x18, uint8(v)) - } else if v <= math.MaxUint16 { - e.w.writen1(bd + 0x19) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { - e.w.writen1(bd + 0x1a) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(v)) - } else { // if v <= math.MaxUint64 { - e.w.writen1(bd + 0x1b) - bigenHelper{e.x[:8], e.w}.writeUint64(v) - } -} - -func (e *cborEncDriver) EncodeInt(v int64) { - if v < 0 { - e.encUint(uint64(-1-v), cborBaseNegInt) - } else { - e.encUint(uint64(v), cborBaseUint) - } -} - -func (e *cborEncDriver) EncodeUint(v uint64) { - e.encUint(v, cborBaseUint) -} - -func (e *cborEncDriver) encLen(bd byte, length int) { - e.encUint(uint64(length), bd) -} - -func (e *cborEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - } else if e.h.TimeRFC3339 { - e.encUint(0, cborBaseTag) - e.EncodeStringEnc(cUTF8, t.Format(time.RFC3339Nano)) - } else { - e.encUint(1, cborBaseTag) - t = t.UTC().Round(time.Microsecond) - sec, nsec := t.Unix(), uint64(t.Nanosecond()) - if nsec == 0 { - e.EncodeInt(sec) - } else { - e.EncodeFloat64(float64(sec) + float64(nsec)/1e9) - } - } -} - -func (e *cborEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) { - e.encUint(uint64(xtag), cborBaseTag) - if v := ext.ConvertExt(rv); v == nil { - e.EncodeNil() - } else { - en.encode(v) - } -} - -func (e *cborEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { - e.encUint(uint64(re.Tag), cborBaseTag) - // only encodes re.Value (never re.Data) - // if false && re.Data != nil { - // en.encode(re.Data) - // } else if re.Value != nil { - if re.Value != nil { - en.encode(re.Value) - } else { - e.EncodeNil() - } -} - -func (e *cborEncDriver) WriteArrayStart(length int) { - if e.h.IndefiniteLength { - e.w.writen1(cborBdIndefiniteArray) - } else { - e.encLen(cborBaseArray, length) - } -} - -func (e *cborEncDriver) WriteMapStart(length int) { - if e.h.IndefiniteLength { - e.w.writen1(cborBdIndefiniteMap) - } else { - e.encLen(cborBaseMap, length) - } -} - -func (e *cborEncDriver) WriteMapEnd() { - if e.h.IndefiniteLength { - e.w.writen1(cborBdBreak) - } -} - -func (e *cborEncDriver) WriteArrayEnd() { - if e.h.IndefiniteLength { - e.w.writen1(cborBdBreak) - } -} - -func (e *cborEncDriver) EncodeString(c charEncoding, v string) { - e.encStringBytesS(cborBaseString, v) -} - -func (e *cborEncDriver) EncodeStringEnc(c charEncoding, v string) { - e.encStringBytesS(cborBaseString, v) -} - -func (e *cborEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - if v == nil { - e.EncodeNil() - } else if c == cRAW { - e.encStringBytesS(cborBaseBytes, stringView(v)) - } else { - e.encStringBytesS(cborBaseString, stringView(v)) - } -} - -func (e *cborEncDriver) EncodeStringBytesRaw(v []byte) { - if v == nil { - e.EncodeNil() - } else { - e.encStringBytesS(cborBaseBytes, stringView(v)) - } -} - -func (e *cborEncDriver) encStringBytesS(bb byte, v string) { - if e.h.IndefiniteLength { - if bb == cborBaseBytes { - e.w.writen1(cborBdIndefiniteBytes) - } else { - e.w.writen1(cborBdIndefiniteString) - } - var vlen uint = uint(len(v)) - blen := vlen / 4 - if blen == 0 { - blen = 64 - } else if blen > 1024 { - blen = 1024 - } - for i := uint(0); i < vlen; { - var v2 string - i2 := i + blen - if i2 < vlen { - v2 = v[i:i2] - } else { - v2 = v[i:] - } - e.encLen(bb, len(v2)) - e.w.writestr(v2) - i = i2 - } - e.w.writen1(cborBdBreak) - } else { - e.encLen(bb, len(v)) - e.w.writestr(v) - } -} - -// ---------------------- - -type cborDecDriver struct { - d *Decoder - h *CborHandle - r *decReaderSwitch - br bool // bytes reader - bdRead bool - bd byte - noBuiltInTypes - // decNoSeparator - decDriverNoopContainerReader - // _ [3]uint64 // padding -} - -func (d *cborDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true -} - -func (d *cborDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *cborDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil { - return valueTypeNil - } else if d.bd == cborBdIndefiniteBytes || (d.bd >= cborBaseBytes && d.bd < cborBaseString) { - return valueTypeBytes - } else if d.bd == cborBdIndefiniteString || (d.bd >= cborBaseString && d.bd < cborBaseArray) { - return valueTypeString - } else if d.bd == cborBdIndefiniteArray || (d.bd >= cborBaseArray && d.bd < cborBaseMap) { - return valueTypeArray - } else if d.bd == cborBdIndefiniteMap || (d.bd >= cborBaseMap && d.bd < cborBaseTag) { - return valueTypeMap - } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset -} - -func (d *cborDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } - // treat Nil and Undefined as nil values - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return true - } - return false -} - -func (d *cborDecDriver) CheckBreak() bool { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdBreak { - d.bdRead = false - return true - } - return false -} - -func (d *cborDecDriver) decUint() (ui uint64) { - v := d.bd & 0x1f - if v <= 0x17 { - ui = uint64(v) - } else { - if v == 0x18 { - ui = uint64(d.r.readn1()) - } else if v == 0x19 { - ui = uint64(bigen.Uint16(d.r.readx(2))) - } else if v == 0x1a { - ui = uint64(bigen.Uint32(d.r.readx(4))) - } else if v == 0x1b { - ui = uint64(bigen.Uint64(d.r.readx(8))) - } else { - d.d.errorf("invalid descriptor decoding uint: %x/%s", d.bd, cbordesc(d.bd)) - return - } - } - return -} - -func (d *cborDecDriver) decCheckInteger() (neg bool) { - if !d.bdRead { - d.readNextBd() - } - major := d.bd >> 5 - if major == cborMajorUint { - } else if major == cborMajorNegInt { - neg = true - } else { - d.d.errorf("not an integer - invalid major %v from descriptor %x/%s", - major, d.bd, cbordesc(d.bd)) - return - } - return -} - -func (d *cborDecDriver) DecodeInt64() (i int64) { - neg := d.decCheckInteger() - ui := d.decUint() - // check if this number can be converted to an int without overflow - if neg { - i = -(chkOvf.SignedIntV(ui + 1)) - } else { - i = chkOvf.SignedIntV(ui) - } - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeUint64() (ui uint64) { - if d.decCheckInteger() { - d.d.errorf("assigning negative signed value to unsigned type") - return - } - ui = d.decUint() - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == cborBdFloat16 { - f = float64(math.Float32frombits(halfFloatToFloatBits(bigen.Uint16(d.r.readx(2))))) - } else if bd == cborBdFloat32 { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if bd == cborBdFloat64 { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else if bd >= cborBaseUint && bd < cborBaseBytes { - f = float64(d.DecodeInt64()) - } else { - d.d.errorf("float only valid from float16/32/64 - invalid descriptor %x/%s", bd, cbordesc(bd)) - return - } - d.bdRead = false - return -} - -// bool can be decoded from bool only (single byte). -func (d *cborDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == cborBdTrue { - b = true - } else if bd == cborBdFalse { - } else { - d.d.errorf("not bool - %s %x/%s", msgBadDesc, d.bd, cbordesc(d.bd)) - return - } - d.bdRead = false - return -} - -func (d *cborDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - if d.bd == cborBdIndefiniteMap { - return -1 - } - return d.decLen() -} - -func (d *cborDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - if d.bd == cborBdIndefiniteArray { - return -1 - } - return d.decLen() -} - -func (d *cborDecDriver) decLen() int { - return int(d.decUint()) -} - -func (d *cborDecDriver) decAppendIndefiniteBytes(bs []byte) []byte { - d.bdRead = false - for { - if d.CheckBreak() { - break - } - if major := d.bd >> 5; major != cborMajorBytes && major != cborMajorText { - d.d.errorf("expect bytes/string major type in indefinite string/bytes;"+ - " got major %v from descriptor %x/%x", major, d.bd, cbordesc(d.bd)) - return nil - } - n := d.decLen() - oldLen := len(bs) - newLen := oldLen + n - if newLen > cap(bs) { - bs2 := make([]byte, newLen, 2*cap(bs)+n) - copy(bs2, bs) - bs = bs2 - } else { - bs = bs[:newLen] - } - d.r.readb(bs[oldLen:newLen]) - // bs = append(bs, d.r.readn()...) - d.bdRead = false - } - d.bdRead = false - return bs -} - -func (d *cborDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return nil - } - if d.bd == cborBdIndefiniteBytes || d.bd == cborBdIndefiniteString { - d.bdRead = false - if bs == nil { - if zerocopy { - return d.decAppendIndefiniteBytes(d.d.b[:0]) - } - return d.decAppendIndefiniteBytes(zeroByteSlice) - } - return d.decAppendIndefiniteBytes(bs[:0]) - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.bd == cborBdIndefiniteArray || (d.bd >= cborBaseArray && d.bd < cborBaseMap) { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - clen := d.decLen() - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(uint(clen)) - } else if len(bs) == 0 { - bs = d.d.b[:] - } - } - return decByteSlice(d.r, clen, d.h.MaxInitLen, bs) -} - -func (d *cborDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *cborDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *cborDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return - } - xtag := d.decUint() - d.bdRead = false - return d.decodeTime(xtag) -} - -func (d *cborDecDriver) decodeTime(xtag uint64) (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - switch xtag { - case 0: - var err error - if t, err = time.Parse(time.RFC3339, stringView(d.DecodeStringAsBytes())); err != nil { - d.d.errorv(err) - } - case 1: - // decode an int64 or a float, and infer time.Time from there. - // for floats, round to microseconds, as that is what is guaranteed to fit well. - switch { - case d.bd == cborBdFloat16, d.bd == cborBdFloat32: - f1, f2 := math.Modf(d.DecodeFloat64()) - t = time.Unix(int64(f1), int64(f2*1e9)) - case d.bd == cborBdFloat64: - f1, f2 := math.Modf(d.DecodeFloat64()) - t = time.Unix(int64(f1), int64(f2*1e9)) - case d.bd >= cborBaseUint && d.bd < cborBaseNegInt, - d.bd >= cborBaseNegInt && d.bd < cborBaseBytes: - t = time.Unix(d.DecodeInt64(), 0) - default: - d.d.errorf("time.Time can only be decoded from a number (or RFC3339 string)") - } - default: - d.d.errorf("invalid tag for time.Time - expecting 0 or 1, got 0x%x", xtag) - } - t = t.UTC().Round(time.Microsecond) - return -} - -func (d *cborDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if !d.bdRead { - d.readNextBd() - } - u := d.decUint() - d.bdRead = false - realxtag = u - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - d.d.decode(&re.Value) - } else if xtag != realxtag { - d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", realxtag, xtag) - return - } else { - var v interface{} - d.d.decode(&v) - ext.UpdateExt(rv, v) - } - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.naked() - var decodeFurther bool - - switch d.bd { - case cborBdNil: - n.v = valueTypeNil - case cborBdFalse: - n.v = valueTypeBool - n.b = false - case cborBdTrue: - n.v = valueTypeBool - n.b = true - case cborBdFloat16, cborBdFloat32, cborBdFloat64: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() - case cborBdIndefiniteBytes: - decNakedReadRawBytes(d, d.d, n, d.h.RawToString) - case cborBdIndefiniteString: - n.v = valueTypeString - n.s = d.DecodeString() - case cborBdIndefiniteArray: - n.v = valueTypeArray - decodeFurther = true - case cborBdIndefiniteMap: - n.v = valueTypeMap - decodeFurther = true - default: - switch { - case d.bd >= cborBaseUint && d.bd < cborBaseNegInt: - if d.h.SignedInteger { - n.v = valueTypeInt - n.i = d.DecodeInt64() - } else { - n.v = valueTypeUint - n.u = d.DecodeUint64() - } - case d.bd >= cborBaseNegInt && d.bd < cborBaseBytes: - n.v = valueTypeInt - n.i = d.DecodeInt64() - case d.bd >= cborBaseBytes && d.bd < cborBaseString: - decNakedReadRawBytes(d, d.d, n, d.h.RawToString) - case d.bd >= cborBaseString && d.bd < cborBaseArray: - n.v = valueTypeString - n.s = d.DecodeString() - case d.bd >= cborBaseArray && d.bd < cborBaseMap: - n.v = valueTypeArray - decodeFurther = true - case d.bd >= cborBaseMap && d.bd < cborBaseTag: - n.v = valueTypeMap - decodeFurther = true - case d.bd >= cborBaseTag && d.bd < cborBaseSimple: - n.v = valueTypeExt - n.u = d.decUint() - n.l = nil - if n.u == 0 || n.u == 1 { - d.bdRead = false - n.v = valueTypeTime - n.t = d.decodeTime(n.u) - } - // d.bdRead = false - // d.d.decode(&re.Value) // handled by decode itself. - // decodeFurther = true - default: - d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd) - return - } - } - - if !decodeFurther { - d.bdRead = false - } -} - -// ------------------------- - -// CborHandle is a Handle for the CBOR encoding format, -// defined at http://tools.ietf.org/html/rfc7049 and documented further at http://cbor.io . -// -// CBOR is comprehensively supported, including support for: -// - indefinite-length arrays/maps/bytes/strings -// - (extension) tags in range 0..0xffff (0 .. 65535) -// - half, single and double-precision floats -// - all numbers (1, 2, 4 and 8-byte signed and unsigned integers) -// - nil, true, false, ... -// - arrays and maps, bytes and text strings -// -// None of the optional extensions (with tags) defined in the spec are supported out-of-the-box. -// Users can implement them as needed (using SetExt), including spec-documented ones: -// - timestamp, BigNum, BigFloat, Decimals, -// - Encoded Text (e.g. URL, regexp, base64, MIME Message), etc. -type CborHandle struct { - binaryEncodingType - noElemSeparators - BasicHandle - - // IndefiniteLength=true, means that we encode using indefinitelength - IndefiniteLength bool - - // TimeRFC3339 says to encode time.Time using RFC3339 format. - // If unset, we encode time.Time using seconds past epoch. - TimeRFC3339 bool - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: cbor -func (h *CborHandle) Name() string { return "cbor" } - -// SetInterfaceExt sets an extension -func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext}) -} - -func (h *CborHandle) newEncDriver(e *Encoder) encDriver { - return &cborEncDriver{e: e, w: e.w, h: h} -} - -func (h *CborHandle) newDecDriver(d *Decoder) decDriver { - return &cborDecDriver{d: d, h: h, r: d.r, br: d.bytes} -} - -func (e *cborEncDriver) reset() { - e.w = e.e.w -} - -func (d *cborDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false -} - -var _ decDriver = (*cborDecDriver)(nil) -var _ encDriver = (*cborEncDriver)(nil) diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/codecgen.go b/vendor/github.com/hashicorp/go-msgpack/codec/codecgen.go deleted file mode 100644 index cc5ecec6dbbac..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/codecgen.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build codecgen generated - -package codec - -// this file is here, to set the codecgen variable to true -// when the build tag codecgen is set. -// -// this allows us do specific things e.g. skip missing fields tests, -// when running in codecgen mode. - -func init() { - codecgen = true -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/decode.go b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go index 27d362012d146..851b54ac7e776 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/decode.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go @@ -1,2439 +1,578 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec import ( - "encoding" - "errors" - "fmt" "io" "reflect" - "runtime" - "strconv" - "time" + // "runtime/debug" ) // Some tagging information for error messages. const ( - msgBadDesc = "unrecognized descriptor byte" - // msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v" + msgTagDec = "codec.decoder" + msgBadDesc = "Unrecognized descriptor byte" + msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v" ) -const ( - decDefMaxDepth = 1024 // maximum depth - decDefSliceCap = 8 - decDefChanCap = 64 // should be large, as cap cannot be expanded - decScratchByteArrayLen = cacheLineSize // + (8 * 2) // - (8 * 1) -) - -var ( - errstrOnlyMapOrArrayCanDecodeIntoStruct = "only encoded map or array can be decoded into a struct" - errstrCannotDecodeIntoNil = "cannot decode into nil" - - errmsgExpandSliceOverflow = "expand slice: slice overflow" - errmsgExpandSliceCannotChange = "expand slice: cannot change" - - errDecoderNotInitialized = errors.New("Decoder not initialized") - - errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read") - errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read") - errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown") - errMaxDepthExceeded = errors.New("maximum decoding depth exceeded") -) - -/* - // decReader abstracts the reading source, allowing implementations that can // read from an io.Reader or directly off a byte slice with zero-copying. -// -// Deprecated: Use decReaderSwitch instead. type decReader interface { - unreadn1() - // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR - // just return a view of the []byte being decoded from. - // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control. - readx(n int) []byte + readn(n int) []byte readb([]byte) readn1() uint8 - numread() uint // number of bytes read - track() - stopTrack() []byte - - // skip will skip any byte that matches, and return the first non-matching byte - skip(accept *bitset256) (token byte) - // readTo will read any byte that matches, stopping once no-longer matching. - readTo(in []byte, accept *bitset256) (out []byte) - // readUntil will read, only stopping once it matches the 'stop' byte. - readUntil(in []byte, stop byte) (out []byte) + readUint16() uint16 + readUint32() uint32 + readUint64() uint64 } -*/ - type decDriver interface { - // this will check if the next token is a break. - CheckBreak() bool - // TryDecodeAsNil tries to decode as nil. - // Note: TryDecodeAsNil should be careful not to share any temporary []byte with - // the rest of the decDriver. This is because sometimes, we optimize by holding onto - // a transient []byte, and ensuring the only other call we make to the decDriver - // during that time is maybe a TryDecodeAsNil() call. - TryDecodeAsNil() bool - // ContainerType returns one of: Bytes, String, Nil, Slice or Map. Return unSet if not known. - ContainerType() (vt valueType) - // IsBuiltinType(rt uintptr) bool - - // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt. - // For maps and arrays, it will not do the decoding in-band, but will signal - // the decoder, so that is done later, by setting the decNaked.valueType field. - // - // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types). - // for extensions, DecodeNaked must read the tag and the []byte if it exists. - // if the []byte is not read, then kInterfaceNaked will treat it as a Handle - // that stores the subsequent value in-band, and complete reading the RawExt. - // - // extensions should also use readx to decode them, for efficiency. - // kInterface will extract the detached byte slice if it has to pass it outside its realm. - DecodeNaked() - - // Deprecated: use DecodeInt64 and DecodeUint64 instead - // DecodeInt(bitsize uint8) (i int64) - // DecodeUint(bitsize uint8) (ui uint64) - - DecodeInt64() (i int64) - DecodeUint64() (ui uint64) - - DecodeFloat64() (f float64) - DecodeBool() (b bool) - // DecodeString can also decode symbols. - // It looks redundant as DecodeBytes is available. - // However, some codecs (e.g. binc) support symbols and can - // return a pre-stored string value, meaning that it can bypass - // the cost of []byte->string conversion. - DecodeString() (s string) - DecodeStringAsBytes() (v []byte) - - // DecodeBytes may be called directly, without going through reflection. - // Consequently, it must be designed to handle possible nil. - DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) - // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) - - // decodeExt will decode into a *RawExt or into an extension. - DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64) - // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) - - DecodeTime() (t time.Time) - - ReadArrayStart() int - ReadArrayElem() - ReadArrayEnd() - ReadMapStart() int - ReadMapElemKey() - ReadMapElemValue() - ReadMapEnd() - - reset() - uncacheRead() -} - -type decodeError struct { - codecError - pos int -} - -func (d decodeError) Error() string { - return fmt.Sprintf("%s decode error [pos %d]: %v", d.name, d.pos, d.err) + initReadNext() + tryDecodeAsNil() bool + currentEncodedType() valueType + isBuiltinType(rt uintptr) bool + decodeBuiltin(rt uintptr, v interface{}) + //decodeNaked: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types). + decodeNaked() (v interface{}, vt valueType, decodeFurther bool) + decodeInt(bitsize uint8) (i int64) + decodeUint(bitsize uint8) (ui uint64) + decodeFloat(chkOverflow32 bool) (f float64) + decodeBool() (b bool) + // decodeString can also decode symbols + decodeString() (s string) + decodeBytes(bs []byte) (bsOut []byte, changed bool) + decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) + readMapLen() int + readArrayLen() int } -type decDriverNoopContainerReader struct{} - -func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { return } -func (x decDriverNoopContainerReader) ReadArrayElem() {} -func (x decDriverNoopContainerReader) ReadArrayEnd() {} -func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return } -func (x decDriverNoopContainerReader) ReadMapElemKey() {} -func (x decDriverNoopContainerReader) ReadMapElemValue() {} -func (x decDriverNoopContainerReader) ReadMapEnd() {} -func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return } - -// func (x decNoSeparator) uncacheRead() {} - -// DecodeOptions captures configuration options during decode. type DecodeOptions struct { - // MapType specifies type to use during schema-less decoding of a map in the stream. - // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true, - // else map[interface{}]interface{}. + // An instance of MapType is used during schema-less decoding of a map in the stream. + // If nil, we use map[interface{}]interface{} MapType reflect.Type - - // SliceType specifies type to use during schema-less decoding of an array in the stream. - // If nil (unset), we default to []interface{} for all formats. + // An instance of SliceType is used during schema-less decoding of an array in the stream. + // If nil, we use []interface{} SliceType reflect.Type - - // MaxInitLen defines the maxinum initial length that we "make" a collection - // (string, slice, map, chan). If 0 or negative, we default to a sensible value - // based on the size of an element in the collection. - // - // For example, when decoding, a stream may say that it has 2^64 elements. - // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash. - // Instead, we provision up to MaxInitLen, fill that up, and start appending after that. - MaxInitLen int - - // ReaderBufferSize is the size of the buffer used when reading. - // - // if > 0, we use a smart buffer internally for performance purposes. - ReaderBufferSize int - - // MaxDepth defines the maximum depth when decoding nested - // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024). - MaxDepth int16 - - // If ErrorIfNoField, return an error when decoding a map + // ErrorIfNoField controls whether an error is returned when decoding a map // from a codec stream into a struct, and no matching struct field is found. ErrorIfNoField bool - - // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded. - // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array, - // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set). - ErrorIfNoArrayExpand bool - - // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64). - SignedInteger bool - - // MapValueReset controls how we decode into a map value. - // - // By default, we MAY retrieve the mapping for a key, and then decode into that. - // However, especially with big maps, that retrieval may be expensive and unnecessary - // if the stream already contains all that is necessary to recreate the value. - // - // If true, we will never retrieve the previous mapping, - // but rather decode into a new value and set that in the map. - // - // If false, we will retrieve the previous mapping if necessary e.g. - // the previous mapping is a pointer, or is a struct or array with pre-set state, - // or is an interface. - MapValueReset bool - - // SliceElementReset: on decoding a slice, reset the element to a zero value first. - // - // concern: if the slice already contained some garbage, we will decode into that garbage. - SliceElementReset bool - - // InterfaceReset controls how we decode into an interface. - // - // By default, when we see a field that is an interface{...}, - // or a map with interface{...} value, we will attempt decoding into the - // "contained" value. - // - // However, this prevents us from reading a string into an interface{} - // that formerly contained a number. - // - // If true, we will decode into a new "blank" value, and set that in the interface. - // If false, we will decode into whatever is contained in the interface. - InterfaceReset bool - - // InternString controls interning of strings during decoding. - // - // Some handles, e.g. json, typically will read map keys as strings. - // If the set of keys are finite, it may help reduce allocation to - // look them up from a map (than to allocate them afresh). - // - // Note: Handles will be smart when using the intern functionality. - // Every string should not be interned. - // An excellent use-case for interning is struct field names, - // or map keys where key type is string. - InternString bool - - // PreferArrayOverSlice controls whether to decode to an array or a slice. - // - // This only impacts decoding into a nil interface{}. - // Consequently, it has no effect on codecgen. - // - // *Note*: This only applies if using go1.5 and above, - // as it requires reflect.ArrayOf support which was absent before go1.5. - PreferArrayOverSlice bool - - // DeleteOnNilMapValue controls how to decode a nil value in the stream. - // - // If true, we will delete the mapping of the key. - // Else, just set the mapping to the zero value of the type. - DeleteOnNilMapValue bool - - // RawToString controls how raw bytes in a stream are decoded into a nil interface{}. - // By default, they are decoded as []byte, but can be decoded as string (if configured). - RawToString bool -} - -// ------------------------------------------------ - -type unreadByteStatus uint8 - -// unreadByteStatus goes from -// undefined (when initialized) -- (read) --> canUnread -- (unread) --> canRead ... -const ( - unreadByteUndefined unreadByteStatus = iota - unreadByteCanRead - unreadByteCanUnread -) - -type ioDecReaderCommon struct { - r io.Reader // the reader passed in - - n uint // num read - - l byte // last byte - ls unreadByteStatus // last byte status - trb bool // tracking bytes turned on - _ bool - b [4]byte // tiny buffer for reading single bytes - - tr []byte // tracking bytes read } -func (z *ioDecReaderCommon) reset(r io.Reader) { - z.r = r - z.ls = unreadByteUndefined - z.l, z.n = 0, 0 - z.trb = false - if z.tr != nil { - z.tr = z.tr[:0] - } -} - -func (z *ioDecReaderCommon) numread() uint { - return z.n -} - -func (z *ioDecReaderCommon) track() { - if z.tr != nil { - z.tr = z.tr[:0] - } - z.trb = true -} - -func (z *ioDecReaderCommon) stopTrack() (bs []byte) { - z.trb = false - return z.tr -} - -// ------------------------------------------ +// ------------------------------------ -// ioDecReader is a decReader that reads off an io.Reader. -// -// It also has a fallback implementation of ByteScanner if needed. +// ioDecReader is a decReader that reads off an io.Reader type ioDecReader struct { - ioDecReaderCommon - - rr io.Reader - br io.ByteScanner - - x [scratchByteArrayLen]byte // for: get struct field name, swallow valueTypeBytes, etc - _ [1]uint64 // padding -} - -func (z *ioDecReader) reset(r io.Reader) { - z.ioDecReaderCommon.reset(r) - - var ok bool - z.rr = r - z.br, ok = r.(io.ByteScanner) - if !ok { - z.br = z - z.rr = z - } -} - -func (z *ioDecReader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return - } - var firstByte bool - if z.ls == unreadByteCanRead { - z.ls = unreadByteCanUnread - p[0] = z.l - if len(p) == 1 { - n = 1 - return - } - firstByte = true - p = p[1:] - } - n, err = z.r.Read(p) - if n > 0 { - if err == io.EOF && n == len(p) { - err = nil // read was successful, so postpone EOF (till next time) - } - z.l = p[n-1] - z.ls = unreadByteCanUnread - } - if firstByte { - n++ - } - return -} - -func (z *ioDecReader) ReadByte() (c byte, err error) { - n, err := z.Read(z.b[:1]) - if n == 1 { - c = z.b[0] - if err == io.EOF { - err = nil // read was successful, so postpone EOF (till next time) - } - } - return -} - -func (z *ioDecReader) UnreadByte() (err error) { - switch z.ls { - case unreadByteCanUnread: - z.ls = unreadByteCanRead - case unreadByteCanRead: - err = errDecUnreadByteLastByteNotRead - case unreadByteUndefined: - err = errDecUnreadByteNothingToRead - default: - err = errDecUnreadByteUnknown - } - return + r io.Reader + br io.ByteReader + x [8]byte //temp byte array re-used internally for efficiency } -func (z *ioDecReader) readx(n uint) (bs []byte) { - if n == 0 { +func (z *ioDecReader) readn(n int) (bs []byte) { + if n <= 0 { return } - if n < uint(len(z.x)) { - bs = z.x[:n] - } else { - bs = make([]byte, n) - } - if _, err := decReadFull(z.rr, bs); err != nil { + bs = make([]byte, n) + if _, err := io.ReadAtLeast(z.r, bs, n); err != nil { panic(err) } - z.n += uint(len(bs)) - if z.trb { - z.tr = append(z.tr, bs...) - } return } func (z *ioDecReader) readb(bs []byte) { - if len(bs) == 0 { - return - } - if _, err := decReadFull(z.rr, bs); err != nil { + if _, err := io.ReadAtLeast(z.r, bs, len(bs)); err != nil { panic(err) } - z.n += uint(len(bs)) - if z.trb { - z.tr = append(z.tr, bs...) - } } -func (z *ioDecReader) readn1eof() (b uint8, eof bool) { - b, err := z.br.ReadByte() - if err == nil { - z.n++ - if z.trb { - z.tr = append(z.tr, b) +func (z *ioDecReader) readn1() uint8 { + if z.br != nil { + b, err := z.br.ReadByte() + if err != nil { + panic(err) } - } else if err == io.EOF { - eof = true - } else { - panic(err) + return b } - return + z.readb(z.x[:1]) + return z.x[0] } -func (z *ioDecReader) readn1() (b uint8) { - b, err := z.br.ReadByte() - if err == nil { - z.n++ - if z.trb { - z.tr = append(z.tr, b) - } - return - } - panic(err) +func (z *ioDecReader) readUint16() uint16 { + z.readb(z.x[:2]) + return bigen.Uint16(z.x[:2]) } -func (z *ioDecReader) skip(accept *bitset256) (token byte) { - var eof bool - // for { - // token, eof = z.readn1eof() - // if eof { - // return - // } - // if accept.isset(token) { - // continue - // } - // return - // } -LOOP: - token, eof = z.readn1eof() - if eof { - return - } - if accept.isset(token) { - goto LOOP - } - return +func (z *ioDecReader) readUint32() uint32 { + z.readb(z.x[:4]) + return bigen.Uint32(z.x[:4]) } -func (z *ioDecReader) readTo(in []byte, accept *bitset256) []byte { - // out = in - - // for { - // token, eof := z.readn1eof() - // if eof { - // return - // } - // if accept.isset(token) { - // out = append(out, token) - // } else { - // z.unreadn1() - // return - // } - // } -LOOP: - token, eof := z.readn1eof() - if eof { - return in - } - if accept.isset(token) { - // out = append(out, token) - in = append(in, token) - goto LOOP - } - z.unreadn1() - return in -} - -func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) { - out = in - // for { - // token, eof := z.readn1eof() - // if eof { - // panic(io.EOF) - // } - // out = append(out, token) - // if token == stop { - // return - // } - // } -LOOP: - token, eof := z.readn1eof() - if eof { - panic(io.EOF) - } - out = append(out, token) - if token == stop { - return - } - goto LOOP -} - -//go:noinline -func (z *ioDecReader) unreadn1() { - err := z.br.UnreadByte() - if err != nil { - panic(err) - } - z.n-- - if z.trb { - if l := len(z.tr) - 1; l >= 0 { - z.tr = z.tr[:l] - } - } +func (z *ioDecReader) readUint64() uint64 { + z.readb(z.x[:8]) + return bigen.Uint64(z.x[:8]) } // ------------------------------------ -type bufioDecReader struct { - ioDecReaderCommon - - c uint // cursor - buf []byte - - bytesBufPooler - - // err error - - // Extensions can call Decode() within a current Decode() call. - // We need to know when the top level Decode() call returns, - // so we can decide whether to Release() or not. - calls uint16 // what depth in mustDecode are we in now. - - _ [6]uint8 // padding - - _ [1]uint64 // padding +// bytesDecReader is a decReader that reads off a byte slice with zero copying +type bytesDecReader struct { + b []byte // data + c int // cursor + a int // available } -func (z *bufioDecReader) reset(r io.Reader, bufsize int) { - z.ioDecReaderCommon.reset(r) - z.c = 0 - z.calls = 0 - if cap(z.buf) >= bufsize { - z.buf = z.buf[:0] - } else { - z.buf = z.bytesBufPooler.get(bufsize)[:0] - // z.buf = make([]byte, 0, bufsize) +func (z *bytesDecReader) consume(n int) (oldcursor int) { + if z.a == 0 { + panic(io.EOF) } -} - -func (z *bufioDecReader) release() { - z.buf = nil - z.bytesBufPooler.end() -} - -func (z *bufioDecReader) readb(p []byte) { - var n = uint(copy(p, z.buf[z.c:])) - z.n += n - z.c += n - if len(p) == int(n) { - if z.trb { - z.tr = append(z.tr, p...) // cost=9 - } - } else { - z.readbFill(p, n) + if n > z.a { + decErr("Trying to read %v bytes. Only %v available", n, z.a) } + // z.checkAvailable(n) + oldcursor = z.c + z.c = oldcursor + n + z.a = z.a - n + return } -//go:noinline - fallback when z.buf is consumed -func (z *bufioDecReader) readbFill(p0 []byte, n uint) { - // at this point, there's nothing in z.buf to read (z.buf is fully consumed) - p := p0[n:] - var n2 uint - var err error - if len(p) > cap(z.buf) { - n2, err = decReadFull(z.r, p) - if err != nil { - panic(err) - } - n += n2 - z.n += n2 - // always keep last byte in z.buf - z.buf = z.buf[:1] - z.buf[0] = p[len(p)-1] - z.c = 1 - if z.trb { - z.tr = append(z.tr, p0[:n]...) - } +func (z *bytesDecReader) readn(n int) (bs []byte) { + if n <= 0 { return } - // z.c is now 0, and len(p) <= cap(z.buf) -LOOP: - // for len(p) > 0 && z.err == nil { - if len(p) > 0 { - z.buf = z.buf[0:cap(z.buf)] - var n1 int - n1, err = z.r.Read(z.buf) - n2 = uint(n1) - if n2 == 0 && err != nil { - panic(err) - } - z.buf = z.buf[:n2] - n2 = uint(copy(p, z.buf)) - z.c = n2 - n += n2 - z.n += n2 - p = p[n2:] - goto LOOP - } - if z.c == 0 { - z.buf = z.buf[:1] - z.buf[0] = p[len(p)-1] - z.c = 1 - } - if z.trb { - z.tr = append(z.tr, p0[:n]...) - } -} - -func (z *bufioDecReader) readn1() (b byte) { - // fast-path, so we elide calling into Read() most of the time - if z.c < uint(len(z.buf)) { - b = z.buf[z.c] - z.c++ - z.n++ - if z.trb { - z.tr = append(z.tr, b) - } - } else { // meaning z.c == len(z.buf) or greater ... so need to fill - z.readbFill(z.b[:1], 0) - b = z.b[0] - } + c0 := z.consume(n) + bs = z.b[c0:z.c] return } -func (z *bufioDecReader) unreadn1() { - if z.c == 0 { - panic(errDecUnreadByteNothingToRead) - } - z.c-- - z.n-- - if z.trb { - z.tr = z.tr[:len(z.tr)-1] - } +func (z *bytesDecReader) readb(bs []byte) { + copy(bs, z.readn(len(bs))) } -func (z *bufioDecReader) readx(n uint) (bs []byte) { - if n == 0 { - // return - } else if z.c+n <= uint(len(z.buf)) { - bs = z.buf[z.c : z.c+n] - z.n += n - z.c += n - if z.trb { - z.tr = append(z.tr, bs...) - } - } else { - bs = make([]byte, n) - // n no longer used - can reuse - n = uint(copy(bs, z.buf[z.c:])) - z.n += n - z.c += n - z.readbFill(bs, n) - } - return +func (z *bytesDecReader) readn1() uint8 { + c0 := z.consume(1) + return z.b[c0] } -//go:noinline - track called by Decoder.nextValueBytes() (called by jsonUnmarshal,rawBytes) -func (z *bufioDecReader) doTrack(y uint) { - z.tr = append(z.tr, z.buf[z.c:y]...) // cost=14??? -} +// Use binaryEncoding helper for 4 and 8 bits, but inline it for 2 bits +// creating temp slice variable and copying it to helper function is expensive +// for just 2 bits. -func (z *bufioDecReader) skipLoopFn(i uint) { - z.n += (i - z.c) - 1 - i++ - if z.trb { - // z.tr = append(z.tr, z.buf[z.c:i]...) - z.doTrack(i) - } - z.c = i +func (z *bytesDecReader) readUint16() uint16 { + c0 := z.consume(2) + return uint16(z.b[c0+1]) | uint16(z.b[c0])<<8 } -func (z *bufioDecReader) skip(accept *bitset256) (token byte) { - // token, _ = z.search(nil, accept, 0, 1); return - - // for i := z.c; i < len(z.buf); i++ { - // if token = z.buf[i]; !accept.isset(token) { - // z.skipLoopFn(i) - // return - // } - // } - - i := z.c -LOOP: - if i < uint(len(z.buf)) { - // inline z.skipLoopFn(i) and refactor, so cost is within inline budget - token = z.buf[i] - i++ - if accept.isset(token) { - goto LOOP - } - z.n += i - 2 - z.c - if z.trb { - z.doTrack(i) - } - z.c = i - return - } - return z.skipFill(accept) +func (z *bytesDecReader) readUint32() uint32 { + c0 := z.consume(4) + return bigen.Uint32(z.b[c0:z.c]) } -func (z *bufioDecReader) skipFill(accept *bitset256) (token byte) { - z.n += uint(len(z.buf)) - z.c - if z.trb { - z.tr = append(z.tr, z.buf[z.c:]...) - } - var n2 int - var err error - for { - z.c = 0 - z.buf = z.buf[0:cap(z.buf)] - n2, err = z.r.Read(z.buf) - if n2 == 0 && err != nil { - panic(err) - } - z.buf = z.buf[:n2] - var i int - for i, token = range z.buf { - if !accept.isset(token) { - z.skipLoopFn(uint(i)) - return - } - } - // for i := 0; i < n2; i++ { - // if token = z.buf[i]; !accept.isset(token) { - // z.skipLoopFn(i) - // return - // } - // } - z.n += uint(n2) - if z.trb { - z.tr = append(z.tr, z.buf...) - } - } +func (z *bytesDecReader) readUint64() uint64 { + c0 := z.consume(8) + return bigen.Uint64(z.b[c0:z.c]) } -func (z *bufioDecReader) readToLoopFn(i uint, out0 []byte) (out []byte) { - // out0 is never nil - z.n += (i - z.c) - 1 - out = append(out0, z.buf[z.c:i]...) - if z.trb { - z.doTrack(i) - } - z.c = i - return -} +// ------------------------------------ -func (z *bufioDecReader) readTo(in []byte, accept *bitset256) (out []byte) { - // _, out = z.search(in, accept, 0, 2); return - - // for i := z.c; i < len(z.buf); i++ { - // if !accept.isset(z.buf[i]) { - // return z.readToLoopFn(i, nil) - // } - // } - - i := z.c -LOOP: - if i < uint(len(z.buf)) { - if !accept.isset(z.buf[i]) { - // return z.readToLoopFn(i, nil) - // inline readToLoopFn here (for performance) - z.n += (i - z.c) - 1 - out = z.buf[z.c:i] - if z.trb { - z.doTrack(i) - } - z.c = i - return - } - i++ - goto LOOP - } - return z.readToFill(in, accept) +// decFnInfo has methods for registering handling decoding of a specific type +// based on some characteristics (builtin, extension, reflect Kind, etc) +type decFnInfo struct { + ti *typeInfo + d *Decoder + dd decDriver + xfFn func(reflect.Value, []byte) error + xfTag byte + array bool } -func (z *bufioDecReader) readToFill(in []byte, accept *bitset256) (out []byte) { - z.n += uint(len(z.buf)) - z.c - out = append(in, z.buf[z.c:]...) - if z.trb { - z.tr = append(z.tr, z.buf[z.c:]...) - } - var n2 int - var err error - for { - z.c = 0 - z.buf = z.buf[0:cap(z.buf)] - n2, err = z.r.Read(z.buf) - if n2 == 0 && err != nil { - if err == io.EOF { - return // readTo should read until it matches or end is reached - } - panic(err) - } - z.buf = z.buf[:n2] - for i, token := range z.buf { - if !accept.isset(token) { - return z.readToLoopFn(uint(i), out) - } - } - // for i := 0; i < n2; i++ { - // if !accept.isset(z.buf[i]) { - // return z.readToLoopFn(i, out) - // } - // } - out = append(out, z.buf...) - z.n += uint(n2) - if z.trb { - z.tr = append(z.tr, z.buf...) - } - } +func (f *decFnInfo) builtin(rv reflect.Value) { + f.dd.decodeBuiltin(f.ti.rtid, rv.Addr().Interface()) } -func (z *bufioDecReader) readUntilLoopFn(i uint, out0 []byte) (out []byte) { - z.n += (i - z.c) - 1 - i++ - out = append(out0, z.buf[z.c:i]...) - if z.trb { - // z.tr = append(z.tr, z.buf[z.c:i]...) - z.doTrack(i) - } - z.c = i - return +func (f *decFnInfo) rawExt(rv reflect.Value) { + xtag, xbs := f.dd.decodeExt(false, 0) + rv.Field(0).SetUint(uint64(xtag)) + rv.Field(1).SetBytes(xbs) } -func (z *bufioDecReader) readUntil(in []byte, stop byte) (out []byte) { - // _, out = z.search(in, nil, stop, 4); return - - // for i := z.c; i < len(z.buf); i++ { - // if z.buf[i] == stop { - // return z.readUntilLoopFn(i, nil) - // } - // } - - i := z.c -LOOP: - if i < uint(len(z.buf)) { - if z.buf[i] == stop { - // inline readUntilLoopFn - // return z.readUntilLoopFn(i, nil) - z.n += (i - z.c) - 1 - i++ - out = z.buf[z.c:i] - if z.trb { - z.doTrack(i) - } - z.c = i - return - } - i++ - goto LOOP +func (f *decFnInfo) ext(rv reflect.Value) { + _, xbs := f.dd.decodeExt(true, f.xfTag) + if fnerr := f.xfFn(rv, xbs); fnerr != nil { + panic(fnerr) } - return z.readUntilFill(in, stop) } -func (z *bufioDecReader) readUntilFill(in []byte, stop byte) (out []byte) { - z.n += uint(len(z.buf)) - z.c - out = append(in, z.buf[z.c:]...) - if z.trb { - z.tr = append(z.tr, z.buf[z.c:]...) - } - var n1 int - var n2 uint - var err error - for { - z.c = 0 - z.buf = z.buf[0:cap(z.buf)] - n1, err = z.r.Read(z.buf) - n2 = uint(n1) - if n2 == 0 && err != nil { - panic(err) - } - z.buf = z.buf[:n2] - for i, token := range z.buf { - if token == stop { - return z.readUntilLoopFn(uint(i), out) +func (f *decFnInfo) binaryMarshal(rv reflect.Value) { + var bm binaryUnmarshaler + if f.ti.unmIndir == -1 { + bm = rv.Addr().Interface().(binaryUnmarshaler) + } else if f.ti.unmIndir == 0 { + bm = rv.Interface().(binaryUnmarshaler) + } else { + for j, k := int8(0), f.ti.unmIndir; j < k; j++ { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) } + rv = rv.Elem() } - // for i := 0; i < n2; i++ { - // if z.buf[i] == stop { - // return z.readUntilLoopFn(i, out) - // } - // } - out = append(out, z.buf...) - z.n += n2 - if z.trb { - z.tr = append(z.tr, z.buf...) - } + bm = rv.Interface().(binaryUnmarshaler) } -} - -// ------------------------------------ - -var errBytesDecReaderCannotUnread = errors.New("cannot unread last byte read") - -// bytesDecReader is a decReader that reads off a byte slice with zero copying -type bytesDecReader struct { - b []byte // data - c uint // cursor - t uint // track start - // a int // available -} - -func (z *bytesDecReader) reset(in []byte) { - z.b = in - // z.a = len(in) - z.c = 0 - z.t = 0 -} - -func (z *bytesDecReader) numread() uint { - return z.c -} - -func (z *bytesDecReader) unreadn1() { - if z.c == 0 || len(z.b) == 0 { - panic(errBytesDecReaderCannotUnread) - } - z.c-- - // z.a++ -} - -func (z *bytesDecReader) readx(n uint) (bs []byte) { - // slicing from a non-constant start position is more expensive, - // as more computation is required to decipher the pointer start position. - // However, we do it only once, and it's better than reslicing both z.b and return value. - - // if n <= 0 { - // } else if z.a == 0 { - // panic(io.EOF) - // } else if n > z.a { - // panic(io.ErrUnexpectedEOF) - // } else { - // c0 := z.c - // z.c = c0 + n - // z.a = z.a - n - // bs = z.b[c0:z.c] - // } - // return - - if n != 0 { - z.c += n - if z.c > uint(len(z.b)) { - z.c = uint(len(z.b)) - panic(io.EOF) - } - bs = z.b[z.c-n : z.c] + xbs, _ := f.dd.decodeBytes(nil) + if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil { + panic(fnerr) } - return - - // if n == 0 { - // } else if z.c+n > uint(len(z.b)) { - // z.c = uint(len(z.b)) - // panic(io.EOF) - // } else { - // z.c += n - // bs = z.b[z.c-n : z.c] - // } - // return - - // if n == 0 { - // return - // } - // if z.c == uint(len(z.b)) { - // panic(io.EOF) - // } - // if z.c+n > uint(len(z.b)) { - // panic(io.ErrUnexpectedEOF) - // } - // // z.a -= n - // z.c += n - // return z.b[z.c-n : z.c] } -func (z *bytesDecReader) readb(bs []byte) { - copy(bs, z.readx(uint(len(bs)))) +func (f *decFnInfo) kErr(rv reflect.Value) { + decErr("Unhandled value for kind: %v: %s", rv.Kind(), msgBadDesc) } -func (z *bytesDecReader) readn1() (v uint8) { - if z.c == uint(len(z.b)) { - panic(io.EOF) - } - v = z.b[z.c] - z.c++ - // z.a-- - return -} - -// func (z *bytesDecReader) readn1eof() (v uint8, eof bool) { -// if z.a == 0 { -// eof = true -// return -// } -// v = z.b[z.c] -// z.c++ -// z.a-- -// return -// } - -func (z *bytesDecReader) skip(accept *bitset256) (token byte) { - i := z.c - // if i == len(z.b) { - // goto END - // // panic(io.EOF) - // } - - // Replace loop with goto construct, so that this can be inlined - // for i := z.c; i < blen; i++ { - // if !accept.isset(z.b[i]) { - // token = z.b[i] - // i++ - // z.a -= (i - z.c) - // z.c = i - // return - // } - // } - - // i := z.c -LOOP: - if i < uint(len(z.b)) { - token = z.b[i] - i++ - if accept.isset(token) { - goto LOOP - } - // z.a -= (i - z.c) - z.c = i - return - } - // END: - panic(io.EOF) - // // z.a = 0 - // z.c = blen - // return +func (f *decFnInfo) kString(rv reflect.Value) { + rv.SetString(f.dd.decodeString()) } -func (z *bytesDecReader) readTo(_ []byte, accept *bitset256) (out []byte) { - return z.readToNoInput(accept) +func (f *decFnInfo) kBool(rv reflect.Value) { + rv.SetBool(f.dd.decodeBool()) } -func (z *bytesDecReader) readToNoInput(accept *bitset256) (out []byte) { - i := z.c - if i == uint(len(z.b)) { - panic(io.EOF) - } - - // Replace loop with goto construct, so that this can be inlined - // for i := z.c; i < blen; i++ { - // if !accept.isset(z.b[i]) { - // out = z.b[z.c:i] - // z.a -= (i - z.c) - // z.c = i - // return - // } - // } - // out = z.b[z.c:] - // z.a, z.c = 0, blen - // return - - // i := z.c - // LOOP: - // if i < blen { - // if accept.isset(z.b[i]) { - // i++ - // goto LOOP - // } - // out = z.b[z.c:i] - // z.a -= (i - z.c) - // z.c = i - // return - // } - // out = z.b[z.c:] - // // z.a, z.c = 0, blen - // z.a = 0 - // z.c = blen - // return - - // c := i -LOOP: - if i < uint(len(z.b)) { - if accept.isset(z.b[i]) { - i++ - goto LOOP - } - } - - out = z.b[z.c:i] - // z.a -= (i - z.c) - z.c = i - return // z.b[c:i] - // z.c, i = i, z.c - // return z.b[i:z.c] +func (f *decFnInfo) kInt(rv reflect.Value) { + rv.SetInt(f.dd.decodeInt(intBitsize)) } -func (z *bytesDecReader) readUntil(_ []byte, stop byte) (out []byte) { - return z.readUntilNoInput(stop) +func (f *decFnInfo) kInt64(rv reflect.Value) { + rv.SetInt(f.dd.decodeInt(64)) } -func (z *bytesDecReader) readUntilNoInput(stop byte) (out []byte) { - i := z.c - // if i == len(z.b) { - // panic(io.EOF) - // } - - // Replace loop with goto construct, so that this can be inlined - // for i := z.c; i < blen; i++ { - // if z.b[i] == stop { - // i++ - // out = z.b[z.c:i] - // z.a -= (i - z.c) - // z.c = i - // return - // } - // } -LOOP: - if i < uint(len(z.b)) { - if z.b[i] == stop { - i++ - out = z.b[z.c:i] - // z.a -= (i - z.c) - z.c = i - return - } - i++ - goto LOOP - } - // z.a = 0 - // z.c = blen - panic(io.EOF) +func (f *decFnInfo) kInt32(rv reflect.Value) { + rv.SetInt(f.dd.decodeInt(32)) } -func (z *bytesDecReader) track() { - z.t = z.c +func (f *decFnInfo) kInt8(rv reflect.Value) { + rv.SetInt(f.dd.decodeInt(8)) } -func (z *bytesDecReader) stopTrack() (bs []byte) { - return z.b[z.t:z.c] +func (f *decFnInfo) kInt16(rv reflect.Value) { + rv.SetInt(f.dd.decodeInt(16)) } -// ---------------------------------------- - -// func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) { -// d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv)) -// } - -func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) { - d.d.DecodeExt(rv2i(rv), 0, nil) +func (f *decFnInfo) kFloat32(rv reflect.Value) { + rv.SetFloat(f.dd.decodeFloat(true)) } -func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) { - d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn) +func (f *decFnInfo) kFloat64(rv reflect.Value) { + rv.SetFloat(f.dd.decodeFloat(false)) } -func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) { - rv2i(rv).(Selfer).CodecDecodeSelf(d) +func (f *decFnInfo) kUint8(rv reflect.Value) { + rv.SetUint(f.dd.decodeUint(8)) } -func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) { - bm := rv2i(rv).(encoding.BinaryUnmarshaler) - xbs := d.d.DecodeBytes(nil, true) - if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil { - panic(fnerr) - } +func (f *decFnInfo) kUint64(rv reflect.Value) { + rv.SetUint(f.dd.decodeUint(64)) } -func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) { - tm := rv2i(rv).(encoding.TextUnmarshaler) - fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes()) - if fnerr != nil { - panic(fnerr) - } +func (f *decFnInfo) kUint(rv reflect.Value) { + rv.SetUint(f.dd.decodeUint(uintBitsize)) } -func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) { - tm := rv2i(rv).(jsonUnmarshaler) - // bs := d.d.DecodeBytes(d.b[:], true, true) - // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - fnerr := tm.UnmarshalJSON(d.nextValueBytes()) - if fnerr != nil { - panic(fnerr) - } +func (f *decFnInfo) kUint32(rv reflect.Value) { + rv.SetUint(f.dd.decodeUint(32)) } -func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) { - d.errorf("no decoding function defined for kind %v", rv.Kind()) +func (f *decFnInfo) kUint16(rv reflect.Value) { + rv.SetUint(f.dd.decodeUint(16)) } -// var kIntfCtr uint64 +// func (f *decFnInfo) kPtr(rv reflect.Value) { +// debugf(">>>>>>> ??? decode kPtr called - shouldn't get called") +// if rv.IsNil() { +// rv.Set(reflect.New(rv.Type().Elem())) +// } +// f.d.decodeValue(rv.Elem()) +// } -func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) { - // nil interface: - // use some hieristics to decode it appropriately - // based on the detected next value in the stream. - n := d.naked() - d.d.DecodeNaked() - if n.v == valueTypeNil { +func (f *decFnInfo) kInterface(rv reflect.Value) { + // debugf("\t===> kInterface") + if !rv.IsNil() { + f.d.decodeValue(rv.Elem()) return } - // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader). - if f.ti.numMeth > 0 { - d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth) + // nil interface: + // use some hieristics to set the nil interface to an + // appropriate value based on the first byte read (byte descriptor bd) + v, vt, decodeFurther := f.dd.decodeNaked() + if vt == valueTypeNil { return } - // var useRvn bool - switch n.v { + // Cannot decode into nil interface with methods (e.g. error, io.Reader, etc) + // if non-nil value in stream. + if num := f.ti.rt.NumMethod(); num > 0 { + decErr("decodeValue: Cannot decode non-nil codec value into nil %v (%v methods)", + f.ti.rt, num) + } + var rvn reflect.Value + var useRvn bool + switch vt { case valueTypeMap: - // if json, default to a map type with string keys - mtid := d.mtid - if mtid == 0 { - if d.jsms { - mtid = mapStrIntfTypId - } else { - mtid = mapIntfIntfTypId - } - } - if mtid == mapIntfIntfTypId { - var v2 map[interface{}]interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() - } else if mtid == mapStrIntfTypId { // for json performance - var v2 map[string]interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() + if f.d.h.MapType == nil { + var m2 map[interface{}]interface{} + v = &m2 } else { - if d.mtr { - rvn = reflect.New(d.h.MapType) - d.decode(rv2i(rvn)) - rvn = rvn.Elem() - } else { - rvn = reflect.New(d.h.MapType).Elem() - d.decodeValue(rvn, nil, true) - } + rvn = reflect.New(f.d.h.MapType).Elem() + useRvn = true } case valueTypeArray: - if d.stid == 0 || d.stid == intfSliceTypId { - var v2 []interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() - if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice { - rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem() - reflect.Copy(rvn2, rvn) - rvn = rvn2 - } + if f.d.h.SliceType == nil { + var m2 []interface{} + v = &m2 } else { - if d.str { - rvn = reflect.New(d.h.SliceType) - d.decode(rv2i(rvn)) - rvn = rvn.Elem() - } else { - rvn = reflect.New(d.h.SliceType).Elem() - d.decodeValue(rvn, nil, true) - } + rvn = reflect.New(f.d.h.SliceType).Elem() + useRvn = true } case valueTypeExt: - var v interface{} - tag, bytes := n.u, n.l // calling decode below might taint the values - if bytes == nil { - d.decode(&v) - } - bfn := d.h.getExtForTag(tag) + re := v.(*RawExt) + var bfn func(reflect.Value, []byte) error + rvn, bfn = f.d.h.getDecodeExtForTag(re.Tag) if bfn == nil { - var re RawExt - re.Tag = tag - re.Data = detachZeroCopyBytes(d.bytes, nil, bytes) - re.Value = v - rvn = reflect.ValueOf(&re).Elem() - } else { - rvnA := reflect.New(bfn.rt) - if bytes != nil { - bfn.ext.ReadExt(rv2i(rvnA), bytes) - } else { - bfn.ext.UpdateExt(rv2i(rvnA), v) - } - rvn = rvnA.Elem() - } - case valueTypeNil: - // no-op - case valueTypeInt: - rvn = n.ri() - case valueTypeUint: - rvn = n.ru() - case valueTypeFloat: - rvn = n.rf() - case valueTypeBool: - rvn = n.rb() - case valueTypeString, valueTypeSymbol: - rvn = n.rs() - case valueTypeBytes: - rvn = n.rl() - case valueTypeTime: - rvn = n.rt() - default: - panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v) - } - return -} - -func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) { - // Note: - // A consequence of how kInterface works, is that - // if an interface already contains something, we try - // to decode into what was there before. - // We do not replace with a generic value (as got from decodeNaked). - - // every interface passed here MUST be settable. - var rvn reflect.Value - if rv.IsNil() || d.h.InterfaceReset { - // check if mapping to a type: if so, initialize it and move on - rvn = d.h.intf2impl(f.ti.rtid) - if rvn.IsValid() { - rv.Set(rvn) - } else { - rvn = d.kInterfaceNaked(f) - if rvn.IsValid() { - rv.Set(rvn) - } else if d.h.InterfaceReset { - // reset to zero value based on current type in there. - rv.Set(reflect.Zero(rv.Elem().Type())) - } - return + rvn = reflect.ValueOf(*re) + } else if fnerr := bfn(rvn, re.Data); fnerr != nil { + panic(fnerr) } - } else { - // now we have a non-nil interface value, meaning it contains a type - rvn = rv.Elem() - } - if d.d.TryDecodeAsNil() { - rv.Set(reflect.Zero(rvn.Type())) + rv.Set(rvn) return } - - // Note: interface{} is settable, but underlying type may not be. - // Consequently, we MAY have to create a decodable value out of the underlying value, - // decode into it, and reset the interface itself. - // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type()) - - rvn2, canDecode := isDecodeable(rvn) - if canDecode { - d.decodeValue(rvn2, nil, true) - return + if decodeFurther { + if useRvn { + f.d.decodeValue(rvn) + } else if v != nil { + // this v is a pointer, so we need to dereference it when done + f.d.decode(v) + rvn = reflect.ValueOf(v).Elem() + useRvn = true + } } - - rvn2 = reflect.New(rvn.Type()).Elem() - rvn2.Set(rvn) - d.decodeValue(rvn2, nil, true) - rv.Set(rvn2) -} - -func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) { - // use if-else-if, not switch (which compiles to binary-search) - // since keyType is typically valueTypeString, branch prediction is pretty good. - - if keyType == valueTypeString { - rvkencname = dd.DecodeStringAsBytes() - } else if keyType == valueTypeInt { - rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10) - } else if keyType == valueTypeUint { - rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10) - } else if keyType == valueTypeFloat { - rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64) - } else { - rvkencname = dd.DecodeStringAsBytes() + if useRvn { + rv.Set(rvn) + } else if v != nil { + rv.Set(reflect.ValueOf(v)) } - return rvkencname } -func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) { +func (f *decFnInfo) kStruct(rv reflect.Value) { fti := f.ti - dd := d.d - elemsep := d.esep - sfn := structFieldNode{v: rv, update: true} - ctyp := dd.ContainerType() - var mf MissingFielder - if fti.mf { - mf = rv2i(rv).(MissingFielder) - } else if fti.mfp { - mf = rv2i(rv.Addr()).(MissingFielder) - } - if ctyp == valueTypeMap { - containerLen := dd.ReadMapStart() + if currEncodedType := f.dd.currentEncodedType(); currEncodedType == valueTypeMap { + containerLen := f.dd.readMapLen() if containerLen == 0 { - dd.ReadMapEnd() return } - d.depthIncr() - tisfi := fti.sfiSort - hasLen := containerLen >= 0 - - var rvkencname []byte - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if elemsep { - dd.ReadMapElemKey() - } - rvkencname = decStructFieldKey(dd, fti.keyType, &d.b) - if elemsep { - dd.ReadMapElemValue() - } + tisfi := fti.sfi + for j := 0; j < containerLen; j++ { + // var rvkencname string + // ddecode(&rvkencname) + f.dd.initReadNext() + rvkencname := f.dd.decodeString() + // rvksi := ti.getForEncName(rvkencname) if k := fti.indexForEncName(rvkencname); k > -1 { - si := tisfi[k] - if dd.TryDecodeAsNil() { - si.setToZeroValue(rv) + sfik := tisfi[k] + if sfik.i != -1 { + f.d.decodeValue(rv.Field(int(sfik.i))) } else { - d.decodeValue(sfn.field(si), nil, true) - } - } else if mf != nil { - // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode - name2 := rvkencname - rvkencname = make([]byte, len(rvkencname)) - copy(rvkencname, name2) - - var f interface{} - // xdebugf("kStruct: mf != nil: before decode: rvkencname: %s", rvkencname) - d.decode(&f) - // xdebugf("kStruct: mf != nil: after decode: rvkencname: %s", rvkencname) - if !mf.CodecMissingField(rvkencname, f) && d.h.ErrorIfNoField { - d.errorf("no matching struct field found when decoding stream map with key: %s ", - stringView(rvkencname)) + f.d.decEmbeddedField(rv, sfik.is) } + // f.d.decodeValue(ti.field(k, rv)) } else { - d.structFieldNotFound(-1, stringView(rvkencname)) + if f.d.h.ErrorIfNoField { + decErr("No matching struct field found when decoding stream map with key: %v", + rvkencname) + } else { + var nilintf0 interface{} + f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem()) + } } - // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop } - dd.ReadMapEnd() - d.depthDecr() - } else if ctyp == valueTypeArray { - containerLen := dd.ReadArrayStart() + } else if currEncodedType == valueTypeArray { + containerLen := f.dd.readArrayLen() if containerLen == 0 { - dd.ReadArrayEnd() return } - d.depthIncr() - // Not much gain from doing it two ways for array. - // Arrays are not used as much for structs. - hasLen := containerLen >= 0 - var checkbreak bool - for j, si := range fti.sfiSrc { - if hasLen && j == containerLen { - break - } - if !hasLen && dd.CheckBreak() { - checkbreak = true + for j, si := range fti.sfip { + if j == containerLen { break } - if elemsep { - dd.ReadArrayElem() - } - if dd.TryDecodeAsNil() { - si.setToZeroValue(rv) + if si.i != -1 { + f.d.decodeValue(rv.Field(int(si.i))) } else { - d.decodeValue(sfn.field(si), nil, true) + f.d.decEmbeddedField(rv, si.is) } } - if (hasLen && containerLen > len(fti.sfiSrc)) || (!hasLen && !checkbreak) { + if containerLen > len(fti.sfip) { // read remaining values and throw away - for j := len(fti.sfiSrc); ; j++ { - if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) { - break - } - if elemsep { - dd.ReadArrayElem() - } - d.structFieldNotFound(j, "") + for j := len(fti.sfip); j < containerLen; j++ { + var nilintf0 interface{} + f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem()) } } - dd.ReadArrayEnd() - d.depthDecr() } else { - d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct) - return + decErr("Only encoded map or array can be decoded into a struct. (valueType: %x)", + currEncodedType) } } -func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) { +func (f *decFnInfo) kSlice(rv reflect.Value) { // A slice can be set from a map or array in stream. - // This way, the order can be kept (as order is lost with map). - ti := f.ti - if f.seq == seqTypeChan && ti.chandir&uint8(reflect.SendDir) == 0 { - d.errorf("receive-only channel cannot be decoded") - } - dd := d.d - rtelem0 := ti.elem - ctyp := dd.ContainerType() - if ctyp == valueTypeBytes || ctyp == valueTypeString { - // you can only decode bytes or string in the stream into a slice or array of bytes - if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) { - d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt) - } - if f.seq == seqTypeChan { - bs2 := dd.DecodeBytes(nil, true) - irv := rv2i(rv) - ch, ok := irv.(chan<- byte) - if !ok { - ch = irv.(chan byte) - } - for _, b := range bs2 { - ch <- b - } - } else { - rvbs := rv.Bytes() - bs2 := dd.DecodeBytes(rvbs, false) - // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) { - if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) { - if rv.CanSet() { - rv.SetBytes(bs2) - } else if len(rvbs) > 0 && len(bs2) > 0 { - copy(rvbs, bs2) - } - } - } - return - } - - // array := f.seq == seqTypeChan + currEncodedType := f.dd.currentEncodedType() - slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - - // an array can never return a nil slice. so no need to check f.array here. - if containerLenS == 0 { - if rv.CanSet() { - if f.seq == seqTypeSlice { - if rv.IsNil() { - rv.Set(reflect.MakeSlice(ti.rt, 0, 0)) - } else { - rv.SetLen(0) - } - } else if f.seq == seqTypeChan { - if rv.IsNil() { - rv.Set(reflect.MakeChan(ti.rt, 0)) - } + switch currEncodedType { + case valueTypeBytes, valueTypeString: + if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 { + if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 { + rv.SetBytes(bs2) } - } - slh.End() - return - } - - d.depthIncr() - - rtelem0Size := int(rtelem0.Size()) - rtElem0Kind := rtelem0.Kind() - rtelem0Mut := !isImmutableKind(rtElem0Kind) - rtelem := rtelem0 - rtelemkind := rtelem.Kind() - for rtelemkind == reflect.Ptr { - rtelem = rtelem.Elem() - rtelemkind = rtelem.Kind() - } - - var fn *codecFn - - var rvCanset = rv.CanSet() - var rvChanged bool - var rv0 = rv - var rv9 reflect.Value - - rvlen := rv.Len() - rvcap := rv.Cap() - hasLen := containerLenS > 0 - if hasLen && f.seq == seqTypeSlice { - if containerLenS > rvcap { - oldRvlenGtZero := rvlen > 0 - rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size())) - if rvlen <= rvcap { - if rvCanset { - rv.SetLen(rvlen) - } - } else if rvCanset { - rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) - rvcap = rvlen - rvChanged = true - } else { - d.errorf("cannot decode into non-settable slice") - } - if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) { - reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap) - } - } else if containerLenS != rvlen { - rvlen = containerLenS - if rvCanset { - rv.SetLen(rvlen) - } - // else { - // rv = rv.Slice(0, rvlen) - // rvChanged = true - // d.errorf("cannot decode into non-settable slice") - // } - } - } - - // consider creating new element once, and just decoding into it. - var rtelem0Zero reflect.Value - var rtelem0ZeroValid bool - var decodeAsNil bool - var j int - - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() { - if hasLen { - rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size) - } else if f.seq == seqTypeSlice { - rvlen = decDefSliceCap - } else { - rvlen = decDefChanCap - } - if rvCanset { - if f.seq == seqTypeSlice { - rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) - rvChanged = true - } else { // chan - rv = reflect.MakeChan(ti.rt, rvlen) - rvChanged = true - } - } else { - d.errorf("cannot decode into non-settable slice") - } - } - slh.ElemContainerState(j) - decodeAsNil = dd.TryDecodeAsNil() - if f.seq == seqTypeChan { - if decodeAsNil { - rv.Send(reflect.Zero(rtelem0)) - continue - } - if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) { - rv9 = reflect.New(rtelem0).Elem() - } - if fn == nil { - fn = d.h.fn(rtelem, true, true) - } - d.decodeValue(rv9, fn, true) - rv.Send(rv9) - } else { - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= rvlen { - if f.seq == seqTypeArray { - d.arrayCannotExpand(rvlen, j+1) - decodeIntoBlank = true - } else { // if f.seq == seqTypeSlice - // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs - var rvcap2 int - var rvErrmsg2 string - rv9, rvcap2, rvChanged, rvErrmsg2 = - expandSliceRV(rv, ti.rt, rvCanset, rtelem0Size, 1, rvlen, rvcap) - if rvErrmsg2 != "" { - d.errorf(rvErrmsg2) - } - rvlen++ - if rvChanged { - rv = rv9 - rvcap = rvcap2 - } - } - } - if decodeIntoBlank { - if !decodeAsNil { - d.swallow() - } - } else { - rv9 = rv.Index(j) - if d.h.SliceElementReset || decodeAsNil { - if !rtelem0ZeroValid { - rtelem0ZeroValid = true - rtelem0Zero = reflect.Zero(rtelem0) - } - rv9.Set(rtelem0Zero) - if decodeAsNil { - continue - } - } - - if fn == nil { - fn = d.h.fn(rtelem, true, true) - } - d.decodeValue(rv9, fn, true) - } - } - } - if f.seq == seqTypeSlice { - if j < rvlen { - if rv.CanSet() { - rv.SetLen(j) - } else if rvCanset { - rv = rv.Slice(0, j) - rvChanged = true - } // else { d.errorf("kSlice: cannot change non-settable slice") } - rvlen = j - } else if j == 0 && rv.IsNil() { - if rvCanset { - rv = reflect.MakeSlice(ti.rt, 0, 0) - rvChanged = true - } // else { d.errorf("kSlice: cannot change non-settable slice") } - } - } - slh.End() - - if rvChanged { // infers rvCanset=true, so it can be reset - rv0.Set(rv) - } - - d.depthDecr() -} - -// func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) { -// // d.decodeValueFn(rv.Slice(0, rv.Len())) -// f.kSlice(rv.Slice(0, rv.Len())) -// } - -func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) { - dd := d.d - containerLen := dd.ReadMapStart() - elemsep := d.esep - ti := f.ti - if rv.IsNil() { - rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.key.Size()+ti.elem.Size())) - rv.Set(makeMapReflect(ti.rt, rvlen)) - } - - if containerLen == 0 { - dd.ReadMapEnd() - return - } - - d.depthIncr() - - ktype, vtype := ti.key, ti.elem - ktypeId := rt2id(ktype) - vtypeKind := vtype.Kind() - - var keyFn, valFn *codecFn - var ktypeLo, vtypeLo reflect.Type - - for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() { - } - - for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() { - } - - var mapGet, mapSet bool - rvvImmut := isImmutableKind(vtypeKind) - if !d.h.MapValueReset { - // if pointer, mapGet = true - // if interface, mapGet = true if !DecodeNakedAlways (else false) - // if builtin, mapGet = false - // else mapGet = true - if vtypeKind == reflect.Ptr { - mapGet = true - } else if vtypeKind == reflect.Interface { - if !d.h.InterfaceReset { - mapGet = true - } - } else if !rvvImmut { - mapGet = true + return } } - var rvk, rvkp, rvv, rvz reflect.Value - rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk. - ktypeIsString := ktypeId == stringTypId - ktypeIsIntf := ktypeId == intfTypId - hasLen := containerLen > 0 - var kstrbs []byte - - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if rvkMut || !rvkp.IsValid() { - rvkp = reflect.New(ktype) - rvk = rvkp.Elem() - } - if elemsep { - dd.ReadMapElemKey() - } - // if false && dd.TryDecodeAsNil() { // nil cannot be a map key, so disregard this block - // // Previously, if a nil key, we just ignored the mapped value and continued. - // // However, that makes the result of encoding and then decoding map[intf]intf{nil:nil} - // // to be an empty map. - // // Instead, we treat a nil key as the zero value of the type. - // rvk.Set(reflect.Zero(ktype)) - // } else if ktypeIsString { - if ktypeIsString { - kstrbs = dd.DecodeStringAsBytes() - rvk.SetString(stringView(kstrbs)) - // NOTE: if doing an insert, you MUST use a real string (not stringview) - } else { - if keyFn == nil { - keyFn = d.h.fn(ktypeLo, true, true) - } - d.decodeValue(rvk, keyFn, true) - } - // special case if a byte array. - if ktypeIsIntf { - if rvk2 := rvk.Elem(); rvk2.IsValid() { - if rvk2.Type() == uint8SliceTyp { - rvk = reflect.ValueOf(d.string(rvk2.Bytes())) - } else { - rvk = rvk2 - } - } - } - - if elemsep { - dd.ReadMapElemValue() - } - - // Brittle, but OK per TryDecodeAsNil() contract. - // i.e. TryDecodeAsNil never shares slices with other decDriver procedures - if dd.TryDecodeAsNil() { - if ktypeIsString { - rvk.SetString(d.string(kstrbs)) - } - if d.h.DeleteOnNilMapValue { - rv.SetMapIndex(rvk, reflect.Value{}) - } else { - rv.SetMapIndex(rvk, reflect.Zero(vtype)) - } - continue - } - - mapSet = true // set to false if u do a get, and its a non-nil pointer - if mapGet { - // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable. - rvv = rv.MapIndex(rvk) - if !rvv.IsValid() { - rvv = reflect.New(vtype).Elem() - } else if vtypeKind == reflect.Ptr { - if rvv.IsNil() { - rvv = reflect.New(vtype).Elem() - } else { - mapSet = false - } - } else if vtypeKind == reflect.Interface { - // not addressable, and thus not settable. - // e MUST create a settable/addressable variant - rvv2 := reflect.New(rvv.Type()).Elem() - if !rvv.IsNil() { - rvv2.Set(rvv) - } - rvv = rvv2 - } - // else it is ~mutable, and we can just decode into it directly - } else if rvvImmut { - if !rvz.IsValid() { - rvz = reflect.New(vtype).Elem() - } - rvv = rvz - } else { - rvv = reflect.New(vtype).Elem() - } - - // We MUST be done with the stringview of the key, before decoding the value - // so that we don't bastardize the reused byte array. - if mapSet && ktypeIsString { - rvk.SetString(d.string(kstrbs)) - } - if valFn == nil { - valFn = d.h.fn(vtypeLo, true, true) - } - d.decodeValue(rvv, valFn, true) - // d.decodeValueFn(rvv, valFn) - if mapSet { - rv.SetMapIndex(rvk, rvv) + if shortCircuitReflectToFastPath && rv.CanAddr() { + switch f.ti.rtid { + case intfSliceTypId: + f.d.decSliceIntf(rv.Addr().Interface().(*[]interface{}), currEncodedType, f.array) + return + case uint64SliceTypId: + f.d.decSliceUint64(rv.Addr().Interface().(*[]uint64), currEncodedType, f.array) + return + case int64SliceTypId: + f.d.decSliceInt64(rv.Addr().Interface().(*[]int64), currEncodedType, f.array) + return + case strSliceTypId: + f.d.decSliceStr(rv.Addr().Interface().(*[]string), currEncodedType, f.array) + return } - // if ktypeIsString { - // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop - // } } - dd.ReadMapEnd() + containerLen, containerLenS := decContLens(f.dd, currEncodedType) - d.depthDecr() -} - -// decNaked is used to keep track of the primitives decoded. -// Without it, we would have to decode each primitive and wrap it -// in an interface{}, causing an allocation. -// In this model, the primitives are decoded in a "pseudo-atomic" fashion, -// so we can rest assured that no other decoding happens while these -// primitives are being decoded. -// -// maps and arrays are not handled by this mechanism. -// However, RawExt is, and we accommodate for extensions that decode -// RawExt from DecodeNaked, but need to decode the value subsequently. -// kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat. -// -// However, decNaked also keeps some arrays of default maps and slices -// used in DecodeNaked. This way, we can get a pointer to it -// without causing a new heap allocation. -// -// kInterfaceNaked will ensure that there is no allocation for the common -// uses. - -type decNaked struct { - // r RawExt // used for RawExt, uint, []byte. - - // primitives below - u uint64 - i int64 - f float64 - l []byte - s string - - // ---- cpu cache line boundary? - t time.Time - b bool - - // state - v valueType - _ [6]bool // padding - - // ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above - // - // _ [3]uint64 // padding -} - -// func (n *decNaked) init() { -// n.ru = reflect.ValueOf(&n.u).Elem() -// n.ri = reflect.ValueOf(&n.i).Elem() -// n.rf = reflect.ValueOf(&n.f).Elem() -// n.rl = reflect.ValueOf(&n.l).Elem() -// n.rs = reflect.ValueOf(&n.s).Elem() -// n.rt = reflect.ValueOf(&n.t).Elem() -// n.rb = reflect.ValueOf(&n.b).Elem() -// // n.rr[] = reflect.ValueOf(&n.) -// } - -// type decNakedPooler struct { -// n *decNaked -// nsp *sync.Pool -// } - -// // naked must be called before each call to .DecodeNaked, as they will use it. -// func (d *decNakedPooler) naked() *decNaked { -// if d.n == nil { -// // consider one of: -// // - get from sync.Pool (if GC is frequent, there's no value here) -// // - new alloc (safest. only init'ed if it a naked decode will be done) -// // - field in Decoder (makes the Decoder struct very big) -// // To support using a decoder where a DecodeNaked is not needed, -// // we prefer #1 or #2. -// // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool -// // d.n.init() -// var v interface{} -// d.nsp, v = pool.decNaked() -// d.n = v.(*decNaked) -// } -// return d.n -// } - -// func (d *decNakedPooler) end() { -// if d.n != nil { -// // if n != nil, then nsp != nil (they are always set together) -// d.nsp.Put(d.n) -// d.n, d.nsp = nil, nil -// } -// } - -// type rtid2rv struct { -// rtid uintptr -// rv reflect.Value -// } - -// -------------- - -type decReaderSwitch struct { - rb bytesDecReader - // ---- cpu cache line boundary? - ri *ioDecReader - bi *bufioDecReader - - mtr, str bool // whether maptype or slicetype are known types - - be bool // is binary encoding - js bool // is json handle - jsms bool // is json handle, and MapKeyAsString - esep bool // has elem separators - - // typ entryType - bytes bool // is bytes reader - bufio bool // is this a bufioDecReader? -} - -// numread, track and stopTrack are always inlined, as they just check int fields, etc. - -/* -func (z *decReaderSwitch) numread() int { - switch z.typ { - case entryTypeBytes: - return z.rb.numread() - case entryTypeIo: - return z.ri.numread() - default: - return z.bi.numread() - } -} -func (z *decReaderSwitch) track() { - switch z.typ { - case entryTypeBytes: - z.rb.track() - case entryTypeIo: - z.ri.track() - default: - z.bi.track() - } -} -func (z *decReaderSwitch) stopTrack() []byte { - switch z.typ { - case entryTypeBytes: - return z.rb.stopTrack() - case entryTypeIo: - return z.ri.stopTrack() - default: - return z.bi.stopTrack() - } -} - -func (z *decReaderSwitch) unreadn1() { - switch z.typ { - case entryTypeBytes: - z.rb.unreadn1() - case entryTypeIo: - z.ri.unreadn1() - default: - z.bi.unreadn1() - } -} -func (z *decReaderSwitch) readx(n int) []byte { - switch z.typ { - case entryTypeBytes: - return z.rb.readx(n) - case entryTypeIo: - return z.ri.readx(n) - default: - return z.bi.readx(n) - } -} -func (z *decReaderSwitch) readb(s []byte) { - switch z.typ { - case entryTypeBytes: - z.rb.readb(s) - case entryTypeIo: - z.ri.readb(s) - default: - z.bi.readb(s) - } -} -func (z *decReaderSwitch) readn1() uint8 { - switch z.typ { - case entryTypeBytes: - return z.rb.readn1() - case entryTypeIo: - return z.ri.readn1() - default: - return z.bi.readn1() - } -} -func (z *decReaderSwitch) skip(accept *bitset256) (token byte) { - switch z.typ { - case entryTypeBytes: - return z.rb.skip(accept) - case entryTypeIo: - return z.ri.skip(accept) - default: - return z.bi.skip(accept) - } -} -func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) { - switch z.typ { - case entryTypeBytes: - return z.rb.readTo(in, accept) - case entryTypeIo: - return z.ri.readTo(in, accept) - default: - return z.bi.readTo(in, accept) - } -} -func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) { - switch z.typ { - case entryTypeBytes: - return z.rb.readUntil(in, stop) - case entryTypeIo: - return z.ri.readUntil(in, stop) - default: - return z.bi.readUntil(in, stop) - } -} - -*/ - -// the if/else-if/else block is expensive to inline. -// Each node of this construct costs a lot and dominates the budget. -// Best to only do an if fast-path else block (so fast-path is inlined). -// This is irrespective of inlineExtraCallCost set in $GOROOT/src/cmd/compile/internal/gc/inl.go -// -// In decReaderSwitch methods below, we delegate all IO functions into their own methods. -// This allows for the inlining of the common path when z.bytes=true. -// Go 1.12+ supports inlining methods with up to 1 inlined function (or 2 if no other constructs). - -func (z *decReaderSwitch) numread() uint { - if z.bytes { - return z.rb.numread() - } else if z.bufio { - return z.bi.numread() - } else { - return z.ri.numread() - } -} -func (z *decReaderSwitch) track() { - if z.bytes { - z.rb.track() - } else if z.bufio { - z.bi.track() - } else { - z.ri.track() - } -} -func (z *decReaderSwitch) stopTrack() []byte { - if z.bytes { - return z.rb.stopTrack() - } else if z.bufio { - return z.bi.stopTrack() - } else { - return z.ri.stopTrack() - } -} - -// func (z *decReaderSwitch) unreadn1() { -// if z.bytes { -// z.rb.unreadn1() -// } else { -// z.unreadn1IO() -// } -// } -// func (z *decReaderSwitch) unreadn1IO() { -// if z.bufio { -// z.bi.unreadn1() -// } else { -// z.ri.unreadn1() -// } -// } - -func (z *decReaderSwitch) unreadn1() { - if z.bytes { - z.rb.unreadn1() - } else if z.bufio { - z.bi.unreadn1() - } else { - z.ri.unreadn1() // not inlined - } -} - -func (z *decReaderSwitch) readx(n uint) []byte { - if z.bytes { - return z.rb.readx(n) - } - return z.readxIO(n) -} -func (z *decReaderSwitch) readxIO(n uint) []byte { - if z.bufio { - return z.bi.readx(n) - } - return z.ri.readx(n) -} - -func (z *decReaderSwitch) readb(s []byte) { - if z.bytes { - z.rb.readb(s) - } else { - z.readbIO(s) - } -} - -//go:noinline - fallback for io, ensures z.bytes path is inlined -func (z *decReaderSwitch) readbIO(s []byte) { - if z.bufio { - z.bi.readb(s) - } else { - z.ri.readb(s) - } -} - -func (z *decReaderSwitch) readn1() uint8 { - if z.bytes { - return z.rb.readn1() - } - return z.readn1IO() -} -func (z *decReaderSwitch) readn1IO() uint8 { - if z.bufio { - return z.bi.readn1() - } - return z.ri.readn1() -} + // an array can never return a nil slice. so no need to check f.array here. -func (z *decReaderSwitch) skip(accept *bitset256) (token byte) { - if z.bytes { - return z.rb.skip(accept) - } - return z.skipIO(accept) -} -func (z *decReaderSwitch) skipIO(accept *bitset256) (token byte) { - if z.bufio { - return z.bi.skip(accept) + if rv.IsNil() { + rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)) } - return z.ri.skip(accept) -} -func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) { - if z.bytes { - return z.rb.readToNoInput(accept) // z.rb.readTo(in, accept) + if containerLen == 0 { + return } - return z.readToIO(in, accept) -} -//go:noinline - fallback for io, ensures z.bytes path is inlined -func (z *decReaderSwitch) readToIO(in []byte, accept *bitset256) (out []byte) { - if z.bufio { - return z.bi.readTo(in, accept) - } - return z.ri.readTo(in, accept) -} -func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) { - if z.bytes { - return z.rb.readUntilNoInput(stop) + if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap { + if f.array { // !rv.CanSet() + decErr(msgDecCannotExpandArr, rvcap, containerLenS) + } + rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS) + if rvlen > 0 { + reflect.Copy(rvn, rv) + } + rv.Set(rvn) + } else if containerLenS > rvlen { + rv.SetLen(containerLenS) } - return z.readUntilIO(in, stop) -} -func (z *decReaderSwitch) readUntilIO(in []byte, stop byte) (out []byte) { - if z.bufio { - return z.bi.readUntil(in, stop) + for j := 0; j < containerLenS; j++ { + f.d.decodeValue(rv.Index(j)) } - return z.ri.readUntil(in, stop) } -// Decoder reads and decodes an object from an input stream in a supported format. -// -// Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used -// concurrently in multiple goroutines. -// -// However, as Decoder could be allocation heavy to initialize, a Reset method is provided -// so its state can be reused to decode new input streams repeatedly. -// This is the idiomatic way to use. -type Decoder struct { - panicHdl - // hopefully, reduce derefencing cost by laying the decReader inside the Decoder. - // Try to put things that go together to fit within a cache line (8 words). - - d decDriver - - // NOTE: Decoder shouldn't call it's read methods, - // as the handler MAY need to do some coordination. - r *decReaderSwitch +func (f *decFnInfo) kArray(rv reflect.Value) { + // f.d.decodeValue(rv.Slice(0, rv.Len())) + f.kSlice(rv.Slice(0, rv.Len())) +} - // bi *bufioDecReader - // cache the mapTypeId and sliceTypeId for faster comparisons - mtid uintptr - stid uintptr +func (f *decFnInfo) kMap(rv reflect.Value) { + if shortCircuitReflectToFastPath && rv.CanAddr() { + switch f.ti.rtid { + case mapStrIntfTypId: + f.d.decMapStrIntf(rv.Addr().Interface().(*map[string]interface{})) + return + case mapIntfIntfTypId: + f.d.decMapIntfIntf(rv.Addr().Interface().(*map[interface{}]interface{})) + return + case mapInt64IntfTypId: + f.d.decMapInt64Intf(rv.Addr().Interface().(*map[int64]interface{})) + return + case mapUint64IntfTypId: + f.d.decMapUint64Intf(rv.Addr().Interface().(*map[uint64]interface{})) + return + } + } - hh Handle - h *BasicHandle + containerLen := f.dd.readMapLen() - // ---- cpu cache line boundary? - decReaderSwitch + if rv.IsNil() { + rv.Set(reflect.MakeMap(f.ti.rt)) + } - // ---- cpu cache line boundary? - n decNaked + if containerLen == 0 { + return + } - // cr containerStateRecv - err error + ktype, vtype := f.ti.rt.Key(), f.ti.rt.Elem() + ktypeId := reflect.ValueOf(ktype).Pointer() + for j := 0; j < containerLen; j++ { + rvk := reflect.New(ktype).Elem() + f.d.decodeValue(rvk) - depth int16 - maxdepth int16 + // special case if a byte array. + // if ktype == intfTyp { + if ktypeId == intfTypId { + rvk = rvk.Elem() + if rvk.Type() == uint8SliceTyp { + rvk = reflect.ValueOf(string(rvk.Bytes())) + } + } + rvv := rv.MapIndex(rvk) + if !rvv.IsValid() || !rvv.CanSet() { + rvv = reflect.New(vtype).Elem() + } - _ [4]uint8 // padding + f.d.decodeValue(rvv) + rv.SetMapIndex(rvk, rvv) + } +} - is map[string]string // used for interning strings +// ---------------------------------------- - // ---- cpu cache line boundary? - b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxEncDrivers +type decFn struct { + i *decFnInfo + f func(*decFnInfo, reflect.Value) +} - // padding - false sharing help // modify 232 if Decoder struct changes. - // _ [cacheLineSize - 232%cacheLineSize]byte +// A Decoder reads and decodes an object from an input stream in the codec format. +type Decoder struct { + r decReader + d decDriver + h *BasicHandle + f map[uintptr]decFn + x []uintptr + s []decFn } // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader. // -// For efficiency, Users are encouraged to configure ReaderBufferSize on the handle -// OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer). +// For efficiency, Users are encouraged to pass in a memory buffered writer +// (eg bufio.Reader, bytes.Buffer). func NewDecoder(r io.Reader, h Handle) *Decoder { - d := newDecoder(h) - d.Reset(r) - return d + z := ioDecReader{ + r: r, + } + z.br, _ = r.(io.ByteReader) + return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()} } // NewDecoderBytes returns a Decoder which efficiently decodes directly // from a byte slice with zero copying. func NewDecoderBytes(in []byte, h Handle) *Decoder { - d := newDecoder(h) - d.ResetBytes(in) - return d -} - -// var defaultDecNaked decNaked - -func newDecoder(h Handle) *Decoder { - d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized} - d.bytes = true - if useFinalizers { - runtime.SetFinalizer(d, (*Decoder).finalize) - // xdebugf(">>>> new(Decoder) with finalizer") - } - d.r = &d.decReaderSwitch - d.hh = h - d.be = h.isBinary() - // NOTE: do not initialize d.n here. It is lazily initialized in d.naked() - var jh *JsonHandle - jh, d.js = h.(*JsonHandle) - if d.js { - d.jsms = jh.MapKeyAsString - } - d.esep = d.hh.hasElemSeparators() - if d.h.InternString { - d.is = make(map[string]string, 32) - } - d.d = h.newDecDriver(d) - // d.cr, _ = d.d.(containerStateRecv) - return d -} - -func (d *Decoder) resetCommon() { - // d.r = &d.decReaderSwitch - d.d.reset() - d.err = nil - d.depth = 0 - d.maxdepth = d.h.MaxDepth - if d.maxdepth <= 0 { - d.maxdepth = decDefMaxDepth - } - // reset all things which were cached from the Handle, but could change - d.mtid, d.stid = 0, 0 - d.mtr, d.str = false, false - if d.h.MapType != nil { - d.mtid = rt2id(d.h.MapType) - d.mtr = fastpathAV.index(d.mtid) != -1 - } - if d.h.SliceType != nil { - d.stid = rt2id(d.h.SliceType) - d.str = fastpathAV.index(d.stid) != -1 - } -} - -// Reset the Decoder with a new Reader to decode from, -// clearing all state from last run(s). -func (d *Decoder) Reset(r io.Reader) { - if r == nil { - return - } - d.bytes = false - // d.typ = entryTypeUnset - if d.h.ReaderBufferSize > 0 { - if d.bi == nil { - d.bi = new(bufioDecReader) - } - d.bi.reset(r, d.h.ReaderBufferSize) - // d.r = d.bi - // d.typ = entryTypeBufio - d.bufio = true - } else { - // d.ri.x = &d.b - // d.s = d.sa[:0] - if d.ri == nil { - d.ri = new(ioDecReader) - } - d.ri.reset(r) - // d.r = d.ri - // d.typ = entryTypeIo - d.bufio = false - } - d.resetCommon() -} - -// ResetBytes resets the Decoder with a new []byte to decode from, -// clearing all state from last run(s). -func (d *Decoder) ResetBytes(in []byte) { - if in == nil { - return + z := bytesDecReader{ + b: in, + a: len(in), } - d.bytes = true - d.bufio = false - // d.typ = entryTypeBytes - d.rb.reset(in) - // d.r = &d.rb - d.resetCommon() -} - -func (d *Decoder) naked() *decNaked { - return &d.n + return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()} } // Decode decodes the stream from reader and stores the result in the @@ -2470,8 +609,7 @@ func (d *Decoder) naked() *decNaked { // - Else decode it based on its reflect.Kind // // There are some special rules when decoding into containers (slice/array/map/struct). -// Decode will typically use the stream contents to UPDATE the container i.e. the values -// in these containers will not be zero'ed before decoding. +// Decode will typically use the stream contents to UPDATE the container. // - A map can be decoded from a stream map, by updating matching keys. // - A slice can be decoded from a stream array, // by updating the first n elements, where n is length of the stream. @@ -2481,629 +619,430 @@ func (d *Decoder) naked() *decNaked { // - A struct can be decoded from a stream array, // by updating fields as they occur in the struct (by index). // -// This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update -// in place by default). However, the consequence of this is that values in slices or maps -// which are not zero'ed before hand, will have part of the prior values in place after decode -// if the stream doesn't contain an update for those parts. -// -// This in-place update can be disabled by configuring the MapValueReset and SliceElementReset -// decode options available on every handle. -// -// Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice, +// When decoding a stream map or array with length of 0 into a nil map or slice, // we reset the destination map or slice to a zero-length value. // // However, when decoding a stream nil, we reset the destination container // to its "zero" value (e.g. nil for slice/map, etc). // -// Note: we allow nil values in the stream anywhere except for map keys. -// A nil value in the encoded stream where a map key is expected is treated as an error. func (d *Decoder) Decode(v interface{}) (err error) { - // tried to use closure, as runtime optimizes defer with no params. - // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc). - // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139 - // defer func() { d.deferred(&err) }() - // { x, y := d, &err; defer func() { x.deferred(y) }() } - if d.err != nil { - return d.err - } - if recoverPanicToErr { - defer func() { - if x := recover(); x != nil { - panicValToErr(d, x, &d.err) - err = d.err - } - }() - } - - // defer d.deferred(&err) - d.mustDecode(v) - return -} - -// MustDecode is like Decode, but panics if unable to Decode. -// This provides insight to the code location that triggered the error. -func (d *Decoder) MustDecode(v interface{}) { - if d.err != nil { - panic(d.err) - } - d.mustDecode(v) -} - -// MustDecode is like Decode, but panics if unable to Decode. -// This provides insight to the code location that triggered the error. -func (d *Decoder) mustDecode(v interface{}) { - // TODO: Top-level: ensure that v is a pointer and not nil. - if d.d.TryDecodeAsNil() { - setZero(v) - return - } - if d.bi == nil { - d.decode(v) - return - } - - d.bi.calls++ + defer panicToErr(&err) d.decode(v) - // xprintf.(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn) - d.bi.calls-- - if !d.h.ExplicitRelease && d.bi.calls == 0 { - d.bi.release() - } -} - -// func (d *Decoder) deferred(err1 *error) { -// if recoverPanicToErr { -// if x := recover(); x != nil { -// panicValToErr(d, x, err1) -// panicValToErr(d, x, &d.err) -// } -// } -// } - -//go:noinline -- as it is run by finalizer -func (d *Decoder) finalize() { - // xdebugf("finalizing Decoder") - d.Release() + return } -// Release releases shared (pooled) resources. -// -// It is important to call Release() when done with a Decoder, so those resources -// are released instantly for use by subsequently created Decoders. -// -// By default, Release() is automatically called unless the option ExplicitRelease is set. -func (d *Decoder) Release() { - if d.bi != nil { - d.bi.release() - } - // d.decNakedPooler.end() -} +func (d *Decoder) decode(iv interface{}) { + d.d.initReadNext() -// // this is not a smart swallow, as it allocates objects and does unnecessary work. -// func (d *Decoder) swallowViaHammer() { -// var blank interface{} -// d.decodeValueNoFn(reflect.ValueOf(&blank).Elem()) -// } + switch v := iv.(type) { + case nil: + decErr("Cannot decode into nil.") -func (d *Decoder) swallow() { - // smarter decode that just swallows the content - dd := d.d - if dd.TryDecodeAsNil() { - return - } - elemsep := d.esep - switch dd.ContainerType() { - case valueTypeMap: - containerLen := dd.ReadMapStart() - d.depthIncr() - hasLen := containerLen >= 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break} - if elemsep { - dd.ReadMapElemKey() - } - d.swallow() - if elemsep { - dd.ReadMapElemValue() - } - d.swallow() - } - dd.ReadMapEnd() - d.depthDecr() - case valueTypeArray: - containerLen := dd.ReadArrayStart() - d.depthIncr() - hasLen := containerLen >= 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if elemsep { - dd.ReadArrayElem() - } - d.swallow() - } - dd.ReadArrayEnd() - d.depthDecr() - case valueTypeBytes: - dd.DecodeBytes(d.b[:], true) - case valueTypeString: - dd.DecodeStringAsBytes() - default: - // these are all primitives, which we can get from decodeNaked - // if RawExt using Value, complete the processing. - n := d.naked() - dd.DecodeNaked() - if n.v == valueTypeExt && n.l == nil { - var v2 interface{} - d.decode(&v2) - } - } -} + case reflect.Value: + d.chkPtrValue(v) + d.decodeValue(v.Elem()) -func setZero(iv interface{}) { - if iv == nil || definitelyNil(iv) { - return - } - var canDecode bool - switch v := iv.(type) { case *string: - *v = "" + *v = d.d.decodeString() case *bool: - *v = false + *v = d.d.decodeBool() case *int: - *v = 0 + *v = int(d.d.decodeInt(intBitsize)) case *int8: - *v = 0 + *v = int8(d.d.decodeInt(8)) case *int16: - *v = 0 + *v = int16(d.d.decodeInt(16)) case *int32: - *v = 0 + *v = int32(d.d.decodeInt(32)) case *int64: - *v = 0 + *v = d.d.decodeInt(64) case *uint: - *v = 0 + *v = uint(d.d.decodeUint(uintBitsize)) case *uint8: - *v = 0 + *v = uint8(d.d.decodeUint(8)) case *uint16: - *v = 0 + *v = uint16(d.d.decodeUint(16)) case *uint32: - *v = 0 + *v = uint32(d.d.decodeUint(32)) case *uint64: - *v = 0 + *v = d.d.decodeUint(64) case *float32: - *v = 0 + *v = float32(d.d.decodeFloat(true)) case *float64: - *v = 0 - case *[]uint8: - *v = nil - case *Raw: - *v = nil - case *time.Time: - *v = time.Time{} - case reflect.Value: - if v, canDecode = isDecodeable(v); canDecode && v.CanSet() { - v.Set(reflect.Zero(v.Type())) - } // TODO: else drain if chan, clear if map, set all to nil if slice??? + *v = d.d.decodeFloat(false) + case *[]byte: + *v, _ = d.d.decodeBytes(*v) + + case *[]interface{}: + d.decSliceIntf(v, valueTypeInvalid, false) + case *[]uint64: + d.decSliceUint64(v, valueTypeInvalid, false) + case *[]int64: + d.decSliceInt64(v, valueTypeInvalid, false) + case *[]string: + d.decSliceStr(v, valueTypeInvalid, false) + case *map[string]interface{}: + d.decMapStrIntf(v) + case *map[interface{}]interface{}: + d.decMapIntfIntf(v) + case *map[uint64]interface{}: + d.decMapUint64Intf(v) + case *map[int64]interface{}: + d.decMapInt64Intf(v) + + case *interface{}: + d.decodeValue(reflect.ValueOf(iv).Elem()) + default: - if !fastpathDecodeSetZeroTypeSwitch(iv) { - v := reflect.ValueOf(iv) - if v, canDecode = isDecodeable(v); canDecode && v.CanSet() { - v.Set(reflect.Zero(v.Type())) - } // TODO: else drain if chan, clear if map, set all to nil if slice??? - } + rv := reflect.ValueOf(iv) + d.chkPtrValue(rv) + d.decodeValue(rv.Elem()) } } -func (d *Decoder) decode(iv interface{}) { - // a switch with only concrete types can be optimized. - // consequently, we deal with nil and interfaces outside the switch. +func (d *Decoder) decodeValue(rv reflect.Value) { + d.d.initReadNext() - if iv == nil { - d.errorstr(errstrCannotDecodeIntoNil) + if d.d.tryDecodeAsNil() { + // If value in stream is nil, set the dereferenced value to its "zero" value (if settable) + if rv.Kind() == reflect.Ptr { + if !rv.IsNil() { + rv.Set(reflect.Zero(rv.Type())) + } + return + } + // for rv.Kind() == reflect.Ptr { + // rv = rv.Elem() + // } + if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid + rv.Set(reflect.Zero(rv.Type())) + } return } - switch v := iv.(type) { - // case nil: - // case Selfer: - case reflect.Value: - v = d.ensureDecodeable(v) - d.decodeValue(v, nil, true) - - case *string: - *v = d.d.DecodeString() - case *bool: - *v = d.d.DecodeBool() - case *int: - *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) - case *int8: - *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8)) - case *int16: - *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16)) - case *int32: - *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32)) - case *int64: - *v = d.d.DecodeInt64() - case *uint: - *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) - case *uint8: - *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)) - case *uint16: - *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)) - case *uint32: - *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)) - case *uint64: - *v = d.d.DecodeUint64() - case *float32: - f64 := d.d.DecodeFloat64() - if chkOvf.Float32(f64) { - d.errorf("float32 overflow: %v", f64) - } - *v = float32(f64) - case *float64: - *v = d.d.DecodeFloat64() - case *[]uint8: - *v = d.d.DecodeBytes(*v, false) - case []uint8: - b := d.d.DecodeBytes(v, false) - if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) { - copy(v, b) + // If stream is not containing a nil value, then we can deref to the base + // non-pointer value, and decode into that. + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) } - case *time.Time: - *v = d.d.DecodeTime() - case *Raw: - *v = d.rawBytes() + rv = rv.Elem() + } - case *interface{}: - d.decodeValue(reflect.ValueOf(iv).Elem(), nil, true) - // d.decodeValueNotNil(reflect.ValueOf(iv).Elem()) + rt := rv.Type() + rtid := reflect.ValueOf(rt).Pointer() - default: - if v, ok := iv.(Selfer); ok { - v.CodecDecodeSelf(d) - } else if !fastpathDecodeTypeSwitch(iv, d) { - v := reflect.ValueOf(iv) - v = d.ensureDecodeable(v) - d.decodeValue(v, nil, false) - // d.decodeValueFallback(v) - } - } -} + // retrieve or register a focus'ed function for this type + // to eliminate need to do the retrieval multiple times -func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, chkAll bool) { - // If stream is not containing a nil value, then we can deref to the base - // non-pointer value, and decode into that. - var rvp reflect.Value - var rvpValid bool - if rv.Kind() == reflect.Ptr { - rvpValid = true - for { - if rv.IsNil() { - rv.Set(reflect.New(rv.Type().Elem())) - } - rvp = rv - rv = rv.Elem() - if rv.Kind() != reflect.Ptr { + // if d.f == nil && d.s == nil { debugf("---->Creating new dec f map for type: %v\n", rt) } + var fn decFn + var ok bool + if useMapForCodecCache { + fn, ok = d.f[rtid] + } else { + for i, v := range d.x { + if v == rtid { + fn, ok = d.s[i], true break } } } - - if fn == nil { - // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer - fn = d.h.fn(rv.Type(), chkAll, true) // chkAll, chkAll) - } - if fn.i.addrD { - if rvpValid { - fn.fd(d, &fn.i, rvp) - } else if rv.CanAddr() { - fn.fd(d, &fn.i, rv.Addr()) - } else if !fn.i.addrF { - fn.fd(d, &fn.i, rv) + if !ok { + // debugf("\tCreating new dec fn for type: %v\n", rt) + fi := decFnInfo{ti: getTypeInfo(rtid, rt), d: d, dd: d.d} + fn.i = &fi + // An extension can be registered for any type, regardless of the Kind + // (e.g. type BitSet int64, type MyStruct { / * unexported fields * / }, type X []int, etc. + // + // We can't check if it's an extension byte here first, because the user may have + // registered a pointer or non-pointer type, meaning we may have to recurse first + // before matching a mapped type, even though the extension byte is already detected. + // + // NOTE: if decoding into a nil interface{}, we return a non-nil + // value except even if the container registers a length of 0. + if rtid == rawExtTypId { + fn.f = (*decFnInfo).rawExt + } else if d.d.isBuiltinType(rtid) { + fn.f = (*decFnInfo).builtin + } else if xfTag, xfFn := d.h.getDecodeExt(rtid); xfFn != nil { + fi.xfTag, fi.xfFn = xfTag, xfFn + fn.f = (*decFnInfo).ext + } else if supportBinaryMarshal && fi.ti.unm { + fn.f = (*decFnInfo).binaryMarshal } else { - d.errorf("cannot decode into a non-pointer value") + switch rk := rt.Kind(); rk { + case reflect.String: + fn.f = (*decFnInfo).kString + case reflect.Bool: + fn.f = (*decFnInfo).kBool + case reflect.Int: + fn.f = (*decFnInfo).kInt + case reflect.Int64: + fn.f = (*decFnInfo).kInt64 + case reflect.Int32: + fn.f = (*decFnInfo).kInt32 + case reflect.Int8: + fn.f = (*decFnInfo).kInt8 + case reflect.Int16: + fn.f = (*decFnInfo).kInt16 + case reflect.Float32: + fn.f = (*decFnInfo).kFloat32 + case reflect.Float64: + fn.f = (*decFnInfo).kFloat64 + case reflect.Uint8: + fn.f = (*decFnInfo).kUint8 + case reflect.Uint64: + fn.f = (*decFnInfo).kUint64 + case reflect.Uint: + fn.f = (*decFnInfo).kUint + case reflect.Uint32: + fn.f = (*decFnInfo).kUint32 + case reflect.Uint16: + fn.f = (*decFnInfo).kUint16 + // case reflect.Ptr: + // fn.f = (*decFnInfo).kPtr + case reflect.Interface: + fn.f = (*decFnInfo).kInterface + case reflect.Struct: + fn.f = (*decFnInfo).kStruct + case reflect.Slice: + fn.f = (*decFnInfo).kSlice + case reflect.Array: + fi.array = true + fn.f = (*decFnInfo).kArray + case reflect.Map: + fn.f = (*decFnInfo).kMap + default: + fn.f = (*decFnInfo).kErr + } } - } else { - fn.fd(d, &fn.i, rv) - } - // return rv -} - -func (d *Decoder) structFieldNotFound(index int, rvkencname string) { - // NOTE: rvkencname may be a stringView, so don't pass it to another function. - if d.h.ErrorIfNoField { - if index >= 0 { - d.errorf("no matching struct field found when decoding stream array at index %v", index) - return - } else if rvkencname != "" { - d.errorf("no matching struct field found when decoding stream map with key " + rvkencname) - return + if useMapForCodecCache { + if d.f == nil { + d.f = make(map[uintptr]decFn, 16) + } + d.f[rtid] = fn + } else { + d.s = append(d.s, fn) + d.x = append(d.x, rtid) } } - d.swallow() -} -func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) { - if d.h.ErrorIfNoArrayExpand { - d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen) - } -} + fn.f(fn.i, rv) -func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) { - switch rv.Kind() { - case reflect.Array: - return rv, rv.CanAddr() - case reflect.Ptr: - if !rv.IsNil() { - return rv.Elem(), true - } - case reflect.Slice, reflect.Chan, reflect.Map: - if !rv.IsNil() { - return rv, true - } - } return } -func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) { - // decode can take any reflect.Value that is a inherently addressable i.e. - // - array - // - non-nil chan (we will SEND to it) - // - non-nil slice (we will set its elements) - // - non-nil map (we will put into it) - // - non-nil pointer (we can "update" it) - rv2, canDecode := isDecodeable(rv) - if canDecode { +func (d *Decoder) chkPtrValue(rv reflect.Value) { + // We can only decode into a non-nil pointer + if rv.Kind() == reflect.Ptr && !rv.IsNil() { return } if !rv.IsValid() { - d.errorstr(errstrCannotDecodeIntoNil) - return + decErr("Cannot decode into a zero (ie invalid) reflect.Value") } if !rv.CanInterface() { - d.errorf("cannot decode into a value without an interface: %v", rv) - return - } - rvi := rv2i(rv) - rvk := rv.Kind() - d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi) - return -} - -func (d *Decoder) depthIncr() { - d.depth++ - if d.depth >= d.maxdepth { - panic(errMaxDepthExceeded) + decErr("Cannot decode into a value without an interface: %v", rv) } + rvi := rv.Interface() + decErr("Cannot decode into non-pointer or nil pointer. Got: %v, %T, %v", + rv.Kind(), rvi, rvi) } -func (d *Decoder) depthDecr() { - d.depth-- -} - -// Possibly get an interned version of a string -// -// This should mostly be used for map keys, where the key type is string. -// This is because keys of a map/struct are typically reused across many objects. -func (d *Decoder) string(v []byte) (s string) { - if d.is == nil { - return string(v) // don't return stringView, as we need a real string here. - } - s, ok := d.is[string(v)] // no allocation here, per go implementation - if !ok { - s = string(v) // new allocation here - d.is[s] = s +func (d *Decoder) decEmbeddedField(rv reflect.Value, index []int) { + // d.decodeValue(rv.FieldByIndex(index)) + // nil pointers may be here; so reproduce FieldByIndex logic + enhancements + for _, j := range index { + if rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) + } + // If a pointer, it must be a pointer to struct (based on typeInfo contract) + rv = rv.Elem() + } + rv = rv.Field(j) } - return s -} - -// nextValueBytes returns the next value in the stream as a set of bytes. -func (d *Decoder) nextValueBytes() (bs []byte) { - d.d.uncacheRead() - d.r.track() - d.swallow() - bs = d.r.stopTrack() - return -} - -func (d *Decoder) rawBytes() []byte { - // ensure that this is not a view into the bytes - // i.e. make new copy always. - bs := d.nextValueBytes() - bs2 := make([]byte, len(bs)) - copy(bs2, bs) - return bs2 -} - -func (d *Decoder) wrapErr(v interface{}, err *error) { - *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: int(d.r.numread())} -} - -// NumBytesRead returns the number of bytes read -func (d *Decoder) NumBytesRead() int { - return int(d.r.numread()) + d.decodeValue(rv) } // -------------------------------------------------- -// decSliceHelper assists when decoding into a slice, from a map or an array in the stream. -// A slice can be set from a map or array in stream. This supports the MapBySlice interface. -type decSliceHelper struct { - d *Decoder - // ct valueType - array bool -} - -func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) { - dd := d.d - ctyp := dd.ContainerType() - switch ctyp { - case valueTypeArray: - x.array = true - clen = dd.ReadArrayStart() - case valueTypeMap: - clen = dd.ReadMapStart() * 2 - default: - d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp) +// short circuit functions for common maps and slices + +func (d *Decoder) decSliceIntf(v *[]interface{}, currEncodedType valueType, doNotReset bool) { + _, containerLenS := decContLens(d.d, currEncodedType) + s := *v + if s == nil { + s = make([]interface{}, containerLenS, containerLenS) + } else if containerLenS > cap(s) { + if doNotReset { + decErr(msgDecCannotExpandArr, cap(s), containerLenS) + } + s = make([]interface{}, containerLenS, containerLenS) + copy(s, *v) + } else if containerLenS > len(s) { + s = s[:containerLenS] + } + for j := 0; j < containerLenS; j++ { + d.decode(&s[j]) + } + *v = s +} + +func (d *Decoder) decSliceInt64(v *[]int64, currEncodedType valueType, doNotReset bool) { + _, containerLenS := decContLens(d.d, currEncodedType) + s := *v + if s == nil { + s = make([]int64, containerLenS, containerLenS) + } else if containerLenS > cap(s) { + if doNotReset { + decErr(msgDecCannotExpandArr, cap(s), containerLenS) + } + s = make([]int64, containerLenS, containerLenS) + copy(s, *v) + } else if containerLenS > len(s) { + s = s[:containerLenS] + } + for j := 0; j < containerLenS; j++ { + // d.decode(&s[j]) + d.d.initReadNext() + s[j] = d.d.decodeInt(intBitsize) + } + *v = s +} + +func (d *Decoder) decSliceUint64(v *[]uint64, currEncodedType valueType, doNotReset bool) { + _, containerLenS := decContLens(d.d, currEncodedType) + s := *v + if s == nil { + s = make([]uint64, containerLenS, containerLenS) + } else if containerLenS > cap(s) { + if doNotReset { + decErr(msgDecCannotExpandArr, cap(s), containerLenS) + } + s = make([]uint64, containerLenS, containerLenS) + copy(s, *v) + } else if containerLenS > len(s) { + s = s[:containerLenS] + } + for j := 0; j < containerLenS; j++ { + // d.decode(&s[j]) + d.d.initReadNext() + s[j] = d.d.decodeUint(intBitsize) + } + *v = s +} + +func (d *Decoder) decSliceStr(v *[]string, currEncodedType valueType, doNotReset bool) { + _, containerLenS := decContLens(d.d, currEncodedType) + s := *v + if s == nil { + s = make([]string, containerLenS, containerLenS) + } else if containerLenS > cap(s) { + if doNotReset { + decErr(msgDecCannotExpandArr, cap(s), containerLenS) + } + s = make([]string, containerLenS, containerLenS) + copy(s, *v) + } else if containerLenS > len(s) { + s = s[:containerLenS] + } + for j := 0; j < containerLenS; j++ { + // d.decode(&s[j]) + d.d.initReadNext() + s[j] = d.d.decodeString() + } + *v = s +} + +func (d *Decoder) decMapIntfIntf(v *map[interface{}]interface{}) { + containerLen := d.d.readMapLen() + m := *v + if m == nil { + m = make(map[interface{}]interface{}, containerLen) + *v = m + } + for j := 0; j < containerLen; j++ { + var mk interface{} + d.decode(&mk) + // special case if a byte array. + if bv, bok := mk.([]byte); bok { + mk = string(bv) + } + mv := m[mk] + d.decode(&mv) + m[mk] = mv } - // x.ct = ctyp - x.d = d - return } -func (x decSliceHelper) End() { - if x.array { - x.d.d.ReadArrayEnd() - } else { - x.d.d.ReadMapEnd() +func (d *Decoder) decMapInt64Intf(v *map[int64]interface{}) { + containerLen := d.d.readMapLen() + m := *v + if m == nil { + m = make(map[int64]interface{}, containerLen) + *v = m } -} - -func (x decSliceHelper) ElemContainerState(index int) { - if x.array { - x.d.d.ReadArrayElem() - } else if index%2 == 0 { - x.d.d.ReadMapElemKey() - } else { - x.d.d.ReadMapElemValue() + for j := 0; j < containerLen; j++ { + d.d.initReadNext() + mk := d.d.decodeInt(intBitsize) + mv := m[mk] + d.decode(&mv) + m[mk] = mv } } -func decByteSlice(r *decReaderSwitch, clen, maxInitLen int, bs []byte) (bsOut []byte) { - if clen == 0 { - return zeroByteSlice - } - if len(bs) == clen { - bsOut = bs - r.readb(bsOut) - } else if cap(bs) >= clen { - bsOut = bs[:clen] - r.readb(bsOut) - } else { - // bsOut = make([]byte, clen) - len2 := decInferLen(clen, maxInitLen, 1) - bsOut = make([]byte, len2) - r.readb(bsOut) - for len2 < clen { - len3 := decInferLen(clen-len2, maxInitLen, 1) - bs3 := bsOut - bsOut = make([]byte, len2+len3) - copy(bsOut, bs3) - r.readb(bsOut[len2:]) - len2 += len3 - } +func (d *Decoder) decMapUint64Intf(v *map[uint64]interface{}) { + containerLen := d.d.readMapLen() + m := *v + if m == nil { + m = make(map[uint64]interface{}, containerLen) + *v = m } - return -} - -// func decByteSliceZeroCopy(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) { -// if _, ok := r.(*bytesDecReader); ok && clen <= maxInitLen { -// return r.readx(clen) -// } -// return decByteSlice(r, clen, maxInitLen, bs) -// } - -func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) { - if xlen := len(in); xlen > 0 { - if isBytesReader || xlen <= scratchByteArrayLen { - if cap(dest) >= xlen { - out = dest[:xlen] - } else { - out = make([]byte, xlen) - } - copy(out, in) - return - } + for j := 0; j < containerLen; j++ { + d.d.initReadNext() + mk := d.d.decodeUint(intBitsize) + mv := m[mk] + d.decode(&mv) + m[mk] = mv } - return in } -// decInferLen will infer a sensible length, given the following: -// - clen: length wanted. -// - maxlen: max length to be returned. -// if <= 0, it is unset, and we infer it based on the unit size -// - unit: number of bytes for each element of the collection -func decInferLen(clen, maxlen, unit int) (rvlen int) { - // handle when maxlen is not set i.e. <= 0 - if clen <= 0 { - return - } - if unit == 0 { - return clen - } - if maxlen <= 0 { - // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items. - // maxlen = 256 * 1024 / unit - // if maxlen < (4 * 1024) { - // maxlen = 4 * 1024 - // } - if unit < (256 / 4) { - maxlen = 256 * 1024 / unit - } else { - maxlen = 4 * 1024 - } +func (d *Decoder) decMapStrIntf(v *map[string]interface{}) { + containerLen := d.d.readMapLen() + m := *v + if m == nil { + m = make(map[string]interface{}, containerLen) + *v = m } - if clen > maxlen { - rvlen = maxlen - } else { - rvlen = clen + for j := 0; j < containerLen; j++ { + d.d.initReadNext() + mk := d.d.decodeString() + mv := m[mk] + d.decode(&mv) + m[mk] = mv } - return } -func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) ( - s2 reflect.Value, scap2 int, changed bool, err string) { - l1 := slen + num // new slice length - if l1 < slen { - err = errmsgExpandSliceOverflow - return - } - if l1 <= scap { - if s.CanSet() { - s.SetLen(l1) - } else if canChange { - s2 = s.Slice(0, l1) - scap2 = scap - changed = true - } else { - err = errmsgExpandSliceCannotChange - return - } - return - } - if !canChange { - err = errmsgExpandSliceCannotChange - return - } - scap2 = growCap(scap, stElemSize, num) - s2 = reflect.MakeSlice(st, l1, scap2) - changed = true - reflect.Copy(s2, s) - return -} +// ---------------------------------------- -func decReadFull(r io.Reader, bs []byte) (n uint, err error) { - var nn int - for n < uint(len(bs)) && err == nil { - nn, err = r.Read(bs[n:]) - if nn > 0 { - if err == io.EOF { - // leave EOF for next time - err = nil - } - n += uint(nn) - } +func decContLens(dd decDriver, currEncodedType valueType) (containerLen, containerLenS int) { + if currEncodedType == valueTypeInvalid { + currEncodedType = dd.currentEncodedType() + } + switch currEncodedType { + case valueTypeArray: + containerLen = dd.readArrayLen() + containerLenS = containerLen + case valueTypeMap: + containerLen = dd.readMapLen() + containerLenS = containerLen * 2 + default: + decErr("Only encoded map or array can be decoded into a slice. (valueType: %0x)", + currEncodedType) } - // xdebugf("decReadFull: len(bs): %v, n: %v, err: %v", len(bs), n, err) - // do not do this - it serves no purpose - // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF } return } -func decNakedReadRawBytes(dr decDriver, d *Decoder, n *decNaked, rawToString bool) { - if rawToString { - n.v = valueTypeString - n.s = string(dr.DecodeBytes(d.b[:], true)) - } else { - n.v = valueTypeBytes - n.l = dr.DecodeBytes(nil, false) - } +func decErr(format string, params ...interface{}) { + doPanic(msgTagDec, format, params...) } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/doc.go b/vendor/github.com/hashicorp/go-msgpack/codec/doc.go deleted file mode 100644 index 5c5df9cfda1a0..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/doc.go +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -/* -Package codec provides a -High Performance, Feature-Rich Idiomatic Go 1.4+ codec/encoding library -for binc, msgpack, cbor, json. - -Supported Serialization formats are: - - - msgpack: https://github.com/msgpack/msgpack - - binc: http://github.com/ugorji/binc - - cbor: http://cbor.io http://tools.ietf.org/html/rfc7049 - - json: http://json.org http://tools.ietf.org/html/rfc7159 - - simple: - -This package will carefully use 'package unsafe' for performance reasons in specific places. -You can build without unsafe use by passing the safe or appengine tag -i.e. 'go install -tags=safe ...'. Note that unsafe is only supported for the last 4 -go releases e.g. current go release is go 1.12, so we support unsafe use only from -go 1.9+ . This is because supporting unsafe requires knowledge of implementation details. - -For detailed usage information, read the primer at http://ugorji.net/blog/go-codec-primer . - -The idiomatic Go support is as seen in other encoding packages in -the standard library (ie json, xml, gob, etc). - -Rich Feature Set includes: - - - Simple but extremely powerful and feature-rich API - - Support for go1.4 and above, while selectively using newer APIs for later releases - - Excellent code coverage ( > 90% ) - - Very High Performance. - Our extensive benchmarks show us outperforming Gob, Json, Bson, etc by 2-4X. - - Careful selected use of 'unsafe' for targeted performance gains. - 100% mode exists where 'unsafe' is not used at all. - - Lock-free (sans mutex) concurrency for scaling to 100's of cores - - In-place updates during decode, with option to zero value in maps and slices prior to decode - - Coerce types where appropriate - e.g. decode an int in the stream into a float, decode numbers from formatted strings, etc - - Corner Cases: - Overflows, nil maps/slices, nil values in streams are handled correctly - - Standard field renaming via tags - - Support for omitting empty fields during an encoding - - Encoding from any value and decoding into pointer to any value - (struct, slice, map, primitives, pointers, interface{}, etc) - - Extensions to support efficient encoding/decoding of any named types - - Support encoding.(Binary|Text)(M|Unm)arshaler interfaces - - Support IsZero() bool to determine if a value is a zero value. - Analogous to time.Time.IsZero() bool. - - Decoding without a schema (into a interface{}). - Includes Options to configure what specific map or slice type to use - when decoding an encoded list or map into a nil interface{} - - Mapping a non-interface type to an interface, so we can decode appropriately - into any interface type with a correctly configured non-interface value. - - Encode a struct as an array, and decode struct from an array in the data stream - - Option to encode struct keys as numbers (instead of strings) - (to support structured streams with fields encoded as numeric codes) - - Comprehensive support for anonymous fields - - Fast (no-reflection) encoding/decoding of common maps and slices - - Code-generation for faster performance. - - Support binary (e.g. messagepack, cbor) and text (e.g. json) formats - - Support indefinite-length formats to enable true streaming - (for formats which support it e.g. json, cbor) - - Support canonical encoding, where a value is ALWAYS encoded as same sequence of bytes. - This mostly applies to maps, where iteration order is non-deterministic. - - NIL in data stream decoded as zero value - - Never silently skip data when decoding. - User decides whether to return an error or silently skip data when keys or indexes - in the data stream do not map to fields in the struct. - - Detect and error when encoding a cyclic reference (instead of stack overflow shutdown) - - Encode/Decode from/to chan types (for iterative streaming support) - - Drop-in replacement for encoding/json. `json:` key in struct tag supported. - - Provides a RPC Server and Client Codec for net/rpc communication protocol. - - Handle unique idiosyncrasies of codecs e.g. - - For messagepack, configure how ambiguities in handling raw bytes are resolved - - For messagepack, provide rpc server/client codec to support - msgpack-rpc protocol defined at: - https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md - -Extension Support - -Users can register a function to handle the encoding or decoding of -their custom types. - -There are no restrictions on what the custom type can be. Some examples: - - type BisSet []int - type BitSet64 uint64 - type UUID string - type MyStructWithUnexportedFields struct { a int; b bool; c []int; } - type GifImage struct { ... } - -As an illustration, MyStructWithUnexportedFields would normally be -encoded as an empty map because it has no exported fields, while UUID -would be encoded as a string. However, with extension support, you can -encode any of these however you like. - -Custom Encoding and Decoding - -This package maintains symmetry in the encoding and decoding halfs. -We determine how to encode or decode by walking this decision tree - - - is type a codec.Selfer? - - is there an extension registered for the type? - - is format binary, and is type a encoding.BinaryMarshaler and BinaryUnmarshaler? - - is format specifically json, and is type a encoding/json.Marshaler and Unmarshaler? - - is format text-based, and type an encoding.TextMarshaler and TextUnmarshaler? - - else we use a pair of functions based on the "kind" of the type e.g. map, slice, int64, etc - -This symmetry is important to reduce chances of issues happening because the -encoding and decoding sides are out of sync e.g. decoded via very specific -encoding.TextUnmarshaler but encoded via kind-specific generalized mode. - -Consequently, if a type only defines one-half of the symmetry -(e.g. it implements UnmarshalJSON() but not MarshalJSON() ), -then that type doesn't satisfy the check and we will continue walking down the -decision tree. - -RPC - -RPC Client and Server Codecs are implemented, so the codecs can be used -with the standard net/rpc package. - -Usage - -The Handle is SAFE for concurrent READ, but NOT SAFE for concurrent modification. - -The Encoder and Decoder are NOT safe for concurrent use. - -Consequently, the usage model is basically: - - - Create and initialize the Handle before any use. - Once created, DO NOT modify it. - - Multiple Encoders or Decoders can now use the Handle concurrently. - They only read information off the Handle (never write). - - However, each Encoder or Decoder MUST not be used concurrently - - To re-use an Encoder/Decoder, call Reset(...) on it first. - This allows you use state maintained on the Encoder/Decoder. - -Sample usage model: - - // create and configure Handle - var ( - bh codec.BincHandle - mh codec.MsgpackHandle - ch codec.CborHandle - ) - - mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) - - // configure extensions - // e.g. for msgpack, define functions and enable Time support for tag 1 - // mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt) - - // create and use decoder/encoder - var ( - r io.Reader - w io.Writer - b []byte - h = &bh // or mh to use msgpack - ) - - dec = codec.NewDecoder(r, h) - dec = codec.NewDecoderBytes(b, h) - err = dec.Decode(&v) - - enc = codec.NewEncoder(w, h) - enc = codec.NewEncoderBytes(&b, h) - err = enc.Encode(v) - - //RPC Server - go func() { - for { - conn, err := listener.Accept() - rpcCodec := codec.GoRpc.ServerCodec(conn, h) - //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) - rpc.ServeCodec(rpcCodec) - } - }() - - //RPC Communication (client side) - conn, err = net.Dial("tcp", "localhost:5555") - rpcCodec := codec.GoRpc.ClientCodec(conn, h) - //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) - client := rpc.NewClientWithCodec(rpcCodec) - -Running Tests - -To run tests, use the following: - - go test - -To run the full suite of tests, use the following: - - go test -tags alltests -run Suite - -You can run the tag 'safe' to run tests or build in safe mode. e.g. - - go test -tags safe -run Json - go test -tags "alltests safe" -run Suite - -Running Benchmarks - - cd bench - go test -bench . -benchmem -benchtime 1s - -Please see http://github.com/ugorji/go-codec-bench . - -Managing Binary Size - -This package could add up to 10MB to the size of your binaries. - -This is because we include some a auto-generated file: `fast-path.generated.go` -to help with performance when encoding/decoding slices and maps of -built in numeric, boolean, string and interface{} types. - -You can override this by building (or running tests and benchmarks) -with the tag: `notfastpath`. - - go install -tags notfastpath - go build -tags notfastpath - go test -tags notfastpath - -Be aware that, at least in our representative microbenchmarks for cbor (for example), -we see up to 33% increase in decoding and 50% increase in encoding speeds. -YMMV. - -Caveats - -Struct fields matching the following are ignored during encoding and decoding - - struct tag value set to - - - func, complex numbers, unsafe pointers - - unexported and not embedded - - unexported and embedded and not struct kind - - unexported and embedded pointers (from go1.10) - -Every other field in a struct will be encoded/decoded. - -Embedded fields are encoded as if they exist in the top-level struct, -with some caveats. See Encode documentation. - -*/ -package codec - diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/encode.go b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go index 9d8d1164a4b2c..4914be0c748bf 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/encode.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go @@ -1,1267 +1,626 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec import ( - "encoding" - "errors" - "fmt" "io" "reflect" - "runtime" - "sort" - "strconv" - "time" ) -// defEncByteBufSize is the default size of []byte used -// for bufio buffer or []byte (when nil passed) -const defEncByteBufSize = 1 << 10 // 4:16, 6:64, 8:256, 10:1024 +const ( + // Some tagging information for error messages. + msgTagEnc = "codec.encoder" + defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024 + // maxTimeSecs32 = math.MaxInt32 / 60 / 24 / 366 +) -var errEncoderNotInitialized = errors.New("Encoder not initialized") +// AsSymbolFlag defines what should be encoded as symbols. +type AsSymbolFlag uint8 -/* +const ( + // AsSymbolDefault is default. + // Currently, this means only encode struct field names as symbols. + // The default is subject to change. + AsSymbolDefault AsSymbolFlag = iota -// encWriter abstracts writing to a byte array or to an io.Writer. -// -// -// Deprecated: Use encWriterSwitch instead. + // AsSymbolAll means encode anything which could be a symbol as a symbol. + AsSymbolAll = 0xfe + + // AsSymbolNone means do not encode anything as a symbol. + AsSymbolNone = 1 << iota + + // AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols. + AsSymbolMapStringKeysFlag + + // AsSymbolStructFieldName means encode struct field names as symbols. + AsSymbolStructFieldNameFlag +) + +// encWriter abstracting writing to a byte array or to an io.Writer. type encWriter interface { + writeUint16(uint16) + writeUint32(uint32) + writeUint64(uint64) writeb([]byte) writestr(string) writen1(byte) writen2(byte, byte) - end() + atEndOfEncode() } -*/ - // encDriver abstracts the actual codec (binc vs msgpack, etc) type encDriver interface { - EncodeNil() - EncodeInt(i int64) - EncodeUint(i uint64) - EncodeBool(b bool) - EncodeFloat32(f float32) - EncodeFloat64(f float64) - // encodeExtPreamble(xtag byte, length int) - EncodeRawExt(re *RawExt, e *Encoder) - EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder) - // Deprecated: use EncodeStringEnc instead - EncodeString(c charEncoding, v string) - // Deprecated: use EncodeStringBytesRaw instead - EncodeStringBytes(c charEncoding, v []byte) - EncodeStringEnc(c charEncoding, v string) // c cannot be cRAW - // EncodeSymbol(v string) - EncodeStringBytesRaw(v []byte) - EncodeTime(time.Time) + isBuiltinType(rt uintptr) bool + encodeBuiltin(rt uintptr, v interface{}) + encodeNil() + encodeInt(i int64) + encodeUint(i uint64) + encodeBool(b bool) + encodeFloat32(f float32) + encodeFloat64(f float64) + encodeExtPreamble(xtag byte, length int) + encodeArrayPreamble(length int) + encodeMapPreamble(length int) + encodeString(c charEncoding, v string) + encodeSymbol(v string) + encodeStringBytes(c charEncoding, v []byte) + //TODO //encBignum(f *big.Int) //encStringRunes(c charEncoding, v []rune) - WriteArrayStart(length int) - WriteArrayElem() - WriteArrayEnd() - WriteMapStart(length int) - WriteMapElemKey() - WriteMapElemValue() - WriteMapEnd() - - reset() - atEndOfEncode() -} - -type encDriverAsis interface { - EncodeAsis(v []byte) -} - -type encodeError struct { - codecError } -func (e encodeError) Error() string { - return fmt.Sprintf("%s encode error: %v", e.name, e.err) +type ioEncWriterWriter interface { + WriteByte(c byte) error + WriteString(s string) (n int, err error) + Write(p []byte) (n int, err error) } -type encDriverNoopContainerWriter struct{} - -func (encDriverNoopContainerWriter) WriteArrayStart(length int) {} -func (encDriverNoopContainerWriter) WriteArrayElem() {} -func (encDriverNoopContainerWriter) WriteArrayEnd() {} -func (encDriverNoopContainerWriter) WriteMapStart(length int) {} -func (encDriverNoopContainerWriter) WriteMapElemKey() {} -func (encDriverNoopContainerWriter) WriteMapElemValue() {} -func (encDriverNoopContainerWriter) WriteMapEnd() {} -func (encDriverNoopContainerWriter) atEndOfEncode() {} - -type encDriverTrackContainerWriter struct { - c containerState +type ioEncStringWriter interface { + WriteString(s string) (n int, err error) } -func (e *encDriverTrackContainerWriter) WriteArrayStart(length int) { e.c = containerArrayStart } -func (e *encDriverTrackContainerWriter) WriteArrayElem() { e.c = containerArrayElem } -func (e *encDriverTrackContainerWriter) WriteArrayEnd() { e.c = containerArrayEnd } -func (e *encDriverTrackContainerWriter) WriteMapStart(length int) { e.c = containerMapStart } -func (e *encDriverTrackContainerWriter) WriteMapElemKey() { e.c = containerMapKey } -func (e *encDriverTrackContainerWriter) WriteMapElemValue() { e.c = containerMapValue } -func (e *encDriverTrackContainerWriter) WriteMapEnd() { e.c = containerMapEnd } -func (e *encDriverTrackContainerWriter) atEndOfEncode() {} - -// type ioEncWriterWriter interface { -// WriteByte(c byte) error -// WriteString(s string) (n int, err error) -// Write(p []byte) (n int, err error) -// } - -// EncodeOptions captures configuration options during encode. type EncodeOptions struct { - // WriterBufferSize is the size of the buffer used when writing. - // - // if > 0, we use a smart buffer internally for performance purposes. - WriterBufferSize int - - // ChanRecvTimeout is the timeout used when selecting from a chan. - // - // Configuring this controls how we receive from a chan during the encoding process. - // - If ==0, we only consume the elements currently available in the chan. - // - if <0, we consume until the chan is closed. - // - If >0, we consume until this timeout. - ChanRecvTimeout time.Duration - - // StructToArray specifies to encode a struct as an array, and not as a map + // Encode a struct as an array, and not as a map. StructToArray bool - // Canonical representation means that encoding a value will always result in the same - // sequence of bytes. - // - // This only affects maps, as the iteration order for maps is random. - // - // The implementation MAY use the natural sort order for the map keys if possible: - // - // - If there is a natural sort order (ie for number, bool, string or []byte keys), - // then the map keys are first sorted in natural order and then written - // with corresponding map values to the strema. - // - If there is no natural sort order, then the map keys will first be - // encoded into []byte, and then sorted, - // before writing the sorted keys and the corresponding map values to the stream. - // - Canonical bool - - // CheckCircularRef controls whether we check for circular references - // and error fast during an encode. + // AsSymbols defines what should be encoded as symbols. // - // If enabled, an error is received if a pointer to a struct - // references itself either directly or through one of its fields (iteratively). + // Encoding as symbols can reduce the encoded size significantly. // - // This is opt-in, as there may be a performance hit to checking circular references. - CheckCircularRef bool - - // RecursiveEmptyCheck controls whether we descend into interfaces, structs and pointers - // when checking if a value is empty. + // However, during decoding, each string to be encoded as a symbol must + // be checked to see if it has been seen before. Consequently, encoding time + // will increase if using symbols, because string comparisons has a clear cost. // - // Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls. - RecursiveEmptyCheck bool + // Sample values: + // AsSymbolNone + // AsSymbolAll + // AsSymbolMapStringKeys + // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag + AsSymbols AsSymbolFlag +} - // Raw controls whether we encode Raw values. - // This is a "dangerous" option and must be explicitly set. - // If set, we blindly encode Raw values as-is, without checking - // if they are a correct representation of a value in that format. - // If unset, we error out. - Raw bool +// --------------------------------------------- - // StringToRaw controls how strings are encoded. - // - // As a go string is just an (immutable) sequence of bytes, - // it can be encoded either as raw bytes or as a UTF string. - // - // By default, strings are encoded as UTF-8. - // but can be treated as []byte during an encode. - // - // Note that things which we know (by definition) to be UTF-8 - // are ALWAYS encoded as UTF-8 strings. - // These include encoding.TextMarshaler, time.Format calls, struct field names, etc. - StringToRaw bool - - // // AsSymbols defines what should be encoded as symbols. - // // - // // Encoding as symbols can reduce the encoded size significantly. - // // - // // However, during decoding, each string to be encoded as a symbol must - // // be checked to see if it has been seen before. Consequently, encoding time - // // will increase if using symbols, because string comparisons has a clear cost. - // // - // // Sample values: - // // AsSymbolNone - // // AsSymbolAll - // // AsSymbolMapStringKeys - // // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag - // AsSymbols AsSymbolFlag +type simpleIoEncWriterWriter struct { + w io.Writer + bw io.ByteWriter + sw ioEncStringWriter } -// --------------------------------------------- +func (o *simpleIoEncWriterWriter) WriteByte(c byte) (err error) { + if o.bw != nil { + return o.bw.WriteByte(c) + } + _, err = o.w.Write([]byte{c}) + return +} -/* +func (o *simpleIoEncWriterWriter) WriteString(s string) (n int, err error) { + if o.sw != nil { + return o.sw.WriteString(s) + } + return o.w.Write([]byte(s)) +} -type ioEncStringWriter interface { - WriteString(s string) (n int, err error) +func (o *simpleIoEncWriterWriter) Write(p []byte) (n int, err error) { + return o.w.Write(p) } +// ---------------------------------------- + // ioEncWriter implements encWriter and can write to an io.Writer implementation type ioEncWriter struct { - w io.Writer - ww io.Writer - bw io.ByteWriter - sw ioEncStringWriter - fw ioFlusher - b [8]byte + w ioEncWriterWriter + x [8]byte // temp byte array re-used internally for efficiency } -func (z *ioEncWriter) reset(w io.Writer) { - z.w = w - var ok bool - if z.bw, ok = w.(io.ByteWriter); !ok { - z.bw = z - } - if z.sw, ok = w.(ioEncStringWriter); !ok { - z.sw = z - } - z.fw, _ = w.(ioFlusher) - z.ww = w +func (z *ioEncWriter) writeUint16(v uint16) { + bigen.PutUint16(z.x[:2], v) + z.writeb(z.x[:2]) } -func (z *ioEncWriter) WriteByte(b byte) (err error) { - z.b[0] = b - _, err = z.w.Write(z.b[:1]) - return +func (z *ioEncWriter) writeUint32(v uint32) { + bigen.PutUint32(z.x[:4], v) + z.writeb(z.x[:4]) } -func (z *ioEncWriter) WriteString(s string) (n int, err error) { - return z.w.Write(bytesView(s)) +func (z *ioEncWriter) writeUint64(v uint64) { + bigen.PutUint64(z.x[:8], v) + z.writeb(z.x[:8]) } func (z *ioEncWriter) writeb(bs []byte) { - if _, err := z.ww.Write(bs); err != nil { + if len(bs) == 0 { + return + } + n, err := z.w.Write(bs) + if err != nil { panic(err) } + if n != len(bs) { + encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(bs), n) + } } func (z *ioEncWriter) writestr(s string) { - if _, err := z.sw.WriteString(s); err != nil { + n, err := z.w.WriteString(s) + if err != nil { panic(err) } + if n != len(s) { + encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(s), n) + } } func (z *ioEncWriter) writen1(b byte) { - if err := z.bw.WriteByte(b); err != nil { + if err := z.w.WriteByte(b); err != nil { panic(err) } } -func (z *ioEncWriter) writen2(b1, b2 byte) { - var err error - if err = z.bw.WriteByte(b1); err == nil { - if err = z.bw.WriteByte(b2); err == nil { - return - } - } - panic(err) -} - -// func (z *ioEncWriter) writen5(b1, b2, b3, b4, b5 byte) { -// z.b[0], z.b[1], z.b[2], z.b[3], z.b[4] = b1, b2, b3, b4, b5 -// if _, err := z.ww.Write(z.b[:5]); err != nil { -// panic(err) -// } -// } - -//go:noinline - so *encWriterSwitch.XXX has the bytesEncAppender.XXX inlined -func (z *ioEncWriter) end() { - if z.fw != nil { - if err := z.fw.Flush(); err != nil { - panic(err) - } - } +func (z *ioEncWriter) writen2(b1 byte, b2 byte) { + z.writen1(b1) + z.writen1(b2) } -*/ +func (z *ioEncWriter) atEndOfEncode() {} -// --------------------------------------------- - -// bufioEncWriter -type bufioEncWriter struct { - buf []byte - w io.Writer - n int - sz int // buf size - - // Extensions can call Encode() within a current Encode() call. - // We need to know when the top level Encode() call returns, - // so we can decide whether to Release() or not. - calls uint16 // what depth in mustDecode are we in now. - - _ [6]uint8 // padding +// ---------------------------------------- - bytesBufPooler - - _ [1]uint64 // padding - // a int - // b [4]byte - // err +// bytesEncWriter implements encWriter and can write to an byte slice. +// It is used by Marshal function. +type bytesEncWriter struct { + b []byte + c int // cursor + out *[]byte // write out on atEndOfEncode } -func (z *bufioEncWriter) reset(w io.Writer, bufsize int) { - z.w = w - z.n = 0 - z.calls = 0 - if bufsize <= 0 { - bufsize = defEncByteBufSize - } - z.sz = bufsize - if cap(z.buf) >= bufsize { - z.buf = z.buf[:cap(z.buf)] - } else { - z.buf = z.bytesBufPooler.get(bufsize) - // z.buf = make([]byte, bufsize) - } +func (z *bytesEncWriter) writeUint16(v uint16) { + c := z.grow(2) + z.b[c] = byte(v >> 8) + z.b[c+1] = byte(v) } -func (z *bufioEncWriter) release() { - z.buf = nil - z.bytesBufPooler.end() +func (z *bytesEncWriter) writeUint32(v uint32) { + c := z.grow(4) + z.b[c] = byte(v >> 24) + z.b[c+1] = byte(v >> 16) + z.b[c+2] = byte(v >> 8) + z.b[c+3] = byte(v) } -//go:noinline - flush only called intermittently -func (z *bufioEncWriter) flushErr() (err error) { - n, err := z.w.Write(z.buf[:z.n]) - z.n -= n - if z.n > 0 && err == nil { - err = io.ErrShortWrite - } - if n > 0 && z.n > 0 { - copy(z.buf, z.buf[n:z.n+n]) - } - return err +func (z *bytesEncWriter) writeUint64(v uint64) { + c := z.grow(8) + z.b[c] = byte(v >> 56) + z.b[c+1] = byte(v >> 48) + z.b[c+2] = byte(v >> 40) + z.b[c+3] = byte(v >> 32) + z.b[c+4] = byte(v >> 24) + z.b[c+5] = byte(v >> 16) + z.b[c+6] = byte(v >> 8) + z.b[c+7] = byte(v) } -func (z *bufioEncWriter) flush() { - if err := z.flushErr(); err != nil { - panic(err) +func (z *bytesEncWriter) writeb(s []byte) { + if len(s) == 0 { + return } + c := z.grow(len(s)) + copy(z.b[c:], s) } -func (z *bufioEncWriter) writeb(s []byte) { -LOOP: - a := len(z.buf) - z.n - if len(s) > a { - z.n += copy(z.buf[z.n:], s[:a]) - s = s[a:] - z.flush() - goto LOOP - } - z.n += copy(z.buf[z.n:], s) +func (z *bytesEncWriter) writestr(s string) { + c := z.grow(len(s)) + copy(z.b[c:], s) } -func (z *bufioEncWriter) writestr(s string) { - // z.writeb(bytesView(s)) // inlined below -LOOP: - a := len(z.buf) - z.n - if len(s) > a { - z.n += copy(z.buf[z.n:], s[:a]) - s = s[a:] - z.flush() - goto LOOP - } - z.n += copy(z.buf[z.n:], s) +func (z *bytesEncWriter) writen1(b1 byte) { + c := z.grow(1) + z.b[c] = b1 } -func (z *bufioEncWriter) writen1(b1 byte) { - if 1 > len(z.buf)-z.n { - z.flush() - } - z.buf[z.n] = b1 - z.n++ +func (z *bytesEncWriter) writen2(b1 byte, b2 byte) { + c := z.grow(2) + z.b[c] = b1 + z.b[c+1] = b2 } -func (z *bufioEncWriter) writen2(b1, b2 byte) { - if 2 > len(z.buf)-z.n { - z.flush() - } - z.buf[z.n+1] = b2 - z.buf[z.n] = b1 - z.n += 2 +func (z *bytesEncWriter) atEndOfEncode() { + *(z.out) = z.b[:z.c] } -func (z *bufioEncWriter) endErr() (err error) { - if z.n > 0 { - err = z.flushErr() +func (z *bytesEncWriter) grow(n int) (oldcursor int) { + oldcursor = z.c + z.c = oldcursor + n + if z.c > cap(z.b) { + // Tried using appendslice logic: (if cap < 1024, *2, else *1.25). + // However, it was too expensive, causing too many iterations of copy. + // Using bytes.Buffer model was much better (2*cap + n) + bs := make([]byte, 2*cap(z.b)+n) + copy(bs, z.b[:oldcursor]) + z.b = bs + } else if z.c > len(z.b) { + z.b = z.b[:cap(z.b)] } return } // --------------------------------------------- -// bytesEncAppender implements encWriter and can write to an byte slice. -type bytesEncAppender struct { - b []byte - out *[]byte +type encFnInfo struct { + ti *typeInfo + e *Encoder + ee encDriver + xfFn func(reflect.Value) ([]byte, error) + xfTag byte } -func (z *bytesEncAppender) writeb(s []byte) { - z.b = append(z.b, s...) -} -func (z *bytesEncAppender) writestr(s string) { - z.b = append(z.b, s...) -} -func (z *bytesEncAppender) writen1(b1 byte) { - z.b = append(z.b, b1) -} -func (z *bytesEncAppender) writen2(b1, b2 byte) { - z.b = append(z.b, b1, b2) +func (f *encFnInfo) builtin(rv reflect.Value) { + f.ee.encodeBuiltin(f.ti.rtid, rv.Interface()) } -func (z *bytesEncAppender) endErr() error { - *(z.out) = z.b - return nil -} -func (z *bytesEncAppender) reset(in []byte, out *[]byte) { - z.b = in[:0] - z.out = out + +func (f *encFnInfo) rawExt(rv reflect.Value) { + f.e.encRawExt(rv.Interface().(RawExt)) } -// --------------------------------------------- +func (f *encFnInfo) ext(rv reflect.Value) { + bs, fnerr := f.xfFn(rv) + if fnerr != nil { + panic(fnerr) + } + if bs == nil { + f.ee.encodeNil() + return + } + if f.e.hh.writeExt() { + f.ee.encodeExtPreamble(f.xfTag, len(bs)) + f.e.w.writeb(bs) + } else { + f.ee.encodeStringBytes(c_RAW, bs) + } -func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeRawExt(rv2i(rv).(*RawExt), e) } -func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeExt(rv2i(rv), f.xfTag, f.xfFn, e) +func (f *encFnInfo) binaryMarshal(rv reflect.Value) { + var bm binaryMarshaler + if f.ti.mIndir == 0 { + bm = rv.Interface().(binaryMarshaler) + } else if f.ti.mIndir == -1 { + bm = rv.Addr().Interface().(binaryMarshaler) + } else { + for j, k := int8(0), f.ti.mIndir; j < k; j++ { + if rv.IsNil() { + f.ee.encodeNil() + return + } + rv = rv.Elem() + } + bm = rv.Interface().(binaryMarshaler) + } + // debugf(">>>> binaryMarshaler: %T", rv.Interface()) + bs, fnerr := bm.MarshalBinary() + if fnerr != nil { + panic(fnerr) + } + if bs == nil { + f.ee.encodeNil() + } else { + f.ee.encodeStringBytes(c_RAW, bs) + } } -func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) { - rv2i(rv).(Selfer).CodecEncodeSelf(e) +func (f *encFnInfo) kBool(rv reflect.Value) { + f.ee.encodeBool(rv.Bool()) } -func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary() - e.marshalRaw(bs, fnerr) +func (f *encFnInfo) kString(rv reflect.Value) { + f.ee.encodeString(c_UTF8, rv.String()) } -func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText() - e.marshalUtf8(bs, fnerr) +func (f *encFnInfo) kFloat64(rv reflect.Value) { + f.ee.encodeFloat64(rv.Float()) } -func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON() - e.marshalAsis(bs, fnerr) +func (f *encFnInfo) kFloat32(rv reflect.Value) { + f.ee.encodeFloat32(float32(rv.Float())) } -func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) { - e.rawBytes(rv2i(rv).(Raw)) +func (f *encFnInfo) kInt(rv reflect.Value) { + f.ee.encodeInt(rv.Int()) } -func (e *Encoder) kInvalid(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeNil() +func (f *encFnInfo) kUint(rv reflect.Value) { + f.ee.encodeUint(rv.Uint()) } -func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) { - e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv) +func (f *encFnInfo) kInvalid(rv reflect.Value) { + f.ee.encodeNil() } -func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) { - ti := f.ti - ee := e.e - // array may be non-addressable, so we have to manage with care - // (don't call rv.Bytes, rv.Slice, etc). - // E.g. type struct S{B [2]byte}; - // Encode(S{}) will bomb on "panic: slice of unaddressable array". - if f.seq != seqTypeArray { - if rv.IsNil() { - ee.EncodeNil() +func (f *encFnInfo) kErr(rv reflect.Value) { + encErr("Unsupported kind: %s, for: %#v", rv.Kind(), rv) +} + +func (f *encFnInfo) kSlice(rv reflect.Value) { + if rv.IsNil() { + f.ee.encodeNil() + return + } + + if shortCircuitReflectToFastPath { + switch f.ti.rtid { + case intfSliceTypId: + f.e.encSliceIntf(rv.Interface().([]interface{})) return - } - // If in this method, then there was no extension function defined. - // So it's okay to treat as []byte. - if ti.rtid == uint8SliceTypId { - ee.EncodeStringBytesRaw(rv.Bytes()) + case strSliceTypId: + f.e.encSliceStr(rv.Interface().([]string)) + return + case uint64SliceTypId: + f.e.encSliceUint64(rv.Interface().([]uint64)) + return + case int64SliceTypId: + f.e.encSliceInt64(rv.Interface().([]int64)) return } } - if f.seq == seqTypeChan && ti.chandir&uint8(reflect.RecvDir) == 0 { - e.errorf("send-only channel cannot be encoded") - } - elemsep := e.esep - rtelem := ti.elem - rtelemIsByte := uint8TypId == rt2id(rtelem) // NOT rtelem.Kind() == reflect.Uint8 - var l int - // if a slice, array or chan of bytes, treat specially - if rtelemIsByte { - switch f.seq { - case seqTypeSlice: - ee.EncodeStringBytesRaw(rv.Bytes()) - case seqTypeArray: - l = rv.Len() - if rv.CanAddr() { - ee.EncodeStringBytesRaw(rv.Slice(0, l).Bytes()) - } else { - var bs []byte - if l <= cap(e.b) { - bs = e.b[:l] - } else { - bs = make([]byte, l) - } - reflect.Copy(reflect.ValueOf(bs), rv) - ee.EncodeStringBytesRaw(bs) - } - case seqTypeChan: - // do not use range, so that the number of elements encoded - // does not change, and encoding does not hang waiting on someone to close chan. - // for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) } - // ch := rv2i(rv).(<-chan byte) // fix error - that this is a chan byte, not a <-chan byte. - - if rv.IsNil() { - ee.EncodeNil() - break - } - bs := e.b[:0] - irv := rv2i(rv) - ch, ok := irv.(<-chan byte) - if !ok { - ch = irv.(chan byte) - } - - L1: - switch timeout := e.h.ChanRecvTimeout; { - case timeout == 0: // only consume available - for { - select { - case b := <-ch: - bs = append(bs, b) - default: - break L1 - } - } - case timeout > 0: // consume until timeout - tt := time.NewTimer(timeout) - for { - select { - case b := <-ch: - bs = append(bs, b) - case <-tt.C: - // close(tt.C) - break L1 - } - } - default: // consume until close - for b := range ch { - bs = append(bs, b) - } - } - ee.EncodeStringBytesRaw(bs) - } + // If in this method, then there was no extension function defined. + // So it's okay to treat as []byte. + if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 { + f.ee.encodeStringBytes(c_RAW, rv.Bytes()) return } - // if chan, consume chan into a slice, and work off that slice. - if f.seq == seqTypeChan { - rvcs := reflect.Zero(reflect.SliceOf(rtelem)) - timeout := e.h.ChanRecvTimeout - if timeout < 0 { // consume until close - for { - recv, recvOk := rv.Recv() - if !recvOk { - break - } - rvcs = reflect.Append(rvcs, recv) - } - } else { - cases := make([]reflect.SelectCase, 2) - cases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: rv} - if timeout == 0 { - cases[1] = reflect.SelectCase{Dir: reflect.SelectDefault} - } else { - tt := time.NewTimer(timeout) - cases[1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tt.C)} - } - for { - chosen, recv, recvOk := reflect.Select(cases) - if chosen == 1 || !recvOk { - break - } - rvcs = reflect.Append(rvcs, recv) - } - } - rv = rvcs // TODO: ensure this doesn't mess up anywhere that rv of kind chan is expected - } - - l = rv.Len() - if ti.mbs { + l := rv.Len() + if f.ti.mbs { if l%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", l) - return + encErr("mapBySlice: invalid length (must be divisible by 2): %v", l) } - ee.WriteMapStart(l / 2) + f.ee.encodeMapPreamble(l / 2) } else { - ee.WriteArrayStart(l) + f.ee.encodeArrayPreamble(l) } - - if l > 0 { - var fn *codecFn - for rtelem.Kind() == reflect.Ptr { - rtelem = rtelem.Elem() - } - // if kind is reflect.Interface, do not pre-determine the - // encoding type, because preEncodeValue may break it down to - // a concrete type and kInterface will bomb. - if rtelem.Kind() != reflect.Interface { - fn = e.h.fn(rtelem, true, true) - } - for j := 0; j < l; j++ { - if elemsep { - if ti.mbs { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } else { - ee.WriteArrayElem() - } - } - e.encodeValue(rv.Index(j), fn, true) - } + if l == 0 { + return } - - if ti.mbs { - ee.WriteMapEnd() - } else { - ee.WriteArrayEnd() + for j := 0; j < l; j++ { + // TODO: Consider perf implication of encoding odd index values as symbols if type is string + f.e.encodeValue(rv.Index(j)) } } -func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) { - fti := f.ti - tisfi := fti.sfiSrc - toMap := !(fti.toArray || e.h.StructToArray) - if toMap { - tisfi = fti.sfiSort - } +func (f *encFnInfo) kArray(rv reflect.Value) { + // We cannot share kSlice method, because the array may be non-addressable. + // E.g. type struct S{B [2]byte}; Encode(S{}) will bomb on "panic: slice of unaddressable array". + // So we have to duplicate the functionality here. + // f.e.encodeValue(rv.Slice(0, rv.Len())) + // f.kSlice(rv.Slice(0, rv.Len())) - ee := e.e - - sfn := structFieldNode{v: rv, update: false} - if toMap { - ee.WriteMapStart(len(tisfi)) - if e.esep { - for _, si := range tisfi { - ee.WriteMapElemKey() - e.kStructFieldKey(fti.keyType, si.encNameAsciiAlphaNum, si.encName) - ee.WriteMapElemValue() - e.encodeValue(sfn.field(si), nil, true) - } - } else { - for _, si := range tisfi { - e.kStructFieldKey(fti.keyType, si.encNameAsciiAlphaNum, si.encName) - e.encodeValue(sfn.field(si), nil, true) - } + l := rv.Len() + // Handle an array of bytes specially (in line with what is done for slices) + if f.ti.rt.Elem().Kind() == reflect.Uint8 { + if l == 0 { + f.ee.encodeStringBytes(c_RAW, nil) + return } - ee.WriteMapEnd() - } else { - ee.WriteArrayStart(len(tisfi)) - if e.esep { - for _, si := range tisfi { - ee.WriteArrayElem() - e.encodeValue(sfn.field(si), nil, true) - } + var bs []byte + if rv.CanAddr() { + bs = rv.Slice(0, l).Bytes() } else { - for _, si := range tisfi { - e.encodeValue(sfn.field(si), nil, true) + bs = make([]byte, l) + for i := 0; i < l; i++ { + bs[i] = byte(rv.Index(i).Uint()) } } - ee.WriteArrayEnd() + f.ee.encodeStringBytes(c_RAW, bs) + return } -} -func (e *Encoder) kStructFieldKey(keyType valueType, encNameAsciiAlphaNum bool, encName string) { - encStructFieldKey(encName, e.e, e.w, keyType, encNameAsciiAlphaNum, e.js) + if f.ti.mbs { + if l%2 == 1 { + encErr("mapBySlice: invalid length (must be divisible by 2): %v", l) + } + f.ee.encodeMapPreamble(l / 2) + } else { + f.ee.encodeArrayPreamble(l) + } + if l == 0 { + return + } + for j := 0; j < l; j++ { + // TODO: Consider perf implication of encoding odd index values as symbols if type is string + f.e.encodeValue(rv.Index(j)) + } } -func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { +func (f *encFnInfo) kStruct(rv reflect.Value) { fti := f.ti - elemsep := e.esep - tisfi := fti.sfiSrc - var newlen int + newlen := len(fti.sfi) + rvals := make([]reflect.Value, newlen) + var encnames []string + e := f.e + tisfi := fti.sfip toMap := !(fti.toArray || e.h.StructToArray) - var mf map[string]interface{} - if f.ti.mf { - mf = rv2i(rv).(MissingFielder).CodecMissingFields() - toMap = true - newlen += len(mf) - } else if f.ti.mfp { - if rv.CanAddr() { - mf = rv2i(rv.Addr()).(MissingFielder).CodecMissingFields() - } else { - // make a new addressable value of same one, and use it - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - mf = rv2i(rv2).(MissingFielder).CodecMissingFields() - } - toMap = true - newlen += len(mf) - } // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct) if toMap { - tisfi = fti.sfiSort + tisfi = fti.sfi + encnames = make([]string, newlen) } - newlen += len(tisfi) - ee := e.e - - // Use sync.Pool to reduce allocating slices unnecessarily. - // The cost of sync.Pool is less than the cost of new allocation. - // - // Each element of the array pools one of encStructPool(8|16|32|64). - // It allows the re-use of slices up to 64 in length. - // A performance cost of encoding structs was collecting - // which values were empty and should be omitted. - // We needed slices of reflect.Value and string to collect them. - // This shared pool reduces the amount of unnecessary creation we do. - // The cost is that of locking sometimes, but sync.Pool is efficient - // enough to reduce thread contention. - - // fmt.Printf(">>>>>>>>>>>>>> encode.kStruct: newlen: %d\n", newlen) - var spool sfiRvPooler - var fkvs = spool.get(newlen) - - var kv sfiRv - recur := e.h.RecursiveEmptyCheck - sfn := structFieldNode{v: rv, update: false} newlen = 0 for _, si := range tisfi { - // kv.r = si.field(rv, false) - kv.r = sfn.field(si) + if si.i != -1 { + rvals[newlen] = rv.Field(int(si.i)) + } else { + rvals[newlen] = rv.FieldByIndex(si.is) + } if toMap { - if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) { + if si.omitEmpty && isEmptyValue(rvals[newlen]) { continue } - kv.v = si // si.encName + encnames[newlen] = si.encName } else { - // use the zero value. - // if a reference or struct, set to nil (so you do not output too much) - if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) { - switch kv.r.Kind() { - case reflect.Struct, reflect.Interface, reflect.Ptr, - reflect.Array, reflect.Map, reflect.Slice: - kv.r = reflect.Value{} //encode as nil - } + if si.omitEmpty && isEmptyValue(rvals[newlen]) { + rvals[newlen] = reflect.Value{} //encode as nil } } - fkvs[newlen] = kv newlen++ } - fkvs = fkvs[:newlen] - - var mflen int - for k, v := range mf { - if k == "" { - delete(mf, k) - continue - } - if fti.infoFieldOmitempty && isEmptyValue(reflect.ValueOf(v), e.h.TypeInfos, recur, recur) { - delete(mf, k) - continue - } - mflen++ - } - var j int + // debugf(">>>> kStruct: newlen: %v", newlen) if toMap { - ee.WriteMapStart(newlen + mflen) - if elemsep { - for j = 0; j < len(fkvs); j++ { - kv = fkvs[j] - ee.WriteMapElemKey() - e.kStructFieldKey(fti.keyType, kv.v.encNameAsciiAlphaNum, kv.v.encName) - ee.WriteMapElemValue() - e.encodeValue(kv.r, nil, true) - } - } else { - for j = 0; j < len(fkvs); j++ { - kv = fkvs[j] - e.kStructFieldKey(fti.keyType, kv.v.encNameAsciiAlphaNum, kv.v.encName) - e.encodeValue(kv.r, nil, true) + ee := f.ee //don't dereference everytime + ee.encodeMapPreamble(newlen) + // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 + asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 + for j := 0; j < newlen; j++ { + if asSymbols { + ee.encodeSymbol(encnames[j]) + } else { + ee.encodeString(c_UTF8, encnames[j]) } + e.encodeValue(rvals[j]) } - // now, add the others - for k, v := range mf { - ee.WriteMapElemKey() - e.kStructFieldKey(fti.keyType, false, k) - ee.WriteMapElemValue() - e.encode(v) - } - ee.WriteMapEnd() } else { - ee.WriteArrayStart(newlen) - if elemsep { - for j = 0; j < len(fkvs); j++ { - ee.WriteArrayElem() - e.encodeValue(fkvs[j].r, nil, true) - } - } else { - for j = 0; j < len(fkvs); j++ { - e.encodeValue(fkvs[j].r, nil, true) - } + f.ee.encodeArrayPreamble(newlen) + for j := 0; j < newlen; j++ { + e.encodeValue(rvals[j]) } - ee.WriteArrayEnd() } - - // do not use defer. Instead, use explicit pool return at end of function. - // defer has a cost we are trying to avoid. - // If there is a panic and these slices are not returned, it is ok. - spool.end() } -func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { - ee := e.e +// func (f *encFnInfo) kPtr(rv reflect.Value) { +// debugf(">>>>>>> ??? encode kPtr called - shouldn't get called") +// if rv.IsNil() { +// f.ee.encodeNil() +// return +// } +// f.e.encodeValue(rv.Elem()) +// } + +func (f *encFnInfo) kInterface(rv reflect.Value) { if rv.IsNil() { - ee.EncodeNil() + f.ee.encodeNil() return } + f.e.encodeValue(rv.Elem()) +} - l := rv.Len() - ee.WriteMapStart(l) - if l == 0 { - ee.WriteMapEnd() +func (f *encFnInfo) kMap(rv reflect.Value) { + if rv.IsNil() { + f.ee.encodeNil() return } - // var asSymbols bool - // determine the underlying key and val encFn's for the map. - // This eliminates some work which is done for each loop iteration i.e. - // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn. - // - // However, if kind is reflect.Interface, do not pre-determine the - // encoding type, because preEncodeValue may break it down to - // a concrete type and kInterface will bomb. - var keyFn, valFn *codecFn - ti := f.ti - rtkey0 := ti.key - rtkey := rtkey0 - rtval0 := ti.elem - rtval := rtval0 - // rtkeyid := rt2id(rtkey0) - for rtval.Kind() == reflect.Ptr { - rtval = rtval.Elem() - } - if rtval.Kind() != reflect.Interface { - valFn = e.h.fn(rtval, true, true) + + if shortCircuitReflectToFastPath { + switch f.ti.rtid { + case mapIntfIntfTypId: + f.e.encMapIntfIntf(rv.Interface().(map[interface{}]interface{})) + return + case mapStrIntfTypId: + f.e.encMapStrIntf(rv.Interface().(map[string]interface{})) + return + case mapStrStrTypId: + f.e.encMapStrStr(rv.Interface().(map[string]string)) + return + case mapInt64IntfTypId: + f.e.encMapInt64Intf(rv.Interface().(map[int64]interface{})) + return + case mapUint64IntfTypId: + f.e.encMapUint64Intf(rv.Interface().(map[uint64]interface{})) + return + } } - mks := rv.MapKeys() - if e.h.Canonical { - e.kMapCanonical(rtkey, rv, mks, valFn) - ee.WriteMapEnd() + l := rv.Len() + f.ee.encodeMapPreamble(l) + if l == 0 { return } - - var keyTypeIsString = stringTypId == rt2id(rtkey0) // rtkeyid - if !keyTypeIsString { - for rtkey.Kind() == reflect.Ptr { - rtkey = rtkey.Elem() - } - if rtkey.Kind() != reflect.Interface { - // rtkeyid = rt2id(rtkey) - keyFn = e.h.fn(rtkey, true, true) - } + // keyTypeIsString := f.ti.rt.Key().Kind() == reflect.String + keyTypeIsString := f.ti.rt.Key() == stringTyp + var asSymbols bool + if keyTypeIsString { + asSymbols = f.e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 } - + mks := rv.MapKeys() // for j, lmks := 0, len(mks); j < lmks; j++ { for j := range mks { - if e.esep { - ee.WriteMapElemKey() - } if keyTypeIsString { - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(mks[j].String())) + if asSymbols { + f.ee.encodeSymbol(mks[j].String()) } else { - ee.EncodeStringEnc(cUTF8, mks[j].String()) + f.ee.encodeString(c_UTF8, mks[j].String()) } } else { - e.encodeValue(mks[j], keyFn, true) - } - if e.esep { - ee.WriteMapElemValue() + f.e.encodeValue(mks[j]) } - e.encodeValue(rv.MapIndex(mks[j]), valFn, true) - + f.e.encodeValue(rv.MapIndex(mks[j])) } - ee.WriteMapEnd() -} -func (e *Encoder) kMapCanonical(rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *codecFn) { - ee := e.e - elemsep := e.esep - // we previously did out-of-band if an extension was registered. - // This is not necessary, as the natural kind is sufficient for ordering. - - switch rtkey.Kind() { - case reflect.Bool: - mksv := make([]boolRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Bool() - } - sort.Sort(boolRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeBool(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.String: - mksv := make([]stringRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.String() - } - sort.Sort(stringRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(mksv[i].v)) - } else { - ee.EncodeStringEnc(cUTF8, mksv[i].v) - } - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: - mksv := make([]uintRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Uint() - } - sort.Sort(uintRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeUint(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - mksv := make([]intRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Int() - } - sort.Sort(intRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeInt(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Float32: - mksv := make([]floatRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Float() - } - sort.Sort(floatRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(mksv[i].v)) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Float64: - mksv := make([]floatRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Float() - } - sort.Sort(floatRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Struct: - if rv.Type() == timeTyp { - mksv := make([]timeRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = rv2i(k).(time.Time) - } - sort.Sort(timeRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeTime(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - break - } - fallthrough - default: - // out-of-band - // first encode each key to a []byte first, then sort them, then record - var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - mksbv := make([]bytesRv, len(mks)) - for i, k := range mks { - v := &mksbv[i] - l := len(mksv) - e2.MustEncode(k) - v.r = k - v.v = mksv[l:] - } - sort.Sort(bytesRvSlice(mksbv)) - for j := range mksbv { - if elemsep { - ee.WriteMapElemKey() - } - e.asis(mksbv[j].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksbv[j].r), valFn, true) - } - } } -// // -------------------------------------------------- - -type encWriterSwitch struct { - // wi *ioEncWriter - wb bytesEncAppender - wf *bufioEncWriter - // typ entryType - bytes bool // encoding to []byte - esep bool // whether it has elem separators - isas bool // whether e.as != nil - js bool // is json encoder? - be bool // is binary encoder? - _ [2]byte // padding - // _ [2]uint64 // padding - // _ uint64 // padding -} +// -------------------------------------------------- -func (z *encWriterSwitch) writeb(s []byte) { - if z.bytes { - z.wb.writeb(s) - } else { - z.wf.writeb(s) - } -} -func (z *encWriterSwitch) writestr(s string) { - if z.bytes { - z.wb.writestr(s) - } else { - z.wf.writestr(s) - } -} -func (z *encWriterSwitch) writen1(b1 byte) { - if z.bytes { - z.wb.writen1(b1) - } else { - z.wf.writen1(b1) - } -} -func (z *encWriterSwitch) writen2(b1, b2 byte) { - if z.bytes { - z.wb.writen2(b1, b2) - } else { - z.wf.writen2(b1, b2) - } -} -func (z *encWriterSwitch) endErr() error { - if z.bytes { - return z.wb.endErr() - } - return z.wf.endErr() +// encFn encapsulates the captured variables and the encode function. +// This way, we only do some calculations one times, and pass to the +// code block that should be called (encapsulated in a function) +// instead of executing the checks every time. +type encFn struct { + i *encFnInfo + f func(*encFnInfo, reflect.Value) } -func (z *encWriterSwitch) end() { - if err := z.endErr(); err != nil { - panic(err) - } -} +// -------------------------------------------------- -/* - -// ------------------------------------------ -func (z *encWriterSwitch) writeb(s []byte) { - switch z.typ { - case entryTypeBytes: - z.wb.writeb(s) - case entryTypeIo: - z.wi.writeb(s) - default: - z.wf.writeb(s) - } -} -func (z *encWriterSwitch) writestr(s string) { - switch z.typ { - case entryTypeBytes: - z.wb.writestr(s) - case entryTypeIo: - z.wi.writestr(s) - default: - z.wf.writestr(s) - } -} -func (z *encWriterSwitch) writen1(b1 byte) { - switch z.typ { - case entryTypeBytes: - z.wb.writen1(b1) - case entryTypeIo: - z.wi.writen1(b1) - default: - z.wf.writen1(b1) - } -} -func (z *encWriterSwitch) writen2(b1, b2 byte) { - switch z.typ { - case entryTypeBytes: - z.wb.writen2(b1, b2) - case entryTypeIo: - z.wi.writen2(b1, b2) - default: - z.wf.writen2(b1, b2) - } -} -func (z *encWriterSwitch) end() { - switch z.typ { - case entryTypeBytes: - z.wb.end() - case entryTypeIo: - z.wi.end() - default: - z.wf.end() - } -} - -// ------------------------------------------ -func (z *encWriterSwitch) writeb(s []byte) { - if z.bytes { - z.wb.writeb(s) - } else { - z.wi.writeb(s) - } -} -func (z *encWriterSwitch) writestr(s string) { - if z.bytes { - z.wb.writestr(s) - } else { - z.wi.writestr(s) - } -} -func (z *encWriterSwitch) writen1(b1 byte) { - if z.bytes { - z.wb.writen1(b1) - } else { - z.wi.writen1(b1) - } -} -func (z *encWriterSwitch) writen2(b1, b2 byte) { - if z.bytes { - z.wb.writen2(b1, b2) - } else { - z.wi.writen2(b1, b2) - } -} -func (z *encWriterSwitch) end() { - if z.bytes { - z.wb.end() - } else { - z.wi.end() - } -} - -*/ - -// Encoder writes an object to an output stream in a supported format. -// -// Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used -// concurrently in multiple goroutines. -// -// However, as Encoder could be allocation heavy to initialize, a Reset method is provided -// so its state can be reused to decode new input streams repeatedly. -// This is the idiomatic way to use. +// An Encoder writes an object to an output stream in the codec format. type Encoder struct { - panicHdl - // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder - e encDriver - - // NOTE: Encoder shouldn't call it's write methods, - // as the handler MAY need to do some coordination. - w *encWriterSwitch - - // bw *bufio.Writer - as encDriverAsis - - err error - + w encWriter + e encDriver h *BasicHandle hh Handle - // ---- cpu cache line boundary? + 3 - encWriterSwitch - - ci set - - b [(5 * 8)]byte // for encoding chan or (non-addressable) [N]byte - - // ---- writable fields during execution --- *try* to keep in sep cache line - - // ---- cpu cache line boundary? - // b [scratchByteArrayLen]byte - // _ [cacheLineSize - scratchByteArrayLen]byte // padding - // b [cacheLineSize - (8 * 0)]byte // used for encoding a chan or (non-addressable) array of bytes + f map[uintptr]encFn + x []uintptr + s []encFn } // NewEncoder returns an Encoder for encoding into an io.Writer. // -// For efficiency, Users are encouraged to configure WriterBufferSize on the handle -// OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer). +// For efficiency, Users are encouraged to pass in a memory buffered writer +// (eg bufio.Writer, bytes.Buffer). func NewEncoder(w io.Writer, h Handle) *Encoder { - e := newEncoder(h) - e.Reset(w) - return e + ww, ok := w.(ioEncWriterWriter) + if !ok { + sww := simpleIoEncWriterWriter{w: w} + sww.bw, _ = w.(io.ByteWriter) + sww.sw, _ = w.(ioEncStringWriter) + ww = &sww + //ww = bufio.NewWriterSize(w, defEncByteBufSize) + } + z := ioEncWriter{ + w: ww, + } + return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)} } // NewEncoderBytes returns an encoder for encoding directly and efficiently @@ -1270,541 +629,373 @@ func NewEncoder(w io.Writer, h Handle) *Encoder { // It will potentially replace the output byte slice pointed to. // After encoding, the out parameter contains the encoded contents. func NewEncoderBytes(out *[]byte, h Handle) *Encoder { - e := newEncoder(h) - e.ResetBytes(out) - return e -} - -func newEncoder(h Handle) *Encoder { - e := &Encoder{h: basicHandle(h), err: errEncoderNotInitialized} - e.bytes = true - if useFinalizers { - runtime.SetFinalizer(e, (*Encoder).finalize) - // xdebugf(">>>> new(Encoder) with finalizer") - } - e.w = &e.encWriterSwitch - e.hh = h - e.esep = h.hasElemSeparators() - - return e -} - -func (e *Encoder) resetCommon() { - // e.w = &e.encWriterSwitch - if e.e == nil || e.hh.recreateEncDriver(e.e) { - e.e = e.hh.newEncDriver(e) - e.as, e.isas = e.e.(encDriverAsis) - // e.cr, _ = e.e.(containerStateRecv) - } - e.be = e.hh.isBinary() - _, e.js = e.hh.(*JsonHandle) - e.e.reset() - e.err = nil -} - -// Reset resets the Encoder with a new output stream. -// -// This accommodates using the state of the Encoder, -// where it has "cached" information about sub-engines. -func (e *Encoder) Reset(w io.Writer) { - if w == nil { - return - } - // var ok bool - e.bytes = false - if e.wf == nil { - e.wf = new(bufioEncWriter) - } - // e.typ = entryTypeUnset - // if e.h.WriterBufferSize > 0 { - // // bw := bufio.NewWriterSize(w, e.h.WriterBufferSize) - // // e.wi.bw = bw - // // e.wi.sw = bw - // // e.wi.fw = bw - // // e.wi.ww = bw - // if e.wf == nil { - // e.wf = new(bufioEncWriter) - // } - // e.wf.reset(w, e.h.WriterBufferSize) - // e.typ = entryTypeBufio - // } else { - // if e.wi == nil { - // e.wi = new(ioEncWriter) - // } - // e.wi.reset(w) - // e.typ = entryTypeIo - // } - e.wf.reset(w, e.h.WriterBufferSize) - // e.typ = entryTypeBufio - - // e.w = e.wi - e.resetCommon() -} - -// ResetBytes resets the Encoder with a new destination output []byte. -func (e *Encoder) ResetBytes(out *[]byte) { - if out == nil { - return - } - var in []byte = *out + in := *out if in == nil { in = make([]byte, defEncByteBufSize) } - e.bytes = true - // e.typ = entryTypeBytes - e.wb.reset(in, out) - // e.w = &e.wb - e.resetCommon() + z := bytesEncWriter{ + b: in, + out: out, + } + return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)} } -// Encode writes an object into a stream. +// Encode writes an object into a stream in the codec format. // -// Encoding can be configured via the struct tag for the fields. -// The key (in the struct tags) that we look at is configurable. +// Encoding can be configured via the "codec" struct tag for the fields. // -// By default, we look up the "codec" key in the struct field's tags, -// and fall bak to the "json" key if "codec" is absent. -// That key in struct field's tag value is the key name, +// The "codec" key in struct field's tag value is the key name, // followed by an optional comma and options. // // To set an option on all fields (e.g. omitempty on all fields), you -// can create a field called _struct, and set flags on it. The options -// which can be set on _struct are: -// - omitempty: so all fields are omitted if empty -// - toarray: so struct is encoded as an array -// - int: so struct key names are encoded as signed integers (instead of strings) -// - uint: so struct key names are encoded as unsigned integers (instead of strings) -// - float: so struct key names are encoded as floats (instead of strings) -// More details on these below. +// can create a field called _struct, and set flags on it. // // Struct values "usually" encode as maps. Each exported struct field is encoded unless: -// - the field's tag is "-", OR -// - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option. +// - the field's codec tag is "-", OR +// - the field is empty and its codec tag specifies the "omitempty" option. // // When encoding as a map, the first string in the tag (before the comma) // is the map key string to use when encoding. -// ... -// This key is typically encoded as a string. -// However, there are instances where the encoded stream has mapping keys encoded as numbers. -// For example, some cbor streams have keys as integer codes in the stream, but they should map -// to fields in a structured object. Consequently, a struct is the natural representation in code. -// For these, configure the struct to encode/decode the keys as numbers (instead of string). -// This is done with the int,uint or float option on the _struct field (see above). // // However, struct values may encode as arrays. This happens when: // - StructToArray Encode option is set, OR -// - the tag on the _struct field sets the "toarray" option -// Note that omitempty is ignored when encoding struct values as arrays, -// as an entry must be encoded for each field, to maintain its position. +// - the codec tag on the _struct field sets the "toarray" option // // Values with types that implement MapBySlice are encoded as stream maps. // // The empty values (for omitempty option) are false, 0, any nil pointer // or interface value, and any array, slice, map, or string of length zero. // -// Anonymous fields are encoded inline except: -// - the struct tag specifies a replacement name (first value) -// - the field is of an interface type +// Anonymous fields are encoded inline if no struct tag is present. +// Else they are encoded as regular fields. // // Examples: // -// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below. // type MyStruct struct { // _struct bool `codec:",omitempty"` //set omitempty for every field // Field1 string `codec:"-"` //skip this field // Field2 int `codec:"myName"` //Use key "myName" in encode stream // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty. -// io.Reader //use key "Reader". -// MyStruct `codec:"my1" //use key "my1". -// MyStruct //inline it // ... // } // // type MyStruct struct { -// _struct bool `codec:",toarray"` //encode struct as an array -// } -// -// type MyStruct struct { -// _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys -// Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1) -// Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2) +// _struct bool `codec:",omitempty,toarray"` //set omitempty for every field +// //and encode struct as an array // } // // The mode of encoding is based on the type of the value. When a value is seen: -// - If a Selfer, call its CodecEncodeSelf method // - If an extension is registered for it, call that extension function -// - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method +// - If it implements BinaryMarshaler, call its MarshalBinary() (data []byte, err error) // - Else encode it based on its reflect.Kind // // Note that struct field names and keys in map[string]XXX will be treated as symbols. // Some formats support symbols (e.g. binc) and will properly encode the string // only once in the stream, and use a tag to refer to it thereafter. func (e *Encoder) Encode(v interface{}) (err error) { - // tried to use closure, as runtime optimizes defer with no params. - // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc). - // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139 - // defer func() { e.deferred(&err) }() } - // { x, y := e, &err; defer func() { x.deferred(y) }() } - if e.err != nil { - return e.err - } - if recoverPanicToErr { - defer func() { - // if error occurred during encoding, return that error; - // else if error occurred on end'ing (i.e. during flush), return that error. - err = e.w.endErr() - x := recover() - if x == nil { - e.err = err - } else { - panicValToErr(e, x, &e.err) - err = e.err - } - }() - } - - // defer e.deferred(&err) - e.mustEncode(v) - return -} - -// MustEncode is like Encode, but panics if unable to Encode. -// This provides insight to the code location that triggered the error. -func (e *Encoder) MustEncode(v interface{}) { - if e.err != nil { - panic(e.err) - } - e.mustEncode(v) -} - -func (e *Encoder) mustEncode(v interface{}) { - if e.wf == nil { - e.encode(v) - e.e.atEndOfEncode() - e.w.end() - return - } - - if e.wf.buf == nil { - e.wf.buf = e.wf.bytesBufPooler.get(e.wf.sz) - } - e.wf.calls++ - + defer panicToErr(&err) e.encode(v) - - e.wf.calls-- - - if e.wf.calls == 0 { - e.e.atEndOfEncode() - e.w.end() - if !e.h.ExplicitRelease { - e.wf.release() - } - } -} - -// func (e *Encoder) deferred(err1 *error) { -// e.w.end() -// if recoverPanicToErr { -// if x := recover(); x != nil { -// panicValToErr(e, x, err1) -// panicValToErr(e, x, &e.err) -// } -// } -// } - -//go:noinline -- as it is run by finalizer -func (e *Encoder) finalize() { - // xdebugf("finalizing Encoder") - e.Release() -} - -// Release releases shared (pooled) resources. -// -// It is important to call Release() when done with an Encoder, so those resources -// are released instantly for use by subsequently created Encoders. -func (e *Encoder) Release() { - if e.wf != nil { - e.wf.release() - } + e.w.atEndOfEncode() + return } func (e *Encoder) encode(iv interface{}) { - // a switch with only concrete types can be optimized. - // consequently, we deal with nil and interfaces outside the switch. - - if iv == nil || definitelyNil(iv) { - e.e.EncodeNil() - return - } - switch v := iv.(type) { - // case nil: - // case Selfer: - case Raw: - e.rawBytes(v) + case nil: + e.e.encodeNil() + case reflect.Value: - e.encodeValue(v, nil, true) + e.encodeValue(v) case string: - if e.h.StringToRaw { - e.e.EncodeStringBytesRaw(bytesView(v)) - } else { - e.e.EncodeStringEnc(cUTF8, v) - } + e.e.encodeString(c_UTF8, v) case bool: - e.e.EncodeBool(v) + e.e.encodeBool(v) case int: - e.e.EncodeInt(int64(v)) + e.e.encodeInt(int64(v)) case int8: - e.e.EncodeInt(int64(v)) + e.e.encodeInt(int64(v)) case int16: - e.e.EncodeInt(int64(v)) + e.e.encodeInt(int64(v)) case int32: - e.e.EncodeInt(int64(v)) + e.e.encodeInt(int64(v)) case int64: - e.e.EncodeInt(v) + e.e.encodeInt(v) case uint: - e.e.EncodeUint(uint64(v)) + e.e.encodeUint(uint64(v)) case uint8: - e.e.EncodeUint(uint64(v)) + e.e.encodeUint(uint64(v)) case uint16: - e.e.EncodeUint(uint64(v)) + e.e.encodeUint(uint64(v)) case uint32: - e.e.EncodeUint(uint64(v)) + e.e.encodeUint(uint64(v)) case uint64: - e.e.EncodeUint(v) - case uintptr: - e.e.EncodeUint(uint64(v)) + e.e.encodeUint(v) case float32: - e.e.EncodeFloat32(v) + e.e.encodeFloat32(v) case float64: - e.e.EncodeFloat64(v) - case time.Time: - e.e.EncodeTime(v) + e.e.encodeFloat64(v) + + case []interface{}: + e.encSliceIntf(v) + case []string: + e.encSliceStr(v) + case []int64: + e.encSliceInt64(v) + case []uint64: + e.encSliceUint64(v) case []uint8: - e.e.EncodeStringBytesRaw(v) - - case *Raw: - e.rawBytes(*v) + e.e.encodeStringBytes(c_RAW, v) + + case map[interface{}]interface{}: + e.encMapIntfIntf(v) + case map[string]interface{}: + e.encMapStrIntf(v) + case map[string]string: + e.encMapStrStr(v) + case map[int64]interface{}: + e.encMapInt64Intf(v) + case map[uint64]interface{}: + e.encMapUint64Intf(v) case *string: - if e.h.StringToRaw { - e.e.EncodeStringBytesRaw(bytesView(*v)) - } else { - e.e.EncodeStringEnc(cUTF8, *v) - } + e.e.encodeString(c_UTF8, *v) case *bool: - e.e.EncodeBool(*v) + e.e.encodeBool(*v) case *int: - e.e.EncodeInt(int64(*v)) + e.e.encodeInt(int64(*v)) case *int8: - e.e.EncodeInt(int64(*v)) + e.e.encodeInt(int64(*v)) case *int16: - e.e.EncodeInt(int64(*v)) + e.e.encodeInt(int64(*v)) case *int32: - e.e.EncodeInt(int64(*v)) + e.e.encodeInt(int64(*v)) case *int64: - e.e.EncodeInt(*v) + e.e.encodeInt(*v) case *uint: - e.e.EncodeUint(uint64(*v)) + e.e.encodeUint(uint64(*v)) case *uint8: - e.e.EncodeUint(uint64(*v)) + e.e.encodeUint(uint64(*v)) case *uint16: - e.e.EncodeUint(uint64(*v)) + e.e.encodeUint(uint64(*v)) case *uint32: - e.e.EncodeUint(uint64(*v)) + e.e.encodeUint(uint64(*v)) case *uint64: - e.e.EncodeUint(*v) - case *uintptr: - e.e.EncodeUint(uint64(*v)) + e.e.encodeUint(*v) case *float32: - e.e.EncodeFloat32(*v) + e.e.encodeFloat32(*v) case *float64: - e.e.EncodeFloat64(*v) - case *time.Time: - e.e.EncodeTime(*v) - + e.e.encodeFloat64(*v) + + case *[]interface{}: + e.encSliceIntf(*v) + case *[]string: + e.encSliceStr(*v) + case *[]int64: + e.encSliceInt64(*v) + case *[]uint64: + e.encSliceUint64(*v) case *[]uint8: - e.e.EncodeStringBytesRaw(*v) + e.e.encodeStringBytes(c_RAW, *v) + + case *map[interface{}]interface{}: + e.encMapIntfIntf(*v) + case *map[string]interface{}: + e.encMapStrIntf(*v) + case *map[string]string: + e.encMapStrStr(*v) + case *map[int64]interface{}: + e.encMapInt64Intf(*v) + case *map[uint64]interface{}: + e.encMapUint64Intf(*v) default: - if v, ok := iv.(Selfer); ok { - v.CodecEncodeSelf(e) - } else if !fastpathEncodeTypeSwitch(iv, e) { - // checkfastpath=true (not false), as underlying slice/map type may be fast-path - e.encodeValue(reflect.ValueOf(iv), nil, true) - } + e.encodeValue(reflect.ValueOf(iv)) } } -func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn, checkFastpath bool) { - // if a valid fn is passed, it MUST BE for the dereferenced type of rv - var sptr uintptr - var rvp reflect.Value - var rvpValid bool -TOP: - switch rv.Kind() { - case reflect.Ptr: - if rv.IsNil() { - e.e.EncodeNil() - return - } - rvpValid = true - rvp = rv - rv = rv.Elem() - if e.h.CheckCircularRef && rv.Kind() == reflect.Struct { - // TODO: Movable pointers will be an issue here. Future problem. - sptr = rv.UnsafeAddr() - break TOP - } - goto TOP - case reflect.Interface: +func (e *Encoder) encodeValue(rv reflect.Value) { + for rv.Kind() == reflect.Ptr { if rv.IsNil() { - e.e.EncodeNil() + e.e.encodeNil() return } rv = rv.Elem() - goto TOP - case reflect.Slice, reflect.Map: - if rv.IsNil() { - e.e.EncodeNil() - return - } - case reflect.Invalid, reflect.Func: - e.e.EncodeNil() - return } - if sptr != 0 && (&e.ci).add(sptr) { - e.errorf("circular reference found: # %d", sptr) - } + rt := rv.Type() + rtid := reflect.ValueOf(rt).Pointer() - if fn == nil { - rt := rv.Type() - // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer - fn = e.h.fn(rt, checkFastpath, true) + // if e.f == nil && e.s == nil { debugf("---->Creating new enc f map for type: %v\n", rt) } + var fn encFn + var ok bool + if useMapForCodecCache { + fn, ok = e.f[rtid] + } else { + for i, v := range e.x { + if v == rtid { + fn, ok = e.s[i], true + break + } + } } - if fn.i.addrE { - if rvpValid { - fn.fe(e, &fn.i, rvp) - } else if rv.CanAddr() { - fn.fe(e, &fn.i, rv.Addr()) + if !ok { + // debugf("\tCreating new enc fn for type: %v\n", rt) + fi := encFnInfo{ti: getTypeInfo(rtid, rt), e: e, ee: e.e} + fn.i = &fi + if rtid == rawExtTypId { + fn.f = (*encFnInfo).rawExt + } else if e.e.isBuiltinType(rtid) { + fn.f = (*encFnInfo).builtin + } else if xfTag, xfFn := e.h.getEncodeExt(rtid); xfFn != nil { + fi.xfTag, fi.xfFn = xfTag, xfFn + fn.f = (*encFnInfo).ext + } else if supportBinaryMarshal && fi.ti.m { + fn.f = (*encFnInfo).binaryMarshal } else { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - fn.fe(e, &fn.i, rv2) + switch rk := rt.Kind(); rk { + case reflect.Bool: + fn.f = (*encFnInfo).kBool + case reflect.String: + fn.f = (*encFnInfo).kString + case reflect.Float64: + fn.f = (*encFnInfo).kFloat64 + case reflect.Float32: + fn.f = (*encFnInfo).kFloat32 + case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16: + fn.f = (*encFnInfo).kInt + case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16: + fn.f = (*encFnInfo).kUint + case reflect.Invalid: + fn.f = (*encFnInfo).kInvalid + case reflect.Slice: + fn.f = (*encFnInfo).kSlice + case reflect.Array: + fn.f = (*encFnInfo).kArray + case reflect.Struct: + fn.f = (*encFnInfo).kStruct + // case reflect.Ptr: + // fn.f = (*encFnInfo).kPtr + case reflect.Interface: + fn.f = (*encFnInfo).kInterface + case reflect.Map: + fn.f = (*encFnInfo).kMap + default: + fn.f = (*encFnInfo).kErr + } + } + if useMapForCodecCache { + if e.f == nil { + e.f = make(map[uintptr]encFn, 16) + } + e.f[rtid] = fn + } else { + e.s = append(e.s, fn) + e.x = append(e.x, rtid) } - } else { - fn.fe(e, &fn.i, rv) } - if sptr != 0 { - (&e.ci).remove(sptr) - } -} -// func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) { -// if fnerr != nil { -// panic(fnerr) -// } -// if bs == nil { -// e.e.EncodeNil() -// } else if asis { -// e.asis(bs) -// } else { -// e.e.EncodeStringBytesRaw(bs) -// } -// } + fn.f(fn.i, rv) -func (e *Encoder) marshalUtf8(bs []byte, fnerr error) { - if fnerr != nil { - panic(fnerr) +} + +func (e *Encoder) encRawExt(re RawExt) { + if re.Data == nil { + e.e.encodeNil() + return } - if bs == nil { - e.e.EncodeNil() + if e.hh.writeExt() { + e.e.encodeExtPreamble(re.Tag, len(re.Data)) + e.w.writeb(re.Data) } else { - e.e.EncodeStringEnc(cUTF8, stringView(bs)) + e.e.encodeStringBytes(c_RAW, re.Data) } } -func (e *Encoder) marshalAsis(bs []byte, fnerr error) { - if fnerr != nil { - panic(fnerr) +// --------------------------------------------- +// short circuit functions for common maps and slices + +func (e *Encoder) encSliceIntf(v []interface{}) { + e.e.encodeArrayPreamble(len(v)) + for _, v2 := range v { + e.encode(v2) } - if bs == nil { - e.e.EncodeNil() - } else { - e.asis(bs) +} + +func (e *Encoder) encSliceStr(v []string) { + e.e.encodeArrayPreamble(len(v)) + for _, v2 := range v { + e.e.encodeString(c_UTF8, v2) } } -func (e *Encoder) marshalRaw(bs []byte, fnerr error) { - if fnerr != nil { - panic(fnerr) +func (e *Encoder) encSliceInt64(v []int64) { + e.e.encodeArrayPreamble(len(v)) + for _, v2 := range v { + e.e.encodeInt(v2) } - if bs == nil { - e.e.EncodeNil() - } else { - e.e.EncodeStringBytesRaw(bs) +} + +func (e *Encoder) encSliceUint64(v []uint64) { + e.e.encodeArrayPreamble(len(v)) + for _, v2 := range v { + e.e.encodeUint(v2) } } -func (e *Encoder) asis(v []byte) { - if e.isas { - e.as.EncodeAsis(v) - } else { - e.w.writeb(v) +func (e *Encoder) encMapStrStr(v map[string]string) { + e.e.encodeMapPreamble(len(v)) + asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 + for k2, v2 := range v { + if asSymbols { + e.e.encodeSymbol(k2) + } else { + e.e.encodeString(c_UTF8, k2) + } + e.e.encodeString(c_UTF8, v2) } } -func (e *Encoder) rawBytes(vv Raw) { - v := []byte(vv) - if !e.h.Raw { - e.errorf("Raw values cannot be encoded: %v", v) +func (e *Encoder) encMapStrIntf(v map[string]interface{}) { + e.e.encodeMapPreamble(len(v)) + asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 + for k2, v2 := range v { + if asSymbols { + e.e.encodeSymbol(k2) + } else { + e.e.encodeString(c_UTF8, k2) + } + e.encode(v2) } - e.asis(v) } -func (e *Encoder) wrapErr(v interface{}, err *error) { - *err = encodeError{codecError{name: e.hh.Name(), err: v}} +func (e *Encoder) encMapInt64Intf(v map[int64]interface{}) { + e.e.encodeMapPreamble(len(v)) + for k2, v2 := range v { + e.e.encodeInt(k2) + e.encode(v2) + } } -func encStructFieldKey(encName string, ee encDriver, w *encWriterSwitch, - keyType valueType, encNameAsciiAlphaNum bool, js bool) { - var m must - // use if-else-if, not switch (which compiles to binary-search) - // since keyType is typically valueTypeString, branch prediction is pretty good. - if keyType == valueTypeString { - if js && encNameAsciiAlphaNum { // keyType == valueTypeString - // w.writen1('"') - // w.writestr(encName) - // w.writen1('"') - // ---- - // w.writestr(`"` + encName + `"`) - // ---- - // do concat myself, so it is faster than the generic string concat - b := make([]byte, len(encName)+2) - copy(b[1:], encName) - b[0] = '"' - b[len(b)-1] = '"' - w.writeb(b) - } else { // keyType == valueTypeString - ee.EncodeStringEnc(cUTF8, encName) - } - } else if keyType == valueTypeInt { - ee.EncodeInt(m.Int(strconv.ParseInt(encName, 10, 64))) - } else if keyType == valueTypeUint { - ee.EncodeUint(m.Uint(strconv.ParseUint(encName, 10, 64))) - } else if keyType == valueTypeFloat { - ee.EncodeFloat64(m.Float(strconv.ParseFloat(encName, 64))) +func (e *Encoder) encMapUint64Intf(v map[uint64]interface{}) { + e.e.encodeMapPreamble(len(v)) + for k2, v2 := range v { + e.e.encodeUint(uint64(k2)) + e.encode(v2) } } -// func encStringAsRawBytesMaybe(ee encDriver, s string, stringToRaw bool) { -// if stringToRaw { -// ee.EncodeStringBytesRaw(bytesView(s)) -// } else { -// ee.EncodeStringEnc(cUTF8, s) -// } -// } +func (e *Encoder) encMapIntfIntf(v map[interface{}]interface{}) { + e.e.encodeMapPreamble(len(v)) + for k2, v2 := range v { + e.encode(k2) + e.encode(v2) + } +} + +// ---------------------------------------- + +func encErr(format string, params ...interface{}) { + doPanic(msgTagEnc, format, params...) +} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.generated.go b/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.generated.go deleted file mode 100644 index 9bc14bd638a39..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.generated.go +++ /dev/null @@ -1,33668 +0,0 @@ -// +build !notfastpath - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from fast-path.go.tmpl - DO NOT EDIT. - -package codec - -// Fast path functions try to create a fast path encode or decode implementation -// for common maps and slices. -// -// We define the functions and register then in this single file -// so as not to pollute the encode.go and decode.go, and create a dependency in there. -// This file can be omitted without causing a build failure. -// -// The advantage of fast paths is: -// - Many calls bypass reflection altogether -// -// Currently support -// - slice of all builtin types, -// - map of all builtin types to string or interface value -// - symmetrical maps of all builtin types (e.g. str-str, uint8-uint8) -// This should provide adequate "typical" implementations. -// -// Note that fast track decode functions must handle values for which an address cannot be obtained. -// For example: -// m2 := map[string]int{} -// p2 := []interface{}{m2} -// // decoding into p2 will bomb if fast track functions do not treat like unaddressable. -// - -import ( - "reflect" - "sort" -) - -const fastpathEnabled = true - -const fastpathMapBySliceErrMsg = "mapBySlice requires even slice length, but got %v" - -type fastpathT struct{} - -var fastpathTV fastpathT - -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} - -type fastpathA [271]fastpathE - -func (x *fastpathA) index(rtid uintptr) int { - // use binary search to grab the index (adapted from sort/search.go) - // Note: we use goto (instead of for loop) so this can be inlined. - // h, i, j := 0, 0, len(x) - var h, i uint - var j = uint(len(x)) -LOOP: - if i < j { - h = i + (j-i)/2 - if x[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - goto LOOP - } - if i < uint(len(x)) && x[i].rtid == rtid { - return int(i) - } - return -1 -} - -type fastpathAslice []fastpathE - -func (x fastpathAslice) Len() int { return len(x) } -func (x fastpathAslice) Less(i, j int) bool { return x[uint(i)].rtid < x[uint(j)].rtid } -func (x fastpathAslice) Swap(i, j int) { x[uint(i)], x[uint(j)] = x[uint(j)], x[uint(i)] } - -var fastpathAV fastpathA - -// due to possible initialization loop error, make fastpath in an init() -func init() { - var i uint = 0 - fn := func(v interface{}, - fe func(*Encoder, *codecFnInfo, reflect.Value), - fd func(*Decoder, *codecFnInfo, reflect.Value)) { - xrt := reflect.TypeOf(v) - xptr := rt2id(xrt) - fastpathAV[i] = fastpathE{xptr, xrt, fe, fd} - i++ - } - - fn([]interface{}(nil), (*Encoder).fastpathEncSliceIntfR, (*Decoder).fastpathDecSliceIntfR) - fn([]string(nil), (*Encoder).fastpathEncSliceStringR, (*Decoder).fastpathDecSliceStringR) - fn([]float32(nil), (*Encoder).fastpathEncSliceFloat32R, (*Decoder).fastpathDecSliceFloat32R) - fn([]float64(nil), (*Encoder).fastpathEncSliceFloat64R, (*Decoder).fastpathDecSliceFloat64R) - fn([]uint(nil), (*Encoder).fastpathEncSliceUintR, (*Decoder).fastpathDecSliceUintR) - fn([]uint16(nil), (*Encoder).fastpathEncSliceUint16R, (*Decoder).fastpathDecSliceUint16R) - fn([]uint32(nil), (*Encoder).fastpathEncSliceUint32R, (*Decoder).fastpathDecSliceUint32R) - fn([]uint64(nil), (*Encoder).fastpathEncSliceUint64R, (*Decoder).fastpathDecSliceUint64R) - fn([]uintptr(nil), (*Encoder).fastpathEncSliceUintptrR, (*Decoder).fastpathDecSliceUintptrR) - fn([]int(nil), (*Encoder).fastpathEncSliceIntR, (*Decoder).fastpathDecSliceIntR) - fn([]int8(nil), (*Encoder).fastpathEncSliceInt8R, (*Decoder).fastpathDecSliceInt8R) - fn([]int16(nil), (*Encoder).fastpathEncSliceInt16R, (*Decoder).fastpathDecSliceInt16R) - fn([]int32(nil), (*Encoder).fastpathEncSliceInt32R, (*Decoder).fastpathDecSliceInt32R) - fn([]int64(nil), (*Encoder).fastpathEncSliceInt64R, (*Decoder).fastpathDecSliceInt64R) - fn([]bool(nil), (*Encoder).fastpathEncSliceBoolR, (*Decoder).fastpathDecSliceBoolR) - - fn(map[interface{}]interface{}(nil), (*Encoder).fastpathEncMapIntfIntfR, (*Decoder).fastpathDecMapIntfIntfR) - fn(map[interface{}]string(nil), (*Encoder).fastpathEncMapIntfStringR, (*Decoder).fastpathDecMapIntfStringR) - fn(map[interface{}]uint(nil), (*Encoder).fastpathEncMapIntfUintR, (*Decoder).fastpathDecMapIntfUintR) - fn(map[interface{}]uint8(nil), (*Encoder).fastpathEncMapIntfUint8R, (*Decoder).fastpathDecMapIntfUint8R) - fn(map[interface{}]uint16(nil), (*Encoder).fastpathEncMapIntfUint16R, (*Decoder).fastpathDecMapIntfUint16R) - fn(map[interface{}]uint32(nil), (*Encoder).fastpathEncMapIntfUint32R, (*Decoder).fastpathDecMapIntfUint32R) - fn(map[interface{}]uint64(nil), (*Encoder).fastpathEncMapIntfUint64R, (*Decoder).fastpathDecMapIntfUint64R) - fn(map[interface{}]uintptr(nil), (*Encoder).fastpathEncMapIntfUintptrR, (*Decoder).fastpathDecMapIntfUintptrR) - fn(map[interface{}]int(nil), (*Encoder).fastpathEncMapIntfIntR, (*Decoder).fastpathDecMapIntfIntR) - fn(map[interface{}]int8(nil), (*Encoder).fastpathEncMapIntfInt8R, (*Decoder).fastpathDecMapIntfInt8R) - fn(map[interface{}]int16(nil), (*Encoder).fastpathEncMapIntfInt16R, (*Decoder).fastpathDecMapIntfInt16R) - fn(map[interface{}]int32(nil), (*Encoder).fastpathEncMapIntfInt32R, (*Decoder).fastpathDecMapIntfInt32R) - fn(map[interface{}]int64(nil), (*Encoder).fastpathEncMapIntfInt64R, (*Decoder).fastpathDecMapIntfInt64R) - fn(map[interface{}]float32(nil), (*Encoder).fastpathEncMapIntfFloat32R, (*Decoder).fastpathDecMapIntfFloat32R) - fn(map[interface{}]float64(nil), (*Encoder).fastpathEncMapIntfFloat64R, (*Decoder).fastpathDecMapIntfFloat64R) - fn(map[interface{}]bool(nil), (*Encoder).fastpathEncMapIntfBoolR, (*Decoder).fastpathDecMapIntfBoolR) - fn(map[string]interface{}(nil), (*Encoder).fastpathEncMapStringIntfR, (*Decoder).fastpathDecMapStringIntfR) - fn(map[string]string(nil), (*Encoder).fastpathEncMapStringStringR, (*Decoder).fastpathDecMapStringStringR) - fn(map[string]uint(nil), (*Encoder).fastpathEncMapStringUintR, (*Decoder).fastpathDecMapStringUintR) - fn(map[string]uint8(nil), (*Encoder).fastpathEncMapStringUint8R, (*Decoder).fastpathDecMapStringUint8R) - fn(map[string]uint16(nil), (*Encoder).fastpathEncMapStringUint16R, (*Decoder).fastpathDecMapStringUint16R) - fn(map[string]uint32(nil), (*Encoder).fastpathEncMapStringUint32R, (*Decoder).fastpathDecMapStringUint32R) - fn(map[string]uint64(nil), (*Encoder).fastpathEncMapStringUint64R, (*Decoder).fastpathDecMapStringUint64R) - fn(map[string]uintptr(nil), (*Encoder).fastpathEncMapStringUintptrR, (*Decoder).fastpathDecMapStringUintptrR) - fn(map[string]int(nil), (*Encoder).fastpathEncMapStringIntR, (*Decoder).fastpathDecMapStringIntR) - fn(map[string]int8(nil), (*Encoder).fastpathEncMapStringInt8R, (*Decoder).fastpathDecMapStringInt8R) - fn(map[string]int16(nil), (*Encoder).fastpathEncMapStringInt16R, (*Decoder).fastpathDecMapStringInt16R) - fn(map[string]int32(nil), (*Encoder).fastpathEncMapStringInt32R, (*Decoder).fastpathDecMapStringInt32R) - fn(map[string]int64(nil), (*Encoder).fastpathEncMapStringInt64R, (*Decoder).fastpathDecMapStringInt64R) - fn(map[string]float32(nil), (*Encoder).fastpathEncMapStringFloat32R, (*Decoder).fastpathDecMapStringFloat32R) - fn(map[string]float64(nil), (*Encoder).fastpathEncMapStringFloat64R, (*Decoder).fastpathDecMapStringFloat64R) - fn(map[string]bool(nil), (*Encoder).fastpathEncMapStringBoolR, (*Decoder).fastpathDecMapStringBoolR) - fn(map[float32]interface{}(nil), (*Encoder).fastpathEncMapFloat32IntfR, (*Decoder).fastpathDecMapFloat32IntfR) - fn(map[float32]string(nil), (*Encoder).fastpathEncMapFloat32StringR, (*Decoder).fastpathDecMapFloat32StringR) - fn(map[float32]uint(nil), (*Encoder).fastpathEncMapFloat32UintR, (*Decoder).fastpathDecMapFloat32UintR) - fn(map[float32]uint8(nil), (*Encoder).fastpathEncMapFloat32Uint8R, (*Decoder).fastpathDecMapFloat32Uint8R) - fn(map[float32]uint16(nil), (*Encoder).fastpathEncMapFloat32Uint16R, (*Decoder).fastpathDecMapFloat32Uint16R) - fn(map[float32]uint32(nil), (*Encoder).fastpathEncMapFloat32Uint32R, (*Decoder).fastpathDecMapFloat32Uint32R) - fn(map[float32]uint64(nil), (*Encoder).fastpathEncMapFloat32Uint64R, (*Decoder).fastpathDecMapFloat32Uint64R) - fn(map[float32]uintptr(nil), (*Encoder).fastpathEncMapFloat32UintptrR, (*Decoder).fastpathDecMapFloat32UintptrR) - fn(map[float32]int(nil), (*Encoder).fastpathEncMapFloat32IntR, (*Decoder).fastpathDecMapFloat32IntR) - fn(map[float32]int8(nil), (*Encoder).fastpathEncMapFloat32Int8R, (*Decoder).fastpathDecMapFloat32Int8R) - fn(map[float32]int16(nil), (*Encoder).fastpathEncMapFloat32Int16R, (*Decoder).fastpathDecMapFloat32Int16R) - fn(map[float32]int32(nil), (*Encoder).fastpathEncMapFloat32Int32R, (*Decoder).fastpathDecMapFloat32Int32R) - fn(map[float32]int64(nil), (*Encoder).fastpathEncMapFloat32Int64R, (*Decoder).fastpathDecMapFloat32Int64R) - fn(map[float32]float32(nil), (*Encoder).fastpathEncMapFloat32Float32R, (*Decoder).fastpathDecMapFloat32Float32R) - fn(map[float32]float64(nil), (*Encoder).fastpathEncMapFloat32Float64R, (*Decoder).fastpathDecMapFloat32Float64R) - fn(map[float32]bool(nil), (*Encoder).fastpathEncMapFloat32BoolR, (*Decoder).fastpathDecMapFloat32BoolR) - fn(map[float64]interface{}(nil), (*Encoder).fastpathEncMapFloat64IntfR, (*Decoder).fastpathDecMapFloat64IntfR) - fn(map[float64]string(nil), (*Encoder).fastpathEncMapFloat64StringR, (*Decoder).fastpathDecMapFloat64StringR) - fn(map[float64]uint(nil), (*Encoder).fastpathEncMapFloat64UintR, (*Decoder).fastpathDecMapFloat64UintR) - fn(map[float64]uint8(nil), (*Encoder).fastpathEncMapFloat64Uint8R, (*Decoder).fastpathDecMapFloat64Uint8R) - fn(map[float64]uint16(nil), (*Encoder).fastpathEncMapFloat64Uint16R, (*Decoder).fastpathDecMapFloat64Uint16R) - fn(map[float64]uint32(nil), (*Encoder).fastpathEncMapFloat64Uint32R, (*Decoder).fastpathDecMapFloat64Uint32R) - fn(map[float64]uint64(nil), (*Encoder).fastpathEncMapFloat64Uint64R, (*Decoder).fastpathDecMapFloat64Uint64R) - fn(map[float64]uintptr(nil), (*Encoder).fastpathEncMapFloat64UintptrR, (*Decoder).fastpathDecMapFloat64UintptrR) - fn(map[float64]int(nil), (*Encoder).fastpathEncMapFloat64IntR, (*Decoder).fastpathDecMapFloat64IntR) - fn(map[float64]int8(nil), (*Encoder).fastpathEncMapFloat64Int8R, (*Decoder).fastpathDecMapFloat64Int8R) - fn(map[float64]int16(nil), (*Encoder).fastpathEncMapFloat64Int16R, (*Decoder).fastpathDecMapFloat64Int16R) - fn(map[float64]int32(nil), (*Encoder).fastpathEncMapFloat64Int32R, (*Decoder).fastpathDecMapFloat64Int32R) - fn(map[float64]int64(nil), (*Encoder).fastpathEncMapFloat64Int64R, (*Decoder).fastpathDecMapFloat64Int64R) - fn(map[float64]float32(nil), (*Encoder).fastpathEncMapFloat64Float32R, (*Decoder).fastpathDecMapFloat64Float32R) - fn(map[float64]float64(nil), (*Encoder).fastpathEncMapFloat64Float64R, (*Decoder).fastpathDecMapFloat64Float64R) - fn(map[float64]bool(nil), (*Encoder).fastpathEncMapFloat64BoolR, (*Decoder).fastpathDecMapFloat64BoolR) - fn(map[uint]interface{}(nil), (*Encoder).fastpathEncMapUintIntfR, (*Decoder).fastpathDecMapUintIntfR) - fn(map[uint]string(nil), (*Encoder).fastpathEncMapUintStringR, (*Decoder).fastpathDecMapUintStringR) - fn(map[uint]uint(nil), (*Encoder).fastpathEncMapUintUintR, (*Decoder).fastpathDecMapUintUintR) - fn(map[uint]uint8(nil), (*Encoder).fastpathEncMapUintUint8R, (*Decoder).fastpathDecMapUintUint8R) - fn(map[uint]uint16(nil), (*Encoder).fastpathEncMapUintUint16R, (*Decoder).fastpathDecMapUintUint16R) - fn(map[uint]uint32(nil), (*Encoder).fastpathEncMapUintUint32R, (*Decoder).fastpathDecMapUintUint32R) - fn(map[uint]uint64(nil), (*Encoder).fastpathEncMapUintUint64R, (*Decoder).fastpathDecMapUintUint64R) - fn(map[uint]uintptr(nil), (*Encoder).fastpathEncMapUintUintptrR, (*Decoder).fastpathDecMapUintUintptrR) - fn(map[uint]int(nil), (*Encoder).fastpathEncMapUintIntR, (*Decoder).fastpathDecMapUintIntR) - fn(map[uint]int8(nil), (*Encoder).fastpathEncMapUintInt8R, (*Decoder).fastpathDecMapUintInt8R) - fn(map[uint]int16(nil), (*Encoder).fastpathEncMapUintInt16R, (*Decoder).fastpathDecMapUintInt16R) - fn(map[uint]int32(nil), (*Encoder).fastpathEncMapUintInt32R, (*Decoder).fastpathDecMapUintInt32R) - fn(map[uint]int64(nil), (*Encoder).fastpathEncMapUintInt64R, (*Decoder).fastpathDecMapUintInt64R) - fn(map[uint]float32(nil), (*Encoder).fastpathEncMapUintFloat32R, (*Decoder).fastpathDecMapUintFloat32R) - fn(map[uint]float64(nil), (*Encoder).fastpathEncMapUintFloat64R, (*Decoder).fastpathDecMapUintFloat64R) - fn(map[uint]bool(nil), (*Encoder).fastpathEncMapUintBoolR, (*Decoder).fastpathDecMapUintBoolR) - fn(map[uint8]interface{}(nil), (*Encoder).fastpathEncMapUint8IntfR, (*Decoder).fastpathDecMapUint8IntfR) - fn(map[uint8]string(nil), (*Encoder).fastpathEncMapUint8StringR, (*Decoder).fastpathDecMapUint8StringR) - fn(map[uint8]uint(nil), (*Encoder).fastpathEncMapUint8UintR, (*Decoder).fastpathDecMapUint8UintR) - fn(map[uint8]uint8(nil), (*Encoder).fastpathEncMapUint8Uint8R, (*Decoder).fastpathDecMapUint8Uint8R) - fn(map[uint8]uint16(nil), (*Encoder).fastpathEncMapUint8Uint16R, (*Decoder).fastpathDecMapUint8Uint16R) - fn(map[uint8]uint32(nil), (*Encoder).fastpathEncMapUint8Uint32R, (*Decoder).fastpathDecMapUint8Uint32R) - fn(map[uint8]uint64(nil), (*Encoder).fastpathEncMapUint8Uint64R, (*Decoder).fastpathDecMapUint8Uint64R) - fn(map[uint8]uintptr(nil), (*Encoder).fastpathEncMapUint8UintptrR, (*Decoder).fastpathDecMapUint8UintptrR) - fn(map[uint8]int(nil), (*Encoder).fastpathEncMapUint8IntR, (*Decoder).fastpathDecMapUint8IntR) - fn(map[uint8]int8(nil), (*Encoder).fastpathEncMapUint8Int8R, (*Decoder).fastpathDecMapUint8Int8R) - fn(map[uint8]int16(nil), (*Encoder).fastpathEncMapUint8Int16R, (*Decoder).fastpathDecMapUint8Int16R) - fn(map[uint8]int32(nil), (*Encoder).fastpathEncMapUint8Int32R, (*Decoder).fastpathDecMapUint8Int32R) - fn(map[uint8]int64(nil), (*Encoder).fastpathEncMapUint8Int64R, (*Decoder).fastpathDecMapUint8Int64R) - fn(map[uint8]float32(nil), (*Encoder).fastpathEncMapUint8Float32R, (*Decoder).fastpathDecMapUint8Float32R) - fn(map[uint8]float64(nil), (*Encoder).fastpathEncMapUint8Float64R, (*Decoder).fastpathDecMapUint8Float64R) - fn(map[uint8]bool(nil), (*Encoder).fastpathEncMapUint8BoolR, (*Decoder).fastpathDecMapUint8BoolR) - fn(map[uint16]interface{}(nil), (*Encoder).fastpathEncMapUint16IntfR, (*Decoder).fastpathDecMapUint16IntfR) - fn(map[uint16]string(nil), (*Encoder).fastpathEncMapUint16StringR, (*Decoder).fastpathDecMapUint16StringR) - fn(map[uint16]uint(nil), (*Encoder).fastpathEncMapUint16UintR, (*Decoder).fastpathDecMapUint16UintR) - fn(map[uint16]uint8(nil), (*Encoder).fastpathEncMapUint16Uint8R, (*Decoder).fastpathDecMapUint16Uint8R) - fn(map[uint16]uint16(nil), (*Encoder).fastpathEncMapUint16Uint16R, (*Decoder).fastpathDecMapUint16Uint16R) - fn(map[uint16]uint32(nil), (*Encoder).fastpathEncMapUint16Uint32R, (*Decoder).fastpathDecMapUint16Uint32R) - fn(map[uint16]uint64(nil), (*Encoder).fastpathEncMapUint16Uint64R, (*Decoder).fastpathDecMapUint16Uint64R) - fn(map[uint16]uintptr(nil), (*Encoder).fastpathEncMapUint16UintptrR, (*Decoder).fastpathDecMapUint16UintptrR) - fn(map[uint16]int(nil), (*Encoder).fastpathEncMapUint16IntR, (*Decoder).fastpathDecMapUint16IntR) - fn(map[uint16]int8(nil), (*Encoder).fastpathEncMapUint16Int8R, (*Decoder).fastpathDecMapUint16Int8R) - fn(map[uint16]int16(nil), (*Encoder).fastpathEncMapUint16Int16R, (*Decoder).fastpathDecMapUint16Int16R) - fn(map[uint16]int32(nil), (*Encoder).fastpathEncMapUint16Int32R, (*Decoder).fastpathDecMapUint16Int32R) - fn(map[uint16]int64(nil), (*Encoder).fastpathEncMapUint16Int64R, (*Decoder).fastpathDecMapUint16Int64R) - fn(map[uint16]float32(nil), (*Encoder).fastpathEncMapUint16Float32R, (*Decoder).fastpathDecMapUint16Float32R) - fn(map[uint16]float64(nil), (*Encoder).fastpathEncMapUint16Float64R, (*Decoder).fastpathDecMapUint16Float64R) - fn(map[uint16]bool(nil), (*Encoder).fastpathEncMapUint16BoolR, (*Decoder).fastpathDecMapUint16BoolR) - fn(map[uint32]interface{}(nil), (*Encoder).fastpathEncMapUint32IntfR, (*Decoder).fastpathDecMapUint32IntfR) - fn(map[uint32]string(nil), (*Encoder).fastpathEncMapUint32StringR, (*Decoder).fastpathDecMapUint32StringR) - fn(map[uint32]uint(nil), (*Encoder).fastpathEncMapUint32UintR, (*Decoder).fastpathDecMapUint32UintR) - fn(map[uint32]uint8(nil), (*Encoder).fastpathEncMapUint32Uint8R, (*Decoder).fastpathDecMapUint32Uint8R) - fn(map[uint32]uint16(nil), (*Encoder).fastpathEncMapUint32Uint16R, (*Decoder).fastpathDecMapUint32Uint16R) - fn(map[uint32]uint32(nil), (*Encoder).fastpathEncMapUint32Uint32R, (*Decoder).fastpathDecMapUint32Uint32R) - fn(map[uint32]uint64(nil), (*Encoder).fastpathEncMapUint32Uint64R, (*Decoder).fastpathDecMapUint32Uint64R) - fn(map[uint32]uintptr(nil), (*Encoder).fastpathEncMapUint32UintptrR, (*Decoder).fastpathDecMapUint32UintptrR) - fn(map[uint32]int(nil), (*Encoder).fastpathEncMapUint32IntR, (*Decoder).fastpathDecMapUint32IntR) - fn(map[uint32]int8(nil), (*Encoder).fastpathEncMapUint32Int8R, (*Decoder).fastpathDecMapUint32Int8R) - fn(map[uint32]int16(nil), (*Encoder).fastpathEncMapUint32Int16R, (*Decoder).fastpathDecMapUint32Int16R) - fn(map[uint32]int32(nil), (*Encoder).fastpathEncMapUint32Int32R, (*Decoder).fastpathDecMapUint32Int32R) - fn(map[uint32]int64(nil), (*Encoder).fastpathEncMapUint32Int64R, (*Decoder).fastpathDecMapUint32Int64R) - fn(map[uint32]float32(nil), (*Encoder).fastpathEncMapUint32Float32R, (*Decoder).fastpathDecMapUint32Float32R) - fn(map[uint32]float64(nil), (*Encoder).fastpathEncMapUint32Float64R, (*Decoder).fastpathDecMapUint32Float64R) - fn(map[uint32]bool(nil), (*Encoder).fastpathEncMapUint32BoolR, (*Decoder).fastpathDecMapUint32BoolR) - fn(map[uint64]interface{}(nil), (*Encoder).fastpathEncMapUint64IntfR, (*Decoder).fastpathDecMapUint64IntfR) - fn(map[uint64]string(nil), (*Encoder).fastpathEncMapUint64StringR, (*Decoder).fastpathDecMapUint64StringR) - fn(map[uint64]uint(nil), (*Encoder).fastpathEncMapUint64UintR, (*Decoder).fastpathDecMapUint64UintR) - fn(map[uint64]uint8(nil), (*Encoder).fastpathEncMapUint64Uint8R, (*Decoder).fastpathDecMapUint64Uint8R) - fn(map[uint64]uint16(nil), (*Encoder).fastpathEncMapUint64Uint16R, (*Decoder).fastpathDecMapUint64Uint16R) - fn(map[uint64]uint32(nil), (*Encoder).fastpathEncMapUint64Uint32R, (*Decoder).fastpathDecMapUint64Uint32R) - fn(map[uint64]uint64(nil), (*Encoder).fastpathEncMapUint64Uint64R, (*Decoder).fastpathDecMapUint64Uint64R) - fn(map[uint64]uintptr(nil), (*Encoder).fastpathEncMapUint64UintptrR, (*Decoder).fastpathDecMapUint64UintptrR) - fn(map[uint64]int(nil), (*Encoder).fastpathEncMapUint64IntR, (*Decoder).fastpathDecMapUint64IntR) - fn(map[uint64]int8(nil), (*Encoder).fastpathEncMapUint64Int8R, (*Decoder).fastpathDecMapUint64Int8R) - fn(map[uint64]int16(nil), (*Encoder).fastpathEncMapUint64Int16R, (*Decoder).fastpathDecMapUint64Int16R) - fn(map[uint64]int32(nil), (*Encoder).fastpathEncMapUint64Int32R, (*Decoder).fastpathDecMapUint64Int32R) - fn(map[uint64]int64(nil), (*Encoder).fastpathEncMapUint64Int64R, (*Decoder).fastpathDecMapUint64Int64R) - fn(map[uint64]float32(nil), (*Encoder).fastpathEncMapUint64Float32R, (*Decoder).fastpathDecMapUint64Float32R) - fn(map[uint64]float64(nil), (*Encoder).fastpathEncMapUint64Float64R, (*Decoder).fastpathDecMapUint64Float64R) - fn(map[uint64]bool(nil), (*Encoder).fastpathEncMapUint64BoolR, (*Decoder).fastpathDecMapUint64BoolR) - fn(map[uintptr]interface{}(nil), (*Encoder).fastpathEncMapUintptrIntfR, (*Decoder).fastpathDecMapUintptrIntfR) - fn(map[uintptr]string(nil), (*Encoder).fastpathEncMapUintptrStringR, (*Decoder).fastpathDecMapUintptrStringR) - fn(map[uintptr]uint(nil), (*Encoder).fastpathEncMapUintptrUintR, (*Decoder).fastpathDecMapUintptrUintR) - fn(map[uintptr]uint8(nil), (*Encoder).fastpathEncMapUintptrUint8R, (*Decoder).fastpathDecMapUintptrUint8R) - fn(map[uintptr]uint16(nil), (*Encoder).fastpathEncMapUintptrUint16R, (*Decoder).fastpathDecMapUintptrUint16R) - fn(map[uintptr]uint32(nil), (*Encoder).fastpathEncMapUintptrUint32R, (*Decoder).fastpathDecMapUintptrUint32R) - fn(map[uintptr]uint64(nil), (*Encoder).fastpathEncMapUintptrUint64R, (*Decoder).fastpathDecMapUintptrUint64R) - fn(map[uintptr]uintptr(nil), (*Encoder).fastpathEncMapUintptrUintptrR, (*Decoder).fastpathDecMapUintptrUintptrR) - fn(map[uintptr]int(nil), (*Encoder).fastpathEncMapUintptrIntR, (*Decoder).fastpathDecMapUintptrIntR) - fn(map[uintptr]int8(nil), (*Encoder).fastpathEncMapUintptrInt8R, (*Decoder).fastpathDecMapUintptrInt8R) - fn(map[uintptr]int16(nil), (*Encoder).fastpathEncMapUintptrInt16R, (*Decoder).fastpathDecMapUintptrInt16R) - fn(map[uintptr]int32(nil), (*Encoder).fastpathEncMapUintptrInt32R, (*Decoder).fastpathDecMapUintptrInt32R) - fn(map[uintptr]int64(nil), (*Encoder).fastpathEncMapUintptrInt64R, (*Decoder).fastpathDecMapUintptrInt64R) - fn(map[uintptr]float32(nil), (*Encoder).fastpathEncMapUintptrFloat32R, (*Decoder).fastpathDecMapUintptrFloat32R) - fn(map[uintptr]float64(nil), (*Encoder).fastpathEncMapUintptrFloat64R, (*Decoder).fastpathDecMapUintptrFloat64R) - fn(map[uintptr]bool(nil), (*Encoder).fastpathEncMapUintptrBoolR, (*Decoder).fastpathDecMapUintptrBoolR) - fn(map[int]interface{}(nil), (*Encoder).fastpathEncMapIntIntfR, (*Decoder).fastpathDecMapIntIntfR) - fn(map[int]string(nil), (*Encoder).fastpathEncMapIntStringR, (*Decoder).fastpathDecMapIntStringR) - fn(map[int]uint(nil), (*Encoder).fastpathEncMapIntUintR, (*Decoder).fastpathDecMapIntUintR) - fn(map[int]uint8(nil), (*Encoder).fastpathEncMapIntUint8R, (*Decoder).fastpathDecMapIntUint8R) - fn(map[int]uint16(nil), (*Encoder).fastpathEncMapIntUint16R, (*Decoder).fastpathDecMapIntUint16R) - fn(map[int]uint32(nil), (*Encoder).fastpathEncMapIntUint32R, (*Decoder).fastpathDecMapIntUint32R) - fn(map[int]uint64(nil), (*Encoder).fastpathEncMapIntUint64R, (*Decoder).fastpathDecMapIntUint64R) - fn(map[int]uintptr(nil), (*Encoder).fastpathEncMapIntUintptrR, (*Decoder).fastpathDecMapIntUintptrR) - fn(map[int]int(nil), (*Encoder).fastpathEncMapIntIntR, (*Decoder).fastpathDecMapIntIntR) - fn(map[int]int8(nil), (*Encoder).fastpathEncMapIntInt8R, (*Decoder).fastpathDecMapIntInt8R) - fn(map[int]int16(nil), (*Encoder).fastpathEncMapIntInt16R, (*Decoder).fastpathDecMapIntInt16R) - fn(map[int]int32(nil), (*Encoder).fastpathEncMapIntInt32R, (*Decoder).fastpathDecMapIntInt32R) - fn(map[int]int64(nil), (*Encoder).fastpathEncMapIntInt64R, (*Decoder).fastpathDecMapIntInt64R) - fn(map[int]float32(nil), (*Encoder).fastpathEncMapIntFloat32R, (*Decoder).fastpathDecMapIntFloat32R) - fn(map[int]float64(nil), (*Encoder).fastpathEncMapIntFloat64R, (*Decoder).fastpathDecMapIntFloat64R) - fn(map[int]bool(nil), (*Encoder).fastpathEncMapIntBoolR, (*Decoder).fastpathDecMapIntBoolR) - fn(map[int8]interface{}(nil), (*Encoder).fastpathEncMapInt8IntfR, (*Decoder).fastpathDecMapInt8IntfR) - fn(map[int8]string(nil), (*Encoder).fastpathEncMapInt8StringR, (*Decoder).fastpathDecMapInt8StringR) - fn(map[int8]uint(nil), (*Encoder).fastpathEncMapInt8UintR, (*Decoder).fastpathDecMapInt8UintR) - fn(map[int8]uint8(nil), (*Encoder).fastpathEncMapInt8Uint8R, (*Decoder).fastpathDecMapInt8Uint8R) - fn(map[int8]uint16(nil), (*Encoder).fastpathEncMapInt8Uint16R, (*Decoder).fastpathDecMapInt8Uint16R) - fn(map[int8]uint32(nil), (*Encoder).fastpathEncMapInt8Uint32R, (*Decoder).fastpathDecMapInt8Uint32R) - fn(map[int8]uint64(nil), (*Encoder).fastpathEncMapInt8Uint64R, (*Decoder).fastpathDecMapInt8Uint64R) - fn(map[int8]uintptr(nil), (*Encoder).fastpathEncMapInt8UintptrR, (*Decoder).fastpathDecMapInt8UintptrR) - fn(map[int8]int(nil), (*Encoder).fastpathEncMapInt8IntR, (*Decoder).fastpathDecMapInt8IntR) - fn(map[int8]int8(nil), (*Encoder).fastpathEncMapInt8Int8R, (*Decoder).fastpathDecMapInt8Int8R) - fn(map[int8]int16(nil), (*Encoder).fastpathEncMapInt8Int16R, (*Decoder).fastpathDecMapInt8Int16R) - fn(map[int8]int32(nil), (*Encoder).fastpathEncMapInt8Int32R, (*Decoder).fastpathDecMapInt8Int32R) - fn(map[int8]int64(nil), (*Encoder).fastpathEncMapInt8Int64R, (*Decoder).fastpathDecMapInt8Int64R) - fn(map[int8]float32(nil), (*Encoder).fastpathEncMapInt8Float32R, (*Decoder).fastpathDecMapInt8Float32R) - fn(map[int8]float64(nil), (*Encoder).fastpathEncMapInt8Float64R, (*Decoder).fastpathDecMapInt8Float64R) - fn(map[int8]bool(nil), (*Encoder).fastpathEncMapInt8BoolR, (*Decoder).fastpathDecMapInt8BoolR) - fn(map[int16]interface{}(nil), (*Encoder).fastpathEncMapInt16IntfR, (*Decoder).fastpathDecMapInt16IntfR) - fn(map[int16]string(nil), (*Encoder).fastpathEncMapInt16StringR, (*Decoder).fastpathDecMapInt16StringR) - fn(map[int16]uint(nil), (*Encoder).fastpathEncMapInt16UintR, (*Decoder).fastpathDecMapInt16UintR) - fn(map[int16]uint8(nil), (*Encoder).fastpathEncMapInt16Uint8R, (*Decoder).fastpathDecMapInt16Uint8R) - fn(map[int16]uint16(nil), (*Encoder).fastpathEncMapInt16Uint16R, (*Decoder).fastpathDecMapInt16Uint16R) - fn(map[int16]uint32(nil), (*Encoder).fastpathEncMapInt16Uint32R, (*Decoder).fastpathDecMapInt16Uint32R) - fn(map[int16]uint64(nil), (*Encoder).fastpathEncMapInt16Uint64R, (*Decoder).fastpathDecMapInt16Uint64R) - fn(map[int16]uintptr(nil), (*Encoder).fastpathEncMapInt16UintptrR, (*Decoder).fastpathDecMapInt16UintptrR) - fn(map[int16]int(nil), (*Encoder).fastpathEncMapInt16IntR, (*Decoder).fastpathDecMapInt16IntR) - fn(map[int16]int8(nil), (*Encoder).fastpathEncMapInt16Int8R, (*Decoder).fastpathDecMapInt16Int8R) - fn(map[int16]int16(nil), (*Encoder).fastpathEncMapInt16Int16R, (*Decoder).fastpathDecMapInt16Int16R) - fn(map[int16]int32(nil), (*Encoder).fastpathEncMapInt16Int32R, (*Decoder).fastpathDecMapInt16Int32R) - fn(map[int16]int64(nil), (*Encoder).fastpathEncMapInt16Int64R, (*Decoder).fastpathDecMapInt16Int64R) - fn(map[int16]float32(nil), (*Encoder).fastpathEncMapInt16Float32R, (*Decoder).fastpathDecMapInt16Float32R) - fn(map[int16]float64(nil), (*Encoder).fastpathEncMapInt16Float64R, (*Decoder).fastpathDecMapInt16Float64R) - fn(map[int16]bool(nil), (*Encoder).fastpathEncMapInt16BoolR, (*Decoder).fastpathDecMapInt16BoolR) - fn(map[int32]interface{}(nil), (*Encoder).fastpathEncMapInt32IntfR, (*Decoder).fastpathDecMapInt32IntfR) - fn(map[int32]string(nil), (*Encoder).fastpathEncMapInt32StringR, (*Decoder).fastpathDecMapInt32StringR) - fn(map[int32]uint(nil), (*Encoder).fastpathEncMapInt32UintR, (*Decoder).fastpathDecMapInt32UintR) - fn(map[int32]uint8(nil), (*Encoder).fastpathEncMapInt32Uint8R, (*Decoder).fastpathDecMapInt32Uint8R) - fn(map[int32]uint16(nil), (*Encoder).fastpathEncMapInt32Uint16R, (*Decoder).fastpathDecMapInt32Uint16R) - fn(map[int32]uint32(nil), (*Encoder).fastpathEncMapInt32Uint32R, (*Decoder).fastpathDecMapInt32Uint32R) - fn(map[int32]uint64(nil), (*Encoder).fastpathEncMapInt32Uint64R, (*Decoder).fastpathDecMapInt32Uint64R) - fn(map[int32]uintptr(nil), (*Encoder).fastpathEncMapInt32UintptrR, (*Decoder).fastpathDecMapInt32UintptrR) - fn(map[int32]int(nil), (*Encoder).fastpathEncMapInt32IntR, (*Decoder).fastpathDecMapInt32IntR) - fn(map[int32]int8(nil), (*Encoder).fastpathEncMapInt32Int8R, (*Decoder).fastpathDecMapInt32Int8R) - fn(map[int32]int16(nil), (*Encoder).fastpathEncMapInt32Int16R, (*Decoder).fastpathDecMapInt32Int16R) - fn(map[int32]int32(nil), (*Encoder).fastpathEncMapInt32Int32R, (*Decoder).fastpathDecMapInt32Int32R) - fn(map[int32]int64(nil), (*Encoder).fastpathEncMapInt32Int64R, (*Decoder).fastpathDecMapInt32Int64R) - fn(map[int32]float32(nil), (*Encoder).fastpathEncMapInt32Float32R, (*Decoder).fastpathDecMapInt32Float32R) - fn(map[int32]float64(nil), (*Encoder).fastpathEncMapInt32Float64R, (*Decoder).fastpathDecMapInt32Float64R) - fn(map[int32]bool(nil), (*Encoder).fastpathEncMapInt32BoolR, (*Decoder).fastpathDecMapInt32BoolR) - fn(map[int64]interface{}(nil), (*Encoder).fastpathEncMapInt64IntfR, (*Decoder).fastpathDecMapInt64IntfR) - fn(map[int64]string(nil), (*Encoder).fastpathEncMapInt64StringR, (*Decoder).fastpathDecMapInt64StringR) - fn(map[int64]uint(nil), (*Encoder).fastpathEncMapInt64UintR, (*Decoder).fastpathDecMapInt64UintR) - fn(map[int64]uint8(nil), (*Encoder).fastpathEncMapInt64Uint8R, (*Decoder).fastpathDecMapInt64Uint8R) - fn(map[int64]uint16(nil), (*Encoder).fastpathEncMapInt64Uint16R, (*Decoder).fastpathDecMapInt64Uint16R) - fn(map[int64]uint32(nil), (*Encoder).fastpathEncMapInt64Uint32R, (*Decoder).fastpathDecMapInt64Uint32R) - fn(map[int64]uint64(nil), (*Encoder).fastpathEncMapInt64Uint64R, (*Decoder).fastpathDecMapInt64Uint64R) - fn(map[int64]uintptr(nil), (*Encoder).fastpathEncMapInt64UintptrR, (*Decoder).fastpathDecMapInt64UintptrR) - fn(map[int64]int(nil), (*Encoder).fastpathEncMapInt64IntR, (*Decoder).fastpathDecMapInt64IntR) - fn(map[int64]int8(nil), (*Encoder).fastpathEncMapInt64Int8R, (*Decoder).fastpathDecMapInt64Int8R) - fn(map[int64]int16(nil), (*Encoder).fastpathEncMapInt64Int16R, (*Decoder).fastpathDecMapInt64Int16R) - fn(map[int64]int32(nil), (*Encoder).fastpathEncMapInt64Int32R, (*Decoder).fastpathDecMapInt64Int32R) - fn(map[int64]int64(nil), (*Encoder).fastpathEncMapInt64Int64R, (*Decoder).fastpathDecMapInt64Int64R) - fn(map[int64]float32(nil), (*Encoder).fastpathEncMapInt64Float32R, (*Decoder).fastpathDecMapInt64Float32R) - fn(map[int64]float64(nil), (*Encoder).fastpathEncMapInt64Float64R, (*Decoder).fastpathDecMapInt64Float64R) - fn(map[int64]bool(nil), (*Encoder).fastpathEncMapInt64BoolR, (*Decoder).fastpathDecMapInt64BoolR) - fn(map[bool]interface{}(nil), (*Encoder).fastpathEncMapBoolIntfR, (*Decoder).fastpathDecMapBoolIntfR) - fn(map[bool]string(nil), (*Encoder).fastpathEncMapBoolStringR, (*Decoder).fastpathDecMapBoolStringR) - fn(map[bool]uint(nil), (*Encoder).fastpathEncMapBoolUintR, (*Decoder).fastpathDecMapBoolUintR) - fn(map[bool]uint8(nil), (*Encoder).fastpathEncMapBoolUint8R, (*Decoder).fastpathDecMapBoolUint8R) - fn(map[bool]uint16(nil), (*Encoder).fastpathEncMapBoolUint16R, (*Decoder).fastpathDecMapBoolUint16R) - fn(map[bool]uint32(nil), (*Encoder).fastpathEncMapBoolUint32R, (*Decoder).fastpathDecMapBoolUint32R) - fn(map[bool]uint64(nil), (*Encoder).fastpathEncMapBoolUint64R, (*Decoder).fastpathDecMapBoolUint64R) - fn(map[bool]uintptr(nil), (*Encoder).fastpathEncMapBoolUintptrR, (*Decoder).fastpathDecMapBoolUintptrR) - fn(map[bool]int(nil), (*Encoder).fastpathEncMapBoolIntR, (*Decoder).fastpathDecMapBoolIntR) - fn(map[bool]int8(nil), (*Encoder).fastpathEncMapBoolInt8R, (*Decoder).fastpathDecMapBoolInt8R) - fn(map[bool]int16(nil), (*Encoder).fastpathEncMapBoolInt16R, (*Decoder).fastpathDecMapBoolInt16R) - fn(map[bool]int32(nil), (*Encoder).fastpathEncMapBoolInt32R, (*Decoder).fastpathDecMapBoolInt32R) - fn(map[bool]int64(nil), (*Encoder).fastpathEncMapBoolInt64R, (*Decoder).fastpathDecMapBoolInt64R) - fn(map[bool]float32(nil), (*Encoder).fastpathEncMapBoolFloat32R, (*Decoder).fastpathDecMapBoolFloat32R) - fn(map[bool]float64(nil), (*Encoder).fastpathEncMapBoolFloat64R, (*Decoder).fastpathDecMapBoolFloat64R) - fn(map[bool]bool(nil), (*Encoder).fastpathEncMapBoolBoolR, (*Decoder).fastpathDecMapBoolBoolR) - - sort.Sort(fastpathAslice(fastpathAV[:])) -} - -// -- encode - -// -- -- fast path type switch -func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { - switch v := iv.(type) { - - case []interface{}: - fastpathTV.EncSliceIntfV(v, e) - case *[]interface{}: - fastpathTV.EncSliceIntfV(*v, e) - case []string: - fastpathTV.EncSliceStringV(v, e) - case *[]string: - fastpathTV.EncSliceStringV(*v, e) - case []float32: - fastpathTV.EncSliceFloat32V(v, e) - case *[]float32: - fastpathTV.EncSliceFloat32V(*v, e) - case []float64: - fastpathTV.EncSliceFloat64V(v, e) - case *[]float64: - fastpathTV.EncSliceFloat64V(*v, e) - case []uint: - fastpathTV.EncSliceUintV(v, e) - case *[]uint: - fastpathTV.EncSliceUintV(*v, e) - case []uint16: - fastpathTV.EncSliceUint16V(v, e) - case *[]uint16: - fastpathTV.EncSliceUint16V(*v, e) - case []uint32: - fastpathTV.EncSliceUint32V(v, e) - case *[]uint32: - fastpathTV.EncSliceUint32V(*v, e) - case []uint64: - fastpathTV.EncSliceUint64V(v, e) - case *[]uint64: - fastpathTV.EncSliceUint64V(*v, e) - case []uintptr: - fastpathTV.EncSliceUintptrV(v, e) - case *[]uintptr: - fastpathTV.EncSliceUintptrV(*v, e) - case []int: - fastpathTV.EncSliceIntV(v, e) - case *[]int: - fastpathTV.EncSliceIntV(*v, e) - case []int8: - fastpathTV.EncSliceInt8V(v, e) - case *[]int8: - fastpathTV.EncSliceInt8V(*v, e) - case []int16: - fastpathTV.EncSliceInt16V(v, e) - case *[]int16: - fastpathTV.EncSliceInt16V(*v, e) - case []int32: - fastpathTV.EncSliceInt32V(v, e) - case *[]int32: - fastpathTV.EncSliceInt32V(*v, e) - case []int64: - fastpathTV.EncSliceInt64V(v, e) - case *[]int64: - fastpathTV.EncSliceInt64V(*v, e) - case []bool: - fastpathTV.EncSliceBoolV(v, e) - case *[]bool: - fastpathTV.EncSliceBoolV(*v, e) - - case map[interface{}]interface{}: - fastpathTV.EncMapIntfIntfV(v, e) - case *map[interface{}]interface{}: - fastpathTV.EncMapIntfIntfV(*v, e) - case map[interface{}]string: - fastpathTV.EncMapIntfStringV(v, e) - case *map[interface{}]string: - fastpathTV.EncMapIntfStringV(*v, e) - case map[interface{}]uint: - fastpathTV.EncMapIntfUintV(v, e) - case *map[interface{}]uint: - fastpathTV.EncMapIntfUintV(*v, e) - case map[interface{}]uint8: - fastpathTV.EncMapIntfUint8V(v, e) - case *map[interface{}]uint8: - fastpathTV.EncMapIntfUint8V(*v, e) - case map[interface{}]uint16: - fastpathTV.EncMapIntfUint16V(v, e) - case *map[interface{}]uint16: - fastpathTV.EncMapIntfUint16V(*v, e) - case map[interface{}]uint32: - fastpathTV.EncMapIntfUint32V(v, e) - case *map[interface{}]uint32: - fastpathTV.EncMapIntfUint32V(*v, e) - case map[interface{}]uint64: - fastpathTV.EncMapIntfUint64V(v, e) - case *map[interface{}]uint64: - fastpathTV.EncMapIntfUint64V(*v, e) - case map[interface{}]uintptr: - fastpathTV.EncMapIntfUintptrV(v, e) - case *map[interface{}]uintptr: - fastpathTV.EncMapIntfUintptrV(*v, e) - case map[interface{}]int: - fastpathTV.EncMapIntfIntV(v, e) - case *map[interface{}]int: - fastpathTV.EncMapIntfIntV(*v, e) - case map[interface{}]int8: - fastpathTV.EncMapIntfInt8V(v, e) - case *map[interface{}]int8: - fastpathTV.EncMapIntfInt8V(*v, e) - case map[interface{}]int16: - fastpathTV.EncMapIntfInt16V(v, e) - case *map[interface{}]int16: - fastpathTV.EncMapIntfInt16V(*v, e) - case map[interface{}]int32: - fastpathTV.EncMapIntfInt32V(v, e) - case *map[interface{}]int32: - fastpathTV.EncMapIntfInt32V(*v, e) - case map[interface{}]int64: - fastpathTV.EncMapIntfInt64V(v, e) - case *map[interface{}]int64: - fastpathTV.EncMapIntfInt64V(*v, e) - case map[interface{}]float32: - fastpathTV.EncMapIntfFloat32V(v, e) - case *map[interface{}]float32: - fastpathTV.EncMapIntfFloat32V(*v, e) - case map[interface{}]float64: - fastpathTV.EncMapIntfFloat64V(v, e) - case *map[interface{}]float64: - fastpathTV.EncMapIntfFloat64V(*v, e) - case map[interface{}]bool: - fastpathTV.EncMapIntfBoolV(v, e) - case *map[interface{}]bool: - fastpathTV.EncMapIntfBoolV(*v, e) - case map[string]interface{}: - fastpathTV.EncMapStringIntfV(v, e) - case *map[string]interface{}: - fastpathTV.EncMapStringIntfV(*v, e) - case map[string]string: - fastpathTV.EncMapStringStringV(v, e) - case *map[string]string: - fastpathTV.EncMapStringStringV(*v, e) - case map[string]uint: - fastpathTV.EncMapStringUintV(v, e) - case *map[string]uint: - fastpathTV.EncMapStringUintV(*v, e) - case map[string]uint8: - fastpathTV.EncMapStringUint8V(v, e) - case *map[string]uint8: - fastpathTV.EncMapStringUint8V(*v, e) - case map[string]uint16: - fastpathTV.EncMapStringUint16V(v, e) - case *map[string]uint16: - fastpathTV.EncMapStringUint16V(*v, e) - case map[string]uint32: - fastpathTV.EncMapStringUint32V(v, e) - case *map[string]uint32: - fastpathTV.EncMapStringUint32V(*v, e) - case map[string]uint64: - fastpathTV.EncMapStringUint64V(v, e) - case *map[string]uint64: - fastpathTV.EncMapStringUint64V(*v, e) - case map[string]uintptr: - fastpathTV.EncMapStringUintptrV(v, e) - case *map[string]uintptr: - fastpathTV.EncMapStringUintptrV(*v, e) - case map[string]int: - fastpathTV.EncMapStringIntV(v, e) - case *map[string]int: - fastpathTV.EncMapStringIntV(*v, e) - case map[string]int8: - fastpathTV.EncMapStringInt8V(v, e) - case *map[string]int8: - fastpathTV.EncMapStringInt8V(*v, e) - case map[string]int16: - fastpathTV.EncMapStringInt16V(v, e) - case *map[string]int16: - fastpathTV.EncMapStringInt16V(*v, e) - case map[string]int32: - fastpathTV.EncMapStringInt32V(v, e) - case *map[string]int32: - fastpathTV.EncMapStringInt32V(*v, e) - case map[string]int64: - fastpathTV.EncMapStringInt64V(v, e) - case *map[string]int64: - fastpathTV.EncMapStringInt64V(*v, e) - case map[string]float32: - fastpathTV.EncMapStringFloat32V(v, e) - case *map[string]float32: - fastpathTV.EncMapStringFloat32V(*v, e) - case map[string]float64: - fastpathTV.EncMapStringFloat64V(v, e) - case *map[string]float64: - fastpathTV.EncMapStringFloat64V(*v, e) - case map[string]bool: - fastpathTV.EncMapStringBoolV(v, e) - case *map[string]bool: - fastpathTV.EncMapStringBoolV(*v, e) - case map[float32]interface{}: - fastpathTV.EncMapFloat32IntfV(v, e) - case *map[float32]interface{}: - fastpathTV.EncMapFloat32IntfV(*v, e) - case map[float32]string: - fastpathTV.EncMapFloat32StringV(v, e) - case *map[float32]string: - fastpathTV.EncMapFloat32StringV(*v, e) - case map[float32]uint: - fastpathTV.EncMapFloat32UintV(v, e) - case *map[float32]uint: - fastpathTV.EncMapFloat32UintV(*v, e) - case map[float32]uint8: - fastpathTV.EncMapFloat32Uint8V(v, e) - case *map[float32]uint8: - fastpathTV.EncMapFloat32Uint8V(*v, e) - case map[float32]uint16: - fastpathTV.EncMapFloat32Uint16V(v, e) - case *map[float32]uint16: - fastpathTV.EncMapFloat32Uint16V(*v, e) - case map[float32]uint32: - fastpathTV.EncMapFloat32Uint32V(v, e) - case *map[float32]uint32: - fastpathTV.EncMapFloat32Uint32V(*v, e) - case map[float32]uint64: - fastpathTV.EncMapFloat32Uint64V(v, e) - case *map[float32]uint64: - fastpathTV.EncMapFloat32Uint64V(*v, e) - case map[float32]uintptr: - fastpathTV.EncMapFloat32UintptrV(v, e) - case *map[float32]uintptr: - fastpathTV.EncMapFloat32UintptrV(*v, e) - case map[float32]int: - fastpathTV.EncMapFloat32IntV(v, e) - case *map[float32]int: - fastpathTV.EncMapFloat32IntV(*v, e) - case map[float32]int8: - fastpathTV.EncMapFloat32Int8V(v, e) - case *map[float32]int8: - fastpathTV.EncMapFloat32Int8V(*v, e) - case map[float32]int16: - fastpathTV.EncMapFloat32Int16V(v, e) - case *map[float32]int16: - fastpathTV.EncMapFloat32Int16V(*v, e) - case map[float32]int32: - fastpathTV.EncMapFloat32Int32V(v, e) - case *map[float32]int32: - fastpathTV.EncMapFloat32Int32V(*v, e) - case map[float32]int64: - fastpathTV.EncMapFloat32Int64V(v, e) - case *map[float32]int64: - fastpathTV.EncMapFloat32Int64V(*v, e) - case map[float32]float32: - fastpathTV.EncMapFloat32Float32V(v, e) - case *map[float32]float32: - fastpathTV.EncMapFloat32Float32V(*v, e) - case map[float32]float64: - fastpathTV.EncMapFloat32Float64V(v, e) - case *map[float32]float64: - fastpathTV.EncMapFloat32Float64V(*v, e) - case map[float32]bool: - fastpathTV.EncMapFloat32BoolV(v, e) - case *map[float32]bool: - fastpathTV.EncMapFloat32BoolV(*v, e) - case map[float64]interface{}: - fastpathTV.EncMapFloat64IntfV(v, e) - case *map[float64]interface{}: - fastpathTV.EncMapFloat64IntfV(*v, e) - case map[float64]string: - fastpathTV.EncMapFloat64StringV(v, e) - case *map[float64]string: - fastpathTV.EncMapFloat64StringV(*v, e) - case map[float64]uint: - fastpathTV.EncMapFloat64UintV(v, e) - case *map[float64]uint: - fastpathTV.EncMapFloat64UintV(*v, e) - case map[float64]uint8: - fastpathTV.EncMapFloat64Uint8V(v, e) - case *map[float64]uint8: - fastpathTV.EncMapFloat64Uint8V(*v, e) - case map[float64]uint16: - fastpathTV.EncMapFloat64Uint16V(v, e) - case *map[float64]uint16: - fastpathTV.EncMapFloat64Uint16V(*v, e) - case map[float64]uint32: - fastpathTV.EncMapFloat64Uint32V(v, e) - case *map[float64]uint32: - fastpathTV.EncMapFloat64Uint32V(*v, e) - case map[float64]uint64: - fastpathTV.EncMapFloat64Uint64V(v, e) - case *map[float64]uint64: - fastpathTV.EncMapFloat64Uint64V(*v, e) - case map[float64]uintptr: - fastpathTV.EncMapFloat64UintptrV(v, e) - case *map[float64]uintptr: - fastpathTV.EncMapFloat64UintptrV(*v, e) - case map[float64]int: - fastpathTV.EncMapFloat64IntV(v, e) - case *map[float64]int: - fastpathTV.EncMapFloat64IntV(*v, e) - case map[float64]int8: - fastpathTV.EncMapFloat64Int8V(v, e) - case *map[float64]int8: - fastpathTV.EncMapFloat64Int8V(*v, e) - case map[float64]int16: - fastpathTV.EncMapFloat64Int16V(v, e) - case *map[float64]int16: - fastpathTV.EncMapFloat64Int16V(*v, e) - case map[float64]int32: - fastpathTV.EncMapFloat64Int32V(v, e) - case *map[float64]int32: - fastpathTV.EncMapFloat64Int32V(*v, e) - case map[float64]int64: - fastpathTV.EncMapFloat64Int64V(v, e) - case *map[float64]int64: - fastpathTV.EncMapFloat64Int64V(*v, e) - case map[float64]float32: - fastpathTV.EncMapFloat64Float32V(v, e) - case *map[float64]float32: - fastpathTV.EncMapFloat64Float32V(*v, e) - case map[float64]float64: - fastpathTV.EncMapFloat64Float64V(v, e) - case *map[float64]float64: - fastpathTV.EncMapFloat64Float64V(*v, e) - case map[float64]bool: - fastpathTV.EncMapFloat64BoolV(v, e) - case *map[float64]bool: - fastpathTV.EncMapFloat64BoolV(*v, e) - case map[uint]interface{}: - fastpathTV.EncMapUintIntfV(v, e) - case *map[uint]interface{}: - fastpathTV.EncMapUintIntfV(*v, e) - case map[uint]string: - fastpathTV.EncMapUintStringV(v, e) - case *map[uint]string: - fastpathTV.EncMapUintStringV(*v, e) - case map[uint]uint: - fastpathTV.EncMapUintUintV(v, e) - case *map[uint]uint: - fastpathTV.EncMapUintUintV(*v, e) - case map[uint]uint8: - fastpathTV.EncMapUintUint8V(v, e) - case *map[uint]uint8: - fastpathTV.EncMapUintUint8V(*v, e) - case map[uint]uint16: - fastpathTV.EncMapUintUint16V(v, e) - case *map[uint]uint16: - fastpathTV.EncMapUintUint16V(*v, e) - case map[uint]uint32: - fastpathTV.EncMapUintUint32V(v, e) - case *map[uint]uint32: - fastpathTV.EncMapUintUint32V(*v, e) - case map[uint]uint64: - fastpathTV.EncMapUintUint64V(v, e) - case *map[uint]uint64: - fastpathTV.EncMapUintUint64V(*v, e) - case map[uint]uintptr: - fastpathTV.EncMapUintUintptrV(v, e) - case *map[uint]uintptr: - fastpathTV.EncMapUintUintptrV(*v, e) - case map[uint]int: - fastpathTV.EncMapUintIntV(v, e) - case *map[uint]int: - fastpathTV.EncMapUintIntV(*v, e) - case map[uint]int8: - fastpathTV.EncMapUintInt8V(v, e) - case *map[uint]int8: - fastpathTV.EncMapUintInt8V(*v, e) - case map[uint]int16: - fastpathTV.EncMapUintInt16V(v, e) - case *map[uint]int16: - fastpathTV.EncMapUintInt16V(*v, e) - case map[uint]int32: - fastpathTV.EncMapUintInt32V(v, e) - case *map[uint]int32: - fastpathTV.EncMapUintInt32V(*v, e) - case map[uint]int64: - fastpathTV.EncMapUintInt64V(v, e) - case *map[uint]int64: - fastpathTV.EncMapUintInt64V(*v, e) - case map[uint]float32: - fastpathTV.EncMapUintFloat32V(v, e) - case *map[uint]float32: - fastpathTV.EncMapUintFloat32V(*v, e) - case map[uint]float64: - fastpathTV.EncMapUintFloat64V(v, e) - case *map[uint]float64: - fastpathTV.EncMapUintFloat64V(*v, e) - case map[uint]bool: - fastpathTV.EncMapUintBoolV(v, e) - case *map[uint]bool: - fastpathTV.EncMapUintBoolV(*v, e) - case map[uint8]interface{}: - fastpathTV.EncMapUint8IntfV(v, e) - case *map[uint8]interface{}: - fastpathTV.EncMapUint8IntfV(*v, e) - case map[uint8]string: - fastpathTV.EncMapUint8StringV(v, e) - case *map[uint8]string: - fastpathTV.EncMapUint8StringV(*v, e) - case map[uint8]uint: - fastpathTV.EncMapUint8UintV(v, e) - case *map[uint8]uint: - fastpathTV.EncMapUint8UintV(*v, e) - case map[uint8]uint8: - fastpathTV.EncMapUint8Uint8V(v, e) - case *map[uint8]uint8: - fastpathTV.EncMapUint8Uint8V(*v, e) - case map[uint8]uint16: - fastpathTV.EncMapUint8Uint16V(v, e) - case *map[uint8]uint16: - fastpathTV.EncMapUint8Uint16V(*v, e) - case map[uint8]uint32: - fastpathTV.EncMapUint8Uint32V(v, e) - case *map[uint8]uint32: - fastpathTV.EncMapUint8Uint32V(*v, e) - case map[uint8]uint64: - fastpathTV.EncMapUint8Uint64V(v, e) - case *map[uint8]uint64: - fastpathTV.EncMapUint8Uint64V(*v, e) - case map[uint8]uintptr: - fastpathTV.EncMapUint8UintptrV(v, e) - case *map[uint8]uintptr: - fastpathTV.EncMapUint8UintptrV(*v, e) - case map[uint8]int: - fastpathTV.EncMapUint8IntV(v, e) - case *map[uint8]int: - fastpathTV.EncMapUint8IntV(*v, e) - case map[uint8]int8: - fastpathTV.EncMapUint8Int8V(v, e) - case *map[uint8]int8: - fastpathTV.EncMapUint8Int8V(*v, e) - case map[uint8]int16: - fastpathTV.EncMapUint8Int16V(v, e) - case *map[uint8]int16: - fastpathTV.EncMapUint8Int16V(*v, e) - case map[uint8]int32: - fastpathTV.EncMapUint8Int32V(v, e) - case *map[uint8]int32: - fastpathTV.EncMapUint8Int32V(*v, e) - case map[uint8]int64: - fastpathTV.EncMapUint8Int64V(v, e) - case *map[uint8]int64: - fastpathTV.EncMapUint8Int64V(*v, e) - case map[uint8]float32: - fastpathTV.EncMapUint8Float32V(v, e) - case *map[uint8]float32: - fastpathTV.EncMapUint8Float32V(*v, e) - case map[uint8]float64: - fastpathTV.EncMapUint8Float64V(v, e) - case *map[uint8]float64: - fastpathTV.EncMapUint8Float64V(*v, e) - case map[uint8]bool: - fastpathTV.EncMapUint8BoolV(v, e) - case *map[uint8]bool: - fastpathTV.EncMapUint8BoolV(*v, e) - case map[uint16]interface{}: - fastpathTV.EncMapUint16IntfV(v, e) - case *map[uint16]interface{}: - fastpathTV.EncMapUint16IntfV(*v, e) - case map[uint16]string: - fastpathTV.EncMapUint16StringV(v, e) - case *map[uint16]string: - fastpathTV.EncMapUint16StringV(*v, e) - case map[uint16]uint: - fastpathTV.EncMapUint16UintV(v, e) - case *map[uint16]uint: - fastpathTV.EncMapUint16UintV(*v, e) - case map[uint16]uint8: - fastpathTV.EncMapUint16Uint8V(v, e) - case *map[uint16]uint8: - fastpathTV.EncMapUint16Uint8V(*v, e) - case map[uint16]uint16: - fastpathTV.EncMapUint16Uint16V(v, e) - case *map[uint16]uint16: - fastpathTV.EncMapUint16Uint16V(*v, e) - case map[uint16]uint32: - fastpathTV.EncMapUint16Uint32V(v, e) - case *map[uint16]uint32: - fastpathTV.EncMapUint16Uint32V(*v, e) - case map[uint16]uint64: - fastpathTV.EncMapUint16Uint64V(v, e) - case *map[uint16]uint64: - fastpathTV.EncMapUint16Uint64V(*v, e) - case map[uint16]uintptr: - fastpathTV.EncMapUint16UintptrV(v, e) - case *map[uint16]uintptr: - fastpathTV.EncMapUint16UintptrV(*v, e) - case map[uint16]int: - fastpathTV.EncMapUint16IntV(v, e) - case *map[uint16]int: - fastpathTV.EncMapUint16IntV(*v, e) - case map[uint16]int8: - fastpathTV.EncMapUint16Int8V(v, e) - case *map[uint16]int8: - fastpathTV.EncMapUint16Int8V(*v, e) - case map[uint16]int16: - fastpathTV.EncMapUint16Int16V(v, e) - case *map[uint16]int16: - fastpathTV.EncMapUint16Int16V(*v, e) - case map[uint16]int32: - fastpathTV.EncMapUint16Int32V(v, e) - case *map[uint16]int32: - fastpathTV.EncMapUint16Int32V(*v, e) - case map[uint16]int64: - fastpathTV.EncMapUint16Int64V(v, e) - case *map[uint16]int64: - fastpathTV.EncMapUint16Int64V(*v, e) - case map[uint16]float32: - fastpathTV.EncMapUint16Float32V(v, e) - case *map[uint16]float32: - fastpathTV.EncMapUint16Float32V(*v, e) - case map[uint16]float64: - fastpathTV.EncMapUint16Float64V(v, e) - case *map[uint16]float64: - fastpathTV.EncMapUint16Float64V(*v, e) - case map[uint16]bool: - fastpathTV.EncMapUint16BoolV(v, e) - case *map[uint16]bool: - fastpathTV.EncMapUint16BoolV(*v, e) - case map[uint32]interface{}: - fastpathTV.EncMapUint32IntfV(v, e) - case *map[uint32]interface{}: - fastpathTV.EncMapUint32IntfV(*v, e) - case map[uint32]string: - fastpathTV.EncMapUint32StringV(v, e) - case *map[uint32]string: - fastpathTV.EncMapUint32StringV(*v, e) - case map[uint32]uint: - fastpathTV.EncMapUint32UintV(v, e) - case *map[uint32]uint: - fastpathTV.EncMapUint32UintV(*v, e) - case map[uint32]uint8: - fastpathTV.EncMapUint32Uint8V(v, e) - case *map[uint32]uint8: - fastpathTV.EncMapUint32Uint8V(*v, e) - case map[uint32]uint16: - fastpathTV.EncMapUint32Uint16V(v, e) - case *map[uint32]uint16: - fastpathTV.EncMapUint32Uint16V(*v, e) - case map[uint32]uint32: - fastpathTV.EncMapUint32Uint32V(v, e) - case *map[uint32]uint32: - fastpathTV.EncMapUint32Uint32V(*v, e) - case map[uint32]uint64: - fastpathTV.EncMapUint32Uint64V(v, e) - case *map[uint32]uint64: - fastpathTV.EncMapUint32Uint64V(*v, e) - case map[uint32]uintptr: - fastpathTV.EncMapUint32UintptrV(v, e) - case *map[uint32]uintptr: - fastpathTV.EncMapUint32UintptrV(*v, e) - case map[uint32]int: - fastpathTV.EncMapUint32IntV(v, e) - case *map[uint32]int: - fastpathTV.EncMapUint32IntV(*v, e) - case map[uint32]int8: - fastpathTV.EncMapUint32Int8V(v, e) - case *map[uint32]int8: - fastpathTV.EncMapUint32Int8V(*v, e) - case map[uint32]int16: - fastpathTV.EncMapUint32Int16V(v, e) - case *map[uint32]int16: - fastpathTV.EncMapUint32Int16V(*v, e) - case map[uint32]int32: - fastpathTV.EncMapUint32Int32V(v, e) - case *map[uint32]int32: - fastpathTV.EncMapUint32Int32V(*v, e) - case map[uint32]int64: - fastpathTV.EncMapUint32Int64V(v, e) - case *map[uint32]int64: - fastpathTV.EncMapUint32Int64V(*v, e) - case map[uint32]float32: - fastpathTV.EncMapUint32Float32V(v, e) - case *map[uint32]float32: - fastpathTV.EncMapUint32Float32V(*v, e) - case map[uint32]float64: - fastpathTV.EncMapUint32Float64V(v, e) - case *map[uint32]float64: - fastpathTV.EncMapUint32Float64V(*v, e) - case map[uint32]bool: - fastpathTV.EncMapUint32BoolV(v, e) - case *map[uint32]bool: - fastpathTV.EncMapUint32BoolV(*v, e) - case map[uint64]interface{}: - fastpathTV.EncMapUint64IntfV(v, e) - case *map[uint64]interface{}: - fastpathTV.EncMapUint64IntfV(*v, e) - case map[uint64]string: - fastpathTV.EncMapUint64StringV(v, e) - case *map[uint64]string: - fastpathTV.EncMapUint64StringV(*v, e) - case map[uint64]uint: - fastpathTV.EncMapUint64UintV(v, e) - case *map[uint64]uint: - fastpathTV.EncMapUint64UintV(*v, e) - case map[uint64]uint8: - fastpathTV.EncMapUint64Uint8V(v, e) - case *map[uint64]uint8: - fastpathTV.EncMapUint64Uint8V(*v, e) - case map[uint64]uint16: - fastpathTV.EncMapUint64Uint16V(v, e) - case *map[uint64]uint16: - fastpathTV.EncMapUint64Uint16V(*v, e) - case map[uint64]uint32: - fastpathTV.EncMapUint64Uint32V(v, e) - case *map[uint64]uint32: - fastpathTV.EncMapUint64Uint32V(*v, e) - case map[uint64]uint64: - fastpathTV.EncMapUint64Uint64V(v, e) - case *map[uint64]uint64: - fastpathTV.EncMapUint64Uint64V(*v, e) - case map[uint64]uintptr: - fastpathTV.EncMapUint64UintptrV(v, e) - case *map[uint64]uintptr: - fastpathTV.EncMapUint64UintptrV(*v, e) - case map[uint64]int: - fastpathTV.EncMapUint64IntV(v, e) - case *map[uint64]int: - fastpathTV.EncMapUint64IntV(*v, e) - case map[uint64]int8: - fastpathTV.EncMapUint64Int8V(v, e) - case *map[uint64]int8: - fastpathTV.EncMapUint64Int8V(*v, e) - case map[uint64]int16: - fastpathTV.EncMapUint64Int16V(v, e) - case *map[uint64]int16: - fastpathTV.EncMapUint64Int16V(*v, e) - case map[uint64]int32: - fastpathTV.EncMapUint64Int32V(v, e) - case *map[uint64]int32: - fastpathTV.EncMapUint64Int32V(*v, e) - case map[uint64]int64: - fastpathTV.EncMapUint64Int64V(v, e) - case *map[uint64]int64: - fastpathTV.EncMapUint64Int64V(*v, e) - case map[uint64]float32: - fastpathTV.EncMapUint64Float32V(v, e) - case *map[uint64]float32: - fastpathTV.EncMapUint64Float32V(*v, e) - case map[uint64]float64: - fastpathTV.EncMapUint64Float64V(v, e) - case *map[uint64]float64: - fastpathTV.EncMapUint64Float64V(*v, e) - case map[uint64]bool: - fastpathTV.EncMapUint64BoolV(v, e) - case *map[uint64]bool: - fastpathTV.EncMapUint64BoolV(*v, e) - case map[uintptr]interface{}: - fastpathTV.EncMapUintptrIntfV(v, e) - case *map[uintptr]interface{}: - fastpathTV.EncMapUintptrIntfV(*v, e) - case map[uintptr]string: - fastpathTV.EncMapUintptrStringV(v, e) - case *map[uintptr]string: - fastpathTV.EncMapUintptrStringV(*v, e) - case map[uintptr]uint: - fastpathTV.EncMapUintptrUintV(v, e) - case *map[uintptr]uint: - fastpathTV.EncMapUintptrUintV(*v, e) - case map[uintptr]uint8: - fastpathTV.EncMapUintptrUint8V(v, e) - case *map[uintptr]uint8: - fastpathTV.EncMapUintptrUint8V(*v, e) - case map[uintptr]uint16: - fastpathTV.EncMapUintptrUint16V(v, e) - case *map[uintptr]uint16: - fastpathTV.EncMapUintptrUint16V(*v, e) - case map[uintptr]uint32: - fastpathTV.EncMapUintptrUint32V(v, e) - case *map[uintptr]uint32: - fastpathTV.EncMapUintptrUint32V(*v, e) - case map[uintptr]uint64: - fastpathTV.EncMapUintptrUint64V(v, e) - case *map[uintptr]uint64: - fastpathTV.EncMapUintptrUint64V(*v, e) - case map[uintptr]uintptr: - fastpathTV.EncMapUintptrUintptrV(v, e) - case *map[uintptr]uintptr: - fastpathTV.EncMapUintptrUintptrV(*v, e) - case map[uintptr]int: - fastpathTV.EncMapUintptrIntV(v, e) - case *map[uintptr]int: - fastpathTV.EncMapUintptrIntV(*v, e) - case map[uintptr]int8: - fastpathTV.EncMapUintptrInt8V(v, e) - case *map[uintptr]int8: - fastpathTV.EncMapUintptrInt8V(*v, e) - case map[uintptr]int16: - fastpathTV.EncMapUintptrInt16V(v, e) - case *map[uintptr]int16: - fastpathTV.EncMapUintptrInt16V(*v, e) - case map[uintptr]int32: - fastpathTV.EncMapUintptrInt32V(v, e) - case *map[uintptr]int32: - fastpathTV.EncMapUintptrInt32V(*v, e) - case map[uintptr]int64: - fastpathTV.EncMapUintptrInt64V(v, e) - case *map[uintptr]int64: - fastpathTV.EncMapUintptrInt64V(*v, e) - case map[uintptr]float32: - fastpathTV.EncMapUintptrFloat32V(v, e) - case *map[uintptr]float32: - fastpathTV.EncMapUintptrFloat32V(*v, e) - case map[uintptr]float64: - fastpathTV.EncMapUintptrFloat64V(v, e) - case *map[uintptr]float64: - fastpathTV.EncMapUintptrFloat64V(*v, e) - case map[uintptr]bool: - fastpathTV.EncMapUintptrBoolV(v, e) - case *map[uintptr]bool: - fastpathTV.EncMapUintptrBoolV(*v, e) - case map[int]interface{}: - fastpathTV.EncMapIntIntfV(v, e) - case *map[int]interface{}: - fastpathTV.EncMapIntIntfV(*v, e) - case map[int]string: - fastpathTV.EncMapIntStringV(v, e) - case *map[int]string: - fastpathTV.EncMapIntStringV(*v, e) - case map[int]uint: - fastpathTV.EncMapIntUintV(v, e) - case *map[int]uint: - fastpathTV.EncMapIntUintV(*v, e) - case map[int]uint8: - fastpathTV.EncMapIntUint8V(v, e) - case *map[int]uint8: - fastpathTV.EncMapIntUint8V(*v, e) - case map[int]uint16: - fastpathTV.EncMapIntUint16V(v, e) - case *map[int]uint16: - fastpathTV.EncMapIntUint16V(*v, e) - case map[int]uint32: - fastpathTV.EncMapIntUint32V(v, e) - case *map[int]uint32: - fastpathTV.EncMapIntUint32V(*v, e) - case map[int]uint64: - fastpathTV.EncMapIntUint64V(v, e) - case *map[int]uint64: - fastpathTV.EncMapIntUint64V(*v, e) - case map[int]uintptr: - fastpathTV.EncMapIntUintptrV(v, e) - case *map[int]uintptr: - fastpathTV.EncMapIntUintptrV(*v, e) - case map[int]int: - fastpathTV.EncMapIntIntV(v, e) - case *map[int]int: - fastpathTV.EncMapIntIntV(*v, e) - case map[int]int8: - fastpathTV.EncMapIntInt8V(v, e) - case *map[int]int8: - fastpathTV.EncMapIntInt8V(*v, e) - case map[int]int16: - fastpathTV.EncMapIntInt16V(v, e) - case *map[int]int16: - fastpathTV.EncMapIntInt16V(*v, e) - case map[int]int32: - fastpathTV.EncMapIntInt32V(v, e) - case *map[int]int32: - fastpathTV.EncMapIntInt32V(*v, e) - case map[int]int64: - fastpathTV.EncMapIntInt64V(v, e) - case *map[int]int64: - fastpathTV.EncMapIntInt64V(*v, e) - case map[int]float32: - fastpathTV.EncMapIntFloat32V(v, e) - case *map[int]float32: - fastpathTV.EncMapIntFloat32V(*v, e) - case map[int]float64: - fastpathTV.EncMapIntFloat64V(v, e) - case *map[int]float64: - fastpathTV.EncMapIntFloat64V(*v, e) - case map[int]bool: - fastpathTV.EncMapIntBoolV(v, e) - case *map[int]bool: - fastpathTV.EncMapIntBoolV(*v, e) - case map[int8]interface{}: - fastpathTV.EncMapInt8IntfV(v, e) - case *map[int8]interface{}: - fastpathTV.EncMapInt8IntfV(*v, e) - case map[int8]string: - fastpathTV.EncMapInt8StringV(v, e) - case *map[int8]string: - fastpathTV.EncMapInt8StringV(*v, e) - case map[int8]uint: - fastpathTV.EncMapInt8UintV(v, e) - case *map[int8]uint: - fastpathTV.EncMapInt8UintV(*v, e) - case map[int8]uint8: - fastpathTV.EncMapInt8Uint8V(v, e) - case *map[int8]uint8: - fastpathTV.EncMapInt8Uint8V(*v, e) - case map[int8]uint16: - fastpathTV.EncMapInt8Uint16V(v, e) - case *map[int8]uint16: - fastpathTV.EncMapInt8Uint16V(*v, e) - case map[int8]uint32: - fastpathTV.EncMapInt8Uint32V(v, e) - case *map[int8]uint32: - fastpathTV.EncMapInt8Uint32V(*v, e) - case map[int8]uint64: - fastpathTV.EncMapInt8Uint64V(v, e) - case *map[int8]uint64: - fastpathTV.EncMapInt8Uint64V(*v, e) - case map[int8]uintptr: - fastpathTV.EncMapInt8UintptrV(v, e) - case *map[int8]uintptr: - fastpathTV.EncMapInt8UintptrV(*v, e) - case map[int8]int: - fastpathTV.EncMapInt8IntV(v, e) - case *map[int8]int: - fastpathTV.EncMapInt8IntV(*v, e) - case map[int8]int8: - fastpathTV.EncMapInt8Int8V(v, e) - case *map[int8]int8: - fastpathTV.EncMapInt8Int8V(*v, e) - case map[int8]int16: - fastpathTV.EncMapInt8Int16V(v, e) - case *map[int8]int16: - fastpathTV.EncMapInt8Int16V(*v, e) - case map[int8]int32: - fastpathTV.EncMapInt8Int32V(v, e) - case *map[int8]int32: - fastpathTV.EncMapInt8Int32V(*v, e) - case map[int8]int64: - fastpathTV.EncMapInt8Int64V(v, e) - case *map[int8]int64: - fastpathTV.EncMapInt8Int64V(*v, e) - case map[int8]float32: - fastpathTV.EncMapInt8Float32V(v, e) - case *map[int8]float32: - fastpathTV.EncMapInt8Float32V(*v, e) - case map[int8]float64: - fastpathTV.EncMapInt8Float64V(v, e) - case *map[int8]float64: - fastpathTV.EncMapInt8Float64V(*v, e) - case map[int8]bool: - fastpathTV.EncMapInt8BoolV(v, e) - case *map[int8]bool: - fastpathTV.EncMapInt8BoolV(*v, e) - case map[int16]interface{}: - fastpathTV.EncMapInt16IntfV(v, e) - case *map[int16]interface{}: - fastpathTV.EncMapInt16IntfV(*v, e) - case map[int16]string: - fastpathTV.EncMapInt16StringV(v, e) - case *map[int16]string: - fastpathTV.EncMapInt16StringV(*v, e) - case map[int16]uint: - fastpathTV.EncMapInt16UintV(v, e) - case *map[int16]uint: - fastpathTV.EncMapInt16UintV(*v, e) - case map[int16]uint8: - fastpathTV.EncMapInt16Uint8V(v, e) - case *map[int16]uint8: - fastpathTV.EncMapInt16Uint8V(*v, e) - case map[int16]uint16: - fastpathTV.EncMapInt16Uint16V(v, e) - case *map[int16]uint16: - fastpathTV.EncMapInt16Uint16V(*v, e) - case map[int16]uint32: - fastpathTV.EncMapInt16Uint32V(v, e) - case *map[int16]uint32: - fastpathTV.EncMapInt16Uint32V(*v, e) - case map[int16]uint64: - fastpathTV.EncMapInt16Uint64V(v, e) - case *map[int16]uint64: - fastpathTV.EncMapInt16Uint64V(*v, e) - case map[int16]uintptr: - fastpathTV.EncMapInt16UintptrV(v, e) - case *map[int16]uintptr: - fastpathTV.EncMapInt16UintptrV(*v, e) - case map[int16]int: - fastpathTV.EncMapInt16IntV(v, e) - case *map[int16]int: - fastpathTV.EncMapInt16IntV(*v, e) - case map[int16]int8: - fastpathTV.EncMapInt16Int8V(v, e) - case *map[int16]int8: - fastpathTV.EncMapInt16Int8V(*v, e) - case map[int16]int16: - fastpathTV.EncMapInt16Int16V(v, e) - case *map[int16]int16: - fastpathTV.EncMapInt16Int16V(*v, e) - case map[int16]int32: - fastpathTV.EncMapInt16Int32V(v, e) - case *map[int16]int32: - fastpathTV.EncMapInt16Int32V(*v, e) - case map[int16]int64: - fastpathTV.EncMapInt16Int64V(v, e) - case *map[int16]int64: - fastpathTV.EncMapInt16Int64V(*v, e) - case map[int16]float32: - fastpathTV.EncMapInt16Float32V(v, e) - case *map[int16]float32: - fastpathTV.EncMapInt16Float32V(*v, e) - case map[int16]float64: - fastpathTV.EncMapInt16Float64V(v, e) - case *map[int16]float64: - fastpathTV.EncMapInt16Float64V(*v, e) - case map[int16]bool: - fastpathTV.EncMapInt16BoolV(v, e) - case *map[int16]bool: - fastpathTV.EncMapInt16BoolV(*v, e) - case map[int32]interface{}: - fastpathTV.EncMapInt32IntfV(v, e) - case *map[int32]interface{}: - fastpathTV.EncMapInt32IntfV(*v, e) - case map[int32]string: - fastpathTV.EncMapInt32StringV(v, e) - case *map[int32]string: - fastpathTV.EncMapInt32StringV(*v, e) - case map[int32]uint: - fastpathTV.EncMapInt32UintV(v, e) - case *map[int32]uint: - fastpathTV.EncMapInt32UintV(*v, e) - case map[int32]uint8: - fastpathTV.EncMapInt32Uint8V(v, e) - case *map[int32]uint8: - fastpathTV.EncMapInt32Uint8V(*v, e) - case map[int32]uint16: - fastpathTV.EncMapInt32Uint16V(v, e) - case *map[int32]uint16: - fastpathTV.EncMapInt32Uint16V(*v, e) - case map[int32]uint32: - fastpathTV.EncMapInt32Uint32V(v, e) - case *map[int32]uint32: - fastpathTV.EncMapInt32Uint32V(*v, e) - case map[int32]uint64: - fastpathTV.EncMapInt32Uint64V(v, e) - case *map[int32]uint64: - fastpathTV.EncMapInt32Uint64V(*v, e) - case map[int32]uintptr: - fastpathTV.EncMapInt32UintptrV(v, e) - case *map[int32]uintptr: - fastpathTV.EncMapInt32UintptrV(*v, e) - case map[int32]int: - fastpathTV.EncMapInt32IntV(v, e) - case *map[int32]int: - fastpathTV.EncMapInt32IntV(*v, e) - case map[int32]int8: - fastpathTV.EncMapInt32Int8V(v, e) - case *map[int32]int8: - fastpathTV.EncMapInt32Int8V(*v, e) - case map[int32]int16: - fastpathTV.EncMapInt32Int16V(v, e) - case *map[int32]int16: - fastpathTV.EncMapInt32Int16V(*v, e) - case map[int32]int32: - fastpathTV.EncMapInt32Int32V(v, e) - case *map[int32]int32: - fastpathTV.EncMapInt32Int32V(*v, e) - case map[int32]int64: - fastpathTV.EncMapInt32Int64V(v, e) - case *map[int32]int64: - fastpathTV.EncMapInt32Int64V(*v, e) - case map[int32]float32: - fastpathTV.EncMapInt32Float32V(v, e) - case *map[int32]float32: - fastpathTV.EncMapInt32Float32V(*v, e) - case map[int32]float64: - fastpathTV.EncMapInt32Float64V(v, e) - case *map[int32]float64: - fastpathTV.EncMapInt32Float64V(*v, e) - case map[int32]bool: - fastpathTV.EncMapInt32BoolV(v, e) - case *map[int32]bool: - fastpathTV.EncMapInt32BoolV(*v, e) - case map[int64]interface{}: - fastpathTV.EncMapInt64IntfV(v, e) - case *map[int64]interface{}: - fastpathTV.EncMapInt64IntfV(*v, e) - case map[int64]string: - fastpathTV.EncMapInt64StringV(v, e) - case *map[int64]string: - fastpathTV.EncMapInt64StringV(*v, e) - case map[int64]uint: - fastpathTV.EncMapInt64UintV(v, e) - case *map[int64]uint: - fastpathTV.EncMapInt64UintV(*v, e) - case map[int64]uint8: - fastpathTV.EncMapInt64Uint8V(v, e) - case *map[int64]uint8: - fastpathTV.EncMapInt64Uint8V(*v, e) - case map[int64]uint16: - fastpathTV.EncMapInt64Uint16V(v, e) - case *map[int64]uint16: - fastpathTV.EncMapInt64Uint16V(*v, e) - case map[int64]uint32: - fastpathTV.EncMapInt64Uint32V(v, e) - case *map[int64]uint32: - fastpathTV.EncMapInt64Uint32V(*v, e) - case map[int64]uint64: - fastpathTV.EncMapInt64Uint64V(v, e) - case *map[int64]uint64: - fastpathTV.EncMapInt64Uint64V(*v, e) - case map[int64]uintptr: - fastpathTV.EncMapInt64UintptrV(v, e) - case *map[int64]uintptr: - fastpathTV.EncMapInt64UintptrV(*v, e) - case map[int64]int: - fastpathTV.EncMapInt64IntV(v, e) - case *map[int64]int: - fastpathTV.EncMapInt64IntV(*v, e) - case map[int64]int8: - fastpathTV.EncMapInt64Int8V(v, e) - case *map[int64]int8: - fastpathTV.EncMapInt64Int8V(*v, e) - case map[int64]int16: - fastpathTV.EncMapInt64Int16V(v, e) - case *map[int64]int16: - fastpathTV.EncMapInt64Int16V(*v, e) - case map[int64]int32: - fastpathTV.EncMapInt64Int32V(v, e) - case *map[int64]int32: - fastpathTV.EncMapInt64Int32V(*v, e) - case map[int64]int64: - fastpathTV.EncMapInt64Int64V(v, e) - case *map[int64]int64: - fastpathTV.EncMapInt64Int64V(*v, e) - case map[int64]float32: - fastpathTV.EncMapInt64Float32V(v, e) - case *map[int64]float32: - fastpathTV.EncMapInt64Float32V(*v, e) - case map[int64]float64: - fastpathTV.EncMapInt64Float64V(v, e) - case *map[int64]float64: - fastpathTV.EncMapInt64Float64V(*v, e) - case map[int64]bool: - fastpathTV.EncMapInt64BoolV(v, e) - case *map[int64]bool: - fastpathTV.EncMapInt64BoolV(*v, e) - case map[bool]interface{}: - fastpathTV.EncMapBoolIntfV(v, e) - case *map[bool]interface{}: - fastpathTV.EncMapBoolIntfV(*v, e) - case map[bool]string: - fastpathTV.EncMapBoolStringV(v, e) - case *map[bool]string: - fastpathTV.EncMapBoolStringV(*v, e) - case map[bool]uint: - fastpathTV.EncMapBoolUintV(v, e) - case *map[bool]uint: - fastpathTV.EncMapBoolUintV(*v, e) - case map[bool]uint8: - fastpathTV.EncMapBoolUint8V(v, e) - case *map[bool]uint8: - fastpathTV.EncMapBoolUint8V(*v, e) - case map[bool]uint16: - fastpathTV.EncMapBoolUint16V(v, e) - case *map[bool]uint16: - fastpathTV.EncMapBoolUint16V(*v, e) - case map[bool]uint32: - fastpathTV.EncMapBoolUint32V(v, e) - case *map[bool]uint32: - fastpathTV.EncMapBoolUint32V(*v, e) - case map[bool]uint64: - fastpathTV.EncMapBoolUint64V(v, e) - case *map[bool]uint64: - fastpathTV.EncMapBoolUint64V(*v, e) - case map[bool]uintptr: - fastpathTV.EncMapBoolUintptrV(v, e) - case *map[bool]uintptr: - fastpathTV.EncMapBoolUintptrV(*v, e) - case map[bool]int: - fastpathTV.EncMapBoolIntV(v, e) - case *map[bool]int: - fastpathTV.EncMapBoolIntV(*v, e) - case map[bool]int8: - fastpathTV.EncMapBoolInt8V(v, e) - case *map[bool]int8: - fastpathTV.EncMapBoolInt8V(*v, e) - case map[bool]int16: - fastpathTV.EncMapBoolInt16V(v, e) - case *map[bool]int16: - fastpathTV.EncMapBoolInt16V(*v, e) - case map[bool]int32: - fastpathTV.EncMapBoolInt32V(v, e) - case *map[bool]int32: - fastpathTV.EncMapBoolInt32V(*v, e) - case map[bool]int64: - fastpathTV.EncMapBoolInt64V(v, e) - case *map[bool]int64: - fastpathTV.EncMapBoolInt64V(*v, e) - case map[bool]float32: - fastpathTV.EncMapBoolFloat32V(v, e) - case *map[bool]float32: - fastpathTV.EncMapBoolFloat32V(*v, e) - case map[bool]float64: - fastpathTV.EncMapBoolFloat64V(v, e) - case *map[bool]float64: - fastpathTV.EncMapBoolFloat64V(*v, e) - case map[bool]bool: - fastpathTV.EncMapBoolBoolV(v, e) - case *map[bool]bool: - fastpathTV.EncMapBoolBoolV(*v, e) - - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -// -- -- fast path functions - -func (e *Encoder) fastpathEncSliceIntfR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceIntfV(rv2i(rv).([]interface{}), e) - } else { - fastpathTV.EncSliceIntfV(rv2i(rv).([]interface{}), e) - } -} -func (_ fastpathT) EncSliceIntfV(v []interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - e.encode(v2) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceIntfV(v []interface{}, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - e.encode(v2) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceStringR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceStringV(rv2i(rv).([]string), e) - } else { - fastpathTV.EncSliceStringV(rv2i(rv).([]string), e) - } -} -func (_ fastpathT) EncSliceStringV(v []string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceStringV(v []string, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceFloat32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceFloat32V(rv2i(rv).([]float32), e) - } else { - fastpathTV.EncSliceFloat32V(rv2i(rv).([]float32), e) - } -} -func (_ fastpathT) EncSliceFloat32V(v []float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeFloat32(v2) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceFloat32V(v []float32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeFloat32(v2) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceFloat64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceFloat64V(rv2i(rv).([]float64), e) - } else { - fastpathTV.EncSliceFloat64V(rv2i(rv).([]float64), e) - } -} -func (_ fastpathT) EncSliceFloat64V(v []float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeFloat64(v2) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceFloat64V(v []float64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeFloat64(v2) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUintR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUintV(rv2i(rv).([]uint), e) - } else { - fastpathTV.EncSliceUintV(rv2i(rv).([]uint), e) - } -} -func (_ fastpathT) EncSliceUintV(v []uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUintV(v []uint, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint8R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint8V(rv2i(rv).([]uint8), e) - } else { - fastpathTV.EncSliceUint8V(rv2i(rv).([]uint8), e) - } -} -func (_ fastpathT) EncSliceUint8V(v []uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint8V(v []uint8, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint16R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint16V(rv2i(rv).([]uint16), e) - } else { - fastpathTV.EncSliceUint16V(rv2i(rv).([]uint16), e) - } -} -func (_ fastpathT) EncSliceUint16V(v []uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint16V(v []uint16, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint32V(rv2i(rv).([]uint32), e) - } else { - fastpathTV.EncSliceUint32V(rv2i(rv).([]uint32), e) - } -} -func (_ fastpathT) EncSliceUint32V(v []uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint32V(v []uint32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint64V(rv2i(rv).([]uint64), e) - } else { - fastpathTV.EncSliceUint64V(rv2i(rv).([]uint64), e) - } -} -func (_ fastpathT) EncSliceUint64V(v []uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint64V(v []uint64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeUint(uint64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUintptrR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUintptrV(rv2i(rv).([]uintptr), e) - } else { - fastpathTV.EncSliceUintptrV(rv2i(rv).([]uintptr), e) - } -} -func (_ fastpathT) EncSliceUintptrV(v []uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - e.encode(v2) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUintptrV(v []uintptr, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - e.encode(v2) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceIntR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceIntV(rv2i(rv).([]int), e) - } else { - fastpathTV.EncSliceIntV(rv2i(rv).([]int), e) - } -} -func (_ fastpathT) EncSliceIntV(v []int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeInt(int64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceIntV(v []int, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeInt(int64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt8R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt8V(rv2i(rv).([]int8), e) - } else { - fastpathTV.EncSliceInt8V(rv2i(rv).([]int8), e) - } -} -func (_ fastpathT) EncSliceInt8V(v []int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeInt(int64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt8V(v []int8, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeInt(int64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt16R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt16V(rv2i(rv).([]int16), e) - } else { - fastpathTV.EncSliceInt16V(rv2i(rv).([]int16), e) - } -} -func (_ fastpathT) EncSliceInt16V(v []int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeInt(int64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt16V(v []int16, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeInt(int64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt32V(rv2i(rv).([]int32), e) - } else { - fastpathTV.EncSliceInt32V(rv2i(rv).([]int32), e) - } -} -func (_ fastpathT) EncSliceInt32V(v []int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeInt(int64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt32V(v []int32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeInt(int64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt64V(rv2i(rv).([]int64), e) - } else { - fastpathTV.EncSliceInt64V(rv2i(rv).([]int64), e) - } -} -func (_ fastpathT) EncSliceInt64V(v []int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeInt(int64(v2)) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt64V(v []int64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeInt(int64(v2)) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceBoolR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceBoolV(rv2i(rv).([]bool), e) - } else { - fastpathTV.EncSliceBoolV(rv2i(rv).([]bool), e) - } -} -func (_ fastpathT) EncSliceBoolV(v []bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { - ee.WriteArrayElem() - } - ee.EncodeBool(v2) - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceBoolV(v []bool, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - ee.EncodeBool(v2) - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfIntfV(rv2i(rv).(map[interface{}]interface{}), e) -} -func (_ fastpathT) EncMapIntfIntfV(v map[interface{}]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfStringV(rv2i(rv).(map[interface{}]string), e) -} -func (_ fastpathT) EncMapIntfStringV(v map[interface{}]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUintV(rv2i(rv).(map[interface{}]uint), e) -} -func (_ fastpathT) EncMapIntfUintV(v map[interface{}]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint8V(rv2i(rv).(map[interface{}]uint8), e) -} -func (_ fastpathT) EncMapIntfUint8V(v map[interface{}]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint16V(rv2i(rv).(map[interface{}]uint16), e) -} -func (_ fastpathT) EncMapIntfUint16V(v map[interface{}]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint32V(rv2i(rv).(map[interface{}]uint32), e) -} -func (_ fastpathT) EncMapIntfUint32V(v map[interface{}]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint64V(rv2i(rv).(map[interface{}]uint64), e) -} -func (_ fastpathT) EncMapIntfUint64V(v map[interface{}]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUintptrV(rv2i(rv).(map[interface{}]uintptr), e) -} -func (_ fastpathT) EncMapIntfUintptrV(v map[interface{}]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfIntV(rv2i(rv).(map[interface{}]int), e) -} -func (_ fastpathT) EncMapIntfIntV(v map[interface{}]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt8V(rv2i(rv).(map[interface{}]int8), e) -} -func (_ fastpathT) EncMapIntfInt8V(v map[interface{}]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt16V(rv2i(rv).(map[interface{}]int16), e) -} -func (_ fastpathT) EncMapIntfInt16V(v map[interface{}]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt32V(rv2i(rv).(map[interface{}]int32), e) -} -func (_ fastpathT) EncMapIntfInt32V(v map[interface{}]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt64V(rv2i(rv).(map[interface{}]int64), e) -} -func (_ fastpathT) EncMapIntfInt64V(v map[interface{}]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfFloat32V(rv2i(rv).(map[interface{}]float32), e) -} -func (_ fastpathT) EncMapIntfFloat32V(v map[interface{}]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfFloat64V(rv2i(rv).(map[interface{}]float64), e) -} -func (_ fastpathT) EncMapIntfFloat64V(v map[interface{}]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfBoolV(rv2i(rv).(map[interface{}]bool), e) -} -func (_ fastpathT) EncMapIntfBoolV(v map[interface{}]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.asis(v2[j].v) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[v2[j].i]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringIntfV(rv2i(rv).(map[string]interface{}), e) -} -func (_ fastpathT) EncMapStringIntfV(v map[string]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - e.encode(v[string(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringStringV(rv2i(rv).(map[string]string), e) -} -func (_ fastpathT) EncMapStringStringV(v map[string]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[string(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[string(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUintV(rv2i(rv).(map[string]uint), e) -} -func (_ fastpathT) EncMapStringUintV(v map[string]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint8V(rv2i(rv).(map[string]uint8), e) -} -func (_ fastpathT) EncMapStringUint8V(v map[string]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint16V(rv2i(rv).(map[string]uint16), e) -} -func (_ fastpathT) EncMapStringUint16V(v map[string]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint32V(rv2i(rv).(map[string]uint32), e) -} -func (_ fastpathT) EncMapStringUint32V(v map[string]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint64V(rv2i(rv).(map[string]uint64), e) -} -func (_ fastpathT) EncMapStringUint64V(v map[string]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUintptrV(rv2i(rv).(map[string]uintptr), e) -} -func (_ fastpathT) EncMapStringUintptrV(v map[string]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - e.encode(v[string(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringIntV(rv2i(rv).(map[string]int), e) -} -func (_ fastpathT) EncMapStringIntV(v map[string]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt8V(rv2i(rv).(map[string]int8), e) -} -func (_ fastpathT) EncMapStringInt8V(v map[string]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt16V(rv2i(rv).(map[string]int16), e) -} -func (_ fastpathT) EncMapStringInt16V(v map[string]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt32V(rv2i(rv).(map[string]int32), e) -} -func (_ fastpathT) EncMapStringInt32V(v map[string]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt64V(rv2i(rv).(map[string]int64), e) -} -func (_ fastpathT) EncMapStringInt64V(v map[string]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringFloat32V(rv2i(rv).(map[string]float32), e) -} -func (_ fastpathT) EncMapStringFloat32V(v map[string]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[string(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringFloat64V(rv2i(rv).(map[string]float64), e) -} -func (_ fastpathT) EncMapStringFloat64V(v map[string]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[string(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringBoolV(rv2i(rv).(map[string]bool), e) -} -func (_ fastpathT) EncMapStringBoolV(v map[string]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i uint - for k := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[string(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(k2)) - } else { - ee.EncodeStringEnc(cUTF8, k2) - } - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32IntfV(rv2i(rv).(map[float32]interface{}), e) -} -func (_ fastpathT) EncMapFloat32IntfV(v map[float32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[float32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32StringV(rv2i(rv).(map[float32]string), e) -} -func (_ fastpathT) EncMapFloat32StringV(v map[float32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[float32(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[float32(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32UintV(rv2i(rv).(map[float32]uint), e) -} -func (_ fastpathT) EncMapFloat32UintV(v map[float32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint8V(rv2i(rv).(map[float32]uint8), e) -} -func (_ fastpathT) EncMapFloat32Uint8V(v map[float32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint16V(rv2i(rv).(map[float32]uint16), e) -} -func (_ fastpathT) EncMapFloat32Uint16V(v map[float32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint32V(rv2i(rv).(map[float32]uint32), e) -} -func (_ fastpathT) EncMapFloat32Uint32V(v map[float32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint64V(rv2i(rv).(map[float32]uint64), e) -} -func (_ fastpathT) EncMapFloat32Uint64V(v map[float32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32UintptrV(rv2i(rv).(map[float32]uintptr), e) -} -func (_ fastpathT) EncMapFloat32UintptrV(v map[float32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[float32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32IntV(rv2i(rv).(map[float32]int), e) -} -func (_ fastpathT) EncMapFloat32IntV(v map[float32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int8V(rv2i(rv).(map[float32]int8), e) -} -func (_ fastpathT) EncMapFloat32Int8V(v map[float32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int16V(rv2i(rv).(map[float32]int16), e) -} -func (_ fastpathT) EncMapFloat32Int16V(v map[float32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int32V(rv2i(rv).(map[float32]int32), e) -} -func (_ fastpathT) EncMapFloat32Int32V(v map[float32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int64V(rv2i(rv).(map[float32]int64), e) -} -func (_ fastpathT) EncMapFloat32Int64V(v map[float32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Float32V(rv2i(rv).(map[float32]float32), e) -} -func (_ fastpathT) EncMapFloat32Float32V(v map[float32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[float32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Float64V(rv2i(rv).(map[float32]float64), e) -} -func (_ fastpathT) EncMapFloat32Float64V(v map[float32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[float32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32BoolV(rv2i(rv).(map[float32]bool), e) -} -func (_ fastpathT) EncMapFloat32BoolV(v map[float32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[float32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64IntfV(rv2i(rv).(map[float64]interface{}), e) -} -func (_ fastpathT) EncMapFloat64IntfV(v map[float64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[float64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64StringV(rv2i(rv).(map[float64]string), e) -} -func (_ fastpathT) EncMapFloat64StringV(v map[float64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[float64(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[float64(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64UintV(rv2i(rv).(map[float64]uint), e) -} -func (_ fastpathT) EncMapFloat64UintV(v map[float64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint8V(rv2i(rv).(map[float64]uint8), e) -} -func (_ fastpathT) EncMapFloat64Uint8V(v map[float64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint16V(rv2i(rv).(map[float64]uint16), e) -} -func (_ fastpathT) EncMapFloat64Uint16V(v map[float64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint32V(rv2i(rv).(map[float64]uint32), e) -} -func (_ fastpathT) EncMapFloat64Uint32V(v map[float64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint64V(rv2i(rv).(map[float64]uint64), e) -} -func (_ fastpathT) EncMapFloat64Uint64V(v map[float64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64UintptrV(rv2i(rv).(map[float64]uintptr), e) -} -func (_ fastpathT) EncMapFloat64UintptrV(v map[float64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[float64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64IntV(rv2i(rv).(map[float64]int), e) -} -func (_ fastpathT) EncMapFloat64IntV(v map[float64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int8V(rv2i(rv).(map[float64]int8), e) -} -func (_ fastpathT) EncMapFloat64Int8V(v map[float64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int16V(rv2i(rv).(map[float64]int16), e) -} -func (_ fastpathT) EncMapFloat64Int16V(v map[float64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int32V(rv2i(rv).(map[float64]int32), e) -} -func (_ fastpathT) EncMapFloat64Int32V(v map[float64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int64V(rv2i(rv).(map[float64]int64), e) -} -func (_ fastpathT) EncMapFloat64Int64V(v map[float64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Float32V(rv2i(rv).(map[float64]float32), e) -} -func (_ fastpathT) EncMapFloat64Float32V(v map[float64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[float64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Float64V(rv2i(rv).(map[float64]float64), e) -} -func (_ fastpathT) EncMapFloat64Float64V(v map[float64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[float64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64BoolV(rv2i(rv).(map[float64]bool), e) -} -func (_ fastpathT) EncMapFloat64BoolV(v map[float64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i uint - for k := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(float64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[float64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintIntfV(rv2i(rv).(map[uint]interface{}), e) -} -func (_ fastpathT) EncMapUintIntfV(v map[uint]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintStringV(rv2i(rv).(map[uint]string), e) -} -func (_ fastpathT) EncMapUintStringV(v map[uint]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uint(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uint(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUintV(rv2i(rv).(map[uint]uint), e) -} -func (_ fastpathT) EncMapUintUintV(v map[uint]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint8V(rv2i(rv).(map[uint]uint8), e) -} -func (_ fastpathT) EncMapUintUint8V(v map[uint]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint16V(rv2i(rv).(map[uint]uint16), e) -} -func (_ fastpathT) EncMapUintUint16V(v map[uint]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint32V(rv2i(rv).(map[uint]uint32), e) -} -func (_ fastpathT) EncMapUintUint32V(v map[uint]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint64V(rv2i(rv).(map[uint]uint64), e) -} -func (_ fastpathT) EncMapUintUint64V(v map[uint]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUintptrV(rv2i(rv).(map[uint]uintptr), e) -} -func (_ fastpathT) EncMapUintUintptrV(v map[uint]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintIntV(rv2i(rv).(map[uint]int), e) -} -func (_ fastpathT) EncMapUintIntV(v map[uint]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt8V(rv2i(rv).(map[uint]int8), e) -} -func (_ fastpathT) EncMapUintInt8V(v map[uint]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt16V(rv2i(rv).(map[uint]int16), e) -} -func (_ fastpathT) EncMapUintInt16V(v map[uint]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt32V(rv2i(rv).(map[uint]int32), e) -} -func (_ fastpathT) EncMapUintInt32V(v map[uint]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt64V(rv2i(rv).(map[uint]int64), e) -} -func (_ fastpathT) EncMapUintInt64V(v map[uint]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintFloat32V(rv2i(rv).(map[uint]float32), e) -} -func (_ fastpathT) EncMapUintFloat32V(v map[uint]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uint(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintFloat64V(rv2i(rv).(map[uint]float64), e) -} -func (_ fastpathT) EncMapUintFloat64V(v map[uint]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uint(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintBoolV(rv2i(rv).(map[uint]bool), e) -} -func (_ fastpathT) EncMapUintBoolV(v map[uint]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uint(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), e) -} -func (_ fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8StringV(rv2i(rv).(map[uint8]string), e) -} -func (_ fastpathT) EncMapUint8StringV(v map[uint8]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uint8(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uint8(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8UintV(rv2i(rv).(map[uint8]uint), e) -} -func (_ fastpathT) EncMapUint8UintV(v map[uint8]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint8V(rv2i(rv).(map[uint8]uint8), e) -} -func (_ fastpathT) EncMapUint8Uint8V(v map[uint8]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint16V(rv2i(rv).(map[uint8]uint16), e) -} -func (_ fastpathT) EncMapUint8Uint16V(v map[uint8]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint32V(rv2i(rv).(map[uint8]uint32), e) -} -func (_ fastpathT) EncMapUint8Uint32V(v map[uint8]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint64V(rv2i(rv).(map[uint8]uint64), e) -} -func (_ fastpathT) EncMapUint8Uint64V(v map[uint8]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8UintptrV(rv2i(rv).(map[uint8]uintptr), e) -} -func (_ fastpathT) EncMapUint8UintptrV(v map[uint8]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8IntV(rv2i(rv).(map[uint8]int), e) -} -func (_ fastpathT) EncMapUint8IntV(v map[uint8]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int8V(rv2i(rv).(map[uint8]int8), e) -} -func (_ fastpathT) EncMapUint8Int8V(v map[uint8]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int16V(rv2i(rv).(map[uint8]int16), e) -} -func (_ fastpathT) EncMapUint8Int16V(v map[uint8]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int32V(rv2i(rv).(map[uint8]int32), e) -} -func (_ fastpathT) EncMapUint8Int32V(v map[uint8]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int64V(rv2i(rv).(map[uint8]int64), e) -} -func (_ fastpathT) EncMapUint8Int64V(v map[uint8]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Float32V(rv2i(rv).(map[uint8]float32), e) -} -func (_ fastpathT) EncMapUint8Float32V(v map[uint8]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uint8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Float64V(rv2i(rv).(map[uint8]float64), e) -} -func (_ fastpathT) EncMapUint8Float64V(v map[uint8]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uint8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8BoolV(rv2i(rv).(map[uint8]bool), e) -} -func (_ fastpathT) EncMapUint8BoolV(v map[uint8]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uint8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16IntfV(rv2i(rv).(map[uint16]interface{}), e) -} -func (_ fastpathT) EncMapUint16IntfV(v map[uint16]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16StringV(rv2i(rv).(map[uint16]string), e) -} -func (_ fastpathT) EncMapUint16StringV(v map[uint16]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uint16(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uint16(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16UintV(rv2i(rv).(map[uint16]uint), e) -} -func (_ fastpathT) EncMapUint16UintV(v map[uint16]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint8V(rv2i(rv).(map[uint16]uint8), e) -} -func (_ fastpathT) EncMapUint16Uint8V(v map[uint16]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint16V(rv2i(rv).(map[uint16]uint16), e) -} -func (_ fastpathT) EncMapUint16Uint16V(v map[uint16]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint32V(rv2i(rv).(map[uint16]uint32), e) -} -func (_ fastpathT) EncMapUint16Uint32V(v map[uint16]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint64V(rv2i(rv).(map[uint16]uint64), e) -} -func (_ fastpathT) EncMapUint16Uint64V(v map[uint16]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16UintptrV(rv2i(rv).(map[uint16]uintptr), e) -} -func (_ fastpathT) EncMapUint16UintptrV(v map[uint16]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16IntV(rv2i(rv).(map[uint16]int), e) -} -func (_ fastpathT) EncMapUint16IntV(v map[uint16]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int8V(rv2i(rv).(map[uint16]int8), e) -} -func (_ fastpathT) EncMapUint16Int8V(v map[uint16]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int16V(rv2i(rv).(map[uint16]int16), e) -} -func (_ fastpathT) EncMapUint16Int16V(v map[uint16]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int32V(rv2i(rv).(map[uint16]int32), e) -} -func (_ fastpathT) EncMapUint16Int32V(v map[uint16]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int64V(rv2i(rv).(map[uint16]int64), e) -} -func (_ fastpathT) EncMapUint16Int64V(v map[uint16]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Float32V(rv2i(rv).(map[uint16]float32), e) -} -func (_ fastpathT) EncMapUint16Float32V(v map[uint16]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uint16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Float64V(rv2i(rv).(map[uint16]float64), e) -} -func (_ fastpathT) EncMapUint16Float64V(v map[uint16]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uint16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16BoolV(rv2i(rv).(map[uint16]bool), e) -} -func (_ fastpathT) EncMapUint16BoolV(v map[uint16]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uint16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32IntfV(rv2i(rv).(map[uint32]interface{}), e) -} -func (_ fastpathT) EncMapUint32IntfV(v map[uint32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32StringV(rv2i(rv).(map[uint32]string), e) -} -func (_ fastpathT) EncMapUint32StringV(v map[uint32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uint32(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uint32(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32UintV(rv2i(rv).(map[uint32]uint), e) -} -func (_ fastpathT) EncMapUint32UintV(v map[uint32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint8V(rv2i(rv).(map[uint32]uint8), e) -} -func (_ fastpathT) EncMapUint32Uint8V(v map[uint32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint16V(rv2i(rv).(map[uint32]uint16), e) -} -func (_ fastpathT) EncMapUint32Uint16V(v map[uint32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint32V(rv2i(rv).(map[uint32]uint32), e) -} -func (_ fastpathT) EncMapUint32Uint32V(v map[uint32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint64V(rv2i(rv).(map[uint32]uint64), e) -} -func (_ fastpathT) EncMapUint32Uint64V(v map[uint32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32UintptrV(rv2i(rv).(map[uint32]uintptr), e) -} -func (_ fastpathT) EncMapUint32UintptrV(v map[uint32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32IntV(rv2i(rv).(map[uint32]int), e) -} -func (_ fastpathT) EncMapUint32IntV(v map[uint32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int8V(rv2i(rv).(map[uint32]int8), e) -} -func (_ fastpathT) EncMapUint32Int8V(v map[uint32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int16V(rv2i(rv).(map[uint32]int16), e) -} -func (_ fastpathT) EncMapUint32Int16V(v map[uint32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int32V(rv2i(rv).(map[uint32]int32), e) -} -func (_ fastpathT) EncMapUint32Int32V(v map[uint32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int64V(rv2i(rv).(map[uint32]int64), e) -} -func (_ fastpathT) EncMapUint32Int64V(v map[uint32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Float32V(rv2i(rv).(map[uint32]float32), e) -} -func (_ fastpathT) EncMapUint32Float32V(v map[uint32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uint32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Float64V(rv2i(rv).(map[uint32]float64), e) -} -func (_ fastpathT) EncMapUint32Float64V(v map[uint32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uint32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32BoolV(rv2i(rv).(map[uint32]bool), e) -} -func (_ fastpathT) EncMapUint32BoolV(v map[uint32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uint32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64IntfV(rv2i(rv).(map[uint64]interface{}), e) -} -func (_ fastpathT) EncMapUint64IntfV(v map[uint64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64StringV(rv2i(rv).(map[uint64]string), e) -} -func (_ fastpathT) EncMapUint64StringV(v map[uint64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uint64(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uint64(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64UintV(rv2i(rv).(map[uint64]uint), e) -} -func (_ fastpathT) EncMapUint64UintV(v map[uint64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint8V(rv2i(rv).(map[uint64]uint8), e) -} -func (_ fastpathT) EncMapUint64Uint8V(v map[uint64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint16V(rv2i(rv).(map[uint64]uint16), e) -} -func (_ fastpathT) EncMapUint64Uint16V(v map[uint64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint32V(rv2i(rv).(map[uint64]uint32), e) -} -func (_ fastpathT) EncMapUint64Uint32V(v map[uint64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint64V(rv2i(rv).(map[uint64]uint64), e) -} -func (_ fastpathT) EncMapUint64Uint64V(v map[uint64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64UintptrV(rv2i(rv).(map[uint64]uintptr), e) -} -func (_ fastpathT) EncMapUint64UintptrV(v map[uint64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uint64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64IntV(rv2i(rv).(map[uint64]int), e) -} -func (_ fastpathT) EncMapUint64IntV(v map[uint64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int8V(rv2i(rv).(map[uint64]int8), e) -} -func (_ fastpathT) EncMapUint64Int8V(v map[uint64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int16V(rv2i(rv).(map[uint64]int16), e) -} -func (_ fastpathT) EncMapUint64Int16V(v map[uint64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int32V(rv2i(rv).(map[uint64]int32), e) -} -func (_ fastpathT) EncMapUint64Int32V(v map[uint64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int64V(rv2i(rv).(map[uint64]int64), e) -} -func (_ fastpathT) EncMapUint64Int64V(v map[uint64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Float32V(rv2i(rv).(map[uint64]float32), e) -} -func (_ fastpathT) EncMapUint64Float32V(v map[uint64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uint64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Float64V(rv2i(rv).(map[uint64]float64), e) -} -func (_ fastpathT) EncMapUint64Float64V(v map[uint64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uint64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64BoolV(rv2i(rv).(map[uint64]bool), e) -} -func (_ fastpathT) EncMapUint64BoolV(v map[uint64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(uint64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uint64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeUint(uint64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrIntfV(rv2i(rv).(map[uintptr]interface{}), e) -} -func (_ fastpathT) EncMapUintptrIntfV(v map[uintptr]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uintptr(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrStringV(rv2i(rv).(map[uintptr]string), e) -} -func (_ fastpathT) EncMapUintptrStringV(v map[uintptr]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[uintptr(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[uintptr(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUintV(rv2i(rv).(map[uintptr]uint), e) -} -func (_ fastpathT) EncMapUintptrUintV(v map[uintptr]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint8V(rv2i(rv).(map[uintptr]uint8), e) -} -func (_ fastpathT) EncMapUintptrUint8V(v map[uintptr]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint16V(rv2i(rv).(map[uintptr]uint16), e) -} -func (_ fastpathT) EncMapUintptrUint16V(v map[uintptr]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint32V(rv2i(rv).(map[uintptr]uint32), e) -} -func (_ fastpathT) EncMapUintptrUint32V(v map[uintptr]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint64V(rv2i(rv).(map[uintptr]uint64), e) -} -func (_ fastpathT) EncMapUintptrUint64V(v map[uintptr]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUintptrV(rv2i(rv).(map[uintptr]uintptr), e) -} -func (_ fastpathT) EncMapUintptrUintptrV(v map[uintptr]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[uintptr(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrIntV(rv2i(rv).(map[uintptr]int), e) -} -func (_ fastpathT) EncMapUintptrIntV(v map[uintptr]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt8V(rv2i(rv).(map[uintptr]int8), e) -} -func (_ fastpathT) EncMapUintptrInt8V(v map[uintptr]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt16V(rv2i(rv).(map[uintptr]int16), e) -} -func (_ fastpathT) EncMapUintptrInt16V(v map[uintptr]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt32V(rv2i(rv).(map[uintptr]int32), e) -} -func (_ fastpathT) EncMapUintptrInt32V(v map[uintptr]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt64V(rv2i(rv).(map[uintptr]int64), e) -} -func (_ fastpathT) EncMapUintptrInt64V(v map[uintptr]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrFloat32V(rv2i(rv).(map[uintptr]float32), e) -} -func (_ fastpathT) EncMapUintptrFloat32V(v map[uintptr]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[uintptr(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrFloat64V(rv2i(rv).(map[uintptr]float64), e) -} -func (_ fastpathT) EncMapUintptrFloat64V(v map[uintptr]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[uintptr(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrBoolV(rv2i(rv).(map[uintptr]bool), e) -} -func (_ fastpathT) EncMapUintptrBoolV(v map[uintptr]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i uint - for k := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - e.encode(uintptr(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[uintptr(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - e.encode(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntIntfV(rv2i(rv).(map[int]interface{}), e) -} -func (_ fastpathT) EncMapIntIntfV(v map[int]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntStringV(rv2i(rv).(map[int]string), e) -} -func (_ fastpathT) EncMapIntStringV(v map[int]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[int(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[int(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUintV(rv2i(rv).(map[int]uint), e) -} -func (_ fastpathT) EncMapIntUintV(v map[int]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint8V(rv2i(rv).(map[int]uint8), e) -} -func (_ fastpathT) EncMapIntUint8V(v map[int]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint16V(rv2i(rv).(map[int]uint16), e) -} -func (_ fastpathT) EncMapIntUint16V(v map[int]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint32V(rv2i(rv).(map[int]uint32), e) -} -func (_ fastpathT) EncMapIntUint32V(v map[int]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint64V(rv2i(rv).(map[int]uint64), e) -} -func (_ fastpathT) EncMapIntUint64V(v map[int]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUintptrV(rv2i(rv).(map[int]uintptr), e) -} -func (_ fastpathT) EncMapIntUintptrV(v map[int]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntIntV(rv2i(rv).(map[int]int), e) -} -func (_ fastpathT) EncMapIntIntV(v map[int]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt8V(rv2i(rv).(map[int]int8), e) -} -func (_ fastpathT) EncMapIntInt8V(v map[int]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt16V(rv2i(rv).(map[int]int16), e) -} -func (_ fastpathT) EncMapIntInt16V(v map[int]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt32V(rv2i(rv).(map[int]int32), e) -} -func (_ fastpathT) EncMapIntInt32V(v map[int]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt64V(rv2i(rv).(map[int]int64), e) -} -func (_ fastpathT) EncMapIntInt64V(v map[int]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntFloat32V(rv2i(rv).(map[int]float32), e) -} -func (_ fastpathT) EncMapIntFloat32V(v map[int]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[int(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntFloat64V(rv2i(rv).(map[int]float64), e) -} -func (_ fastpathT) EncMapIntFloat64V(v map[int]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[int(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntBoolV(rv2i(rv).(map[int]bool), e) -} -func (_ fastpathT) EncMapIntBoolV(v map[int]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[int(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8IntfV(rv2i(rv).(map[int8]interface{}), e) -} -func (_ fastpathT) EncMapInt8IntfV(v map[int8]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8StringV(rv2i(rv).(map[int8]string), e) -} -func (_ fastpathT) EncMapInt8StringV(v map[int8]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[int8(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[int8(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8UintV(rv2i(rv).(map[int8]uint), e) -} -func (_ fastpathT) EncMapInt8UintV(v map[int8]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint8V(rv2i(rv).(map[int8]uint8), e) -} -func (_ fastpathT) EncMapInt8Uint8V(v map[int8]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint16V(rv2i(rv).(map[int8]uint16), e) -} -func (_ fastpathT) EncMapInt8Uint16V(v map[int8]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint32V(rv2i(rv).(map[int8]uint32), e) -} -func (_ fastpathT) EncMapInt8Uint32V(v map[int8]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint64V(rv2i(rv).(map[int8]uint64), e) -} -func (_ fastpathT) EncMapInt8Uint64V(v map[int8]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8UintptrV(rv2i(rv).(map[int8]uintptr), e) -} -func (_ fastpathT) EncMapInt8UintptrV(v map[int8]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8IntV(rv2i(rv).(map[int8]int), e) -} -func (_ fastpathT) EncMapInt8IntV(v map[int8]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int8V(rv2i(rv).(map[int8]int8), e) -} -func (_ fastpathT) EncMapInt8Int8V(v map[int8]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int16V(rv2i(rv).(map[int8]int16), e) -} -func (_ fastpathT) EncMapInt8Int16V(v map[int8]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int32V(rv2i(rv).(map[int8]int32), e) -} -func (_ fastpathT) EncMapInt8Int32V(v map[int8]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int64V(rv2i(rv).(map[int8]int64), e) -} -func (_ fastpathT) EncMapInt8Int64V(v map[int8]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Float32V(rv2i(rv).(map[int8]float32), e) -} -func (_ fastpathT) EncMapInt8Float32V(v map[int8]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[int8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Float64V(rv2i(rv).(map[int8]float64), e) -} -func (_ fastpathT) EncMapInt8Float64V(v map[int8]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[int8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8BoolV(rv2i(rv).(map[int8]bool), e) -} -func (_ fastpathT) EncMapInt8BoolV(v map[int8]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int8(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[int8(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16IntfV(rv2i(rv).(map[int16]interface{}), e) -} -func (_ fastpathT) EncMapInt16IntfV(v map[int16]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16StringV(rv2i(rv).(map[int16]string), e) -} -func (_ fastpathT) EncMapInt16StringV(v map[int16]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[int16(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[int16(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16UintV(rv2i(rv).(map[int16]uint), e) -} -func (_ fastpathT) EncMapInt16UintV(v map[int16]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint8V(rv2i(rv).(map[int16]uint8), e) -} -func (_ fastpathT) EncMapInt16Uint8V(v map[int16]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint16V(rv2i(rv).(map[int16]uint16), e) -} -func (_ fastpathT) EncMapInt16Uint16V(v map[int16]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint32V(rv2i(rv).(map[int16]uint32), e) -} -func (_ fastpathT) EncMapInt16Uint32V(v map[int16]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint64V(rv2i(rv).(map[int16]uint64), e) -} -func (_ fastpathT) EncMapInt16Uint64V(v map[int16]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16UintptrV(rv2i(rv).(map[int16]uintptr), e) -} -func (_ fastpathT) EncMapInt16UintptrV(v map[int16]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16IntV(rv2i(rv).(map[int16]int), e) -} -func (_ fastpathT) EncMapInt16IntV(v map[int16]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int8V(rv2i(rv).(map[int16]int8), e) -} -func (_ fastpathT) EncMapInt16Int8V(v map[int16]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int16V(rv2i(rv).(map[int16]int16), e) -} -func (_ fastpathT) EncMapInt16Int16V(v map[int16]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int32V(rv2i(rv).(map[int16]int32), e) -} -func (_ fastpathT) EncMapInt16Int32V(v map[int16]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int64V(rv2i(rv).(map[int16]int64), e) -} -func (_ fastpathT) EncMapInt16Int64V(v map[int16]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Float32V(rv2i(rv).(map[int16]float32), e) -} -func (_ fastpathT) EncMapInt16Float32V(v map[int16]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[int16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Float64V(rv2i(rv).(map[int16]float64), e) -} -func (_ fastpathT) EncMapInt16Float64V(v map[int16]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[int16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16BoolV(rv2i(rv).(map[int16]bool), e) -} -func (_ fastpathT) EncMapInt16BoolV(v map[int16]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int16(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[int16(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32IntfV(rv2i(rv).(map[int32]interface{}), e) -} -func (_ fastpathT) EncMapInt32IntfV(v map[int32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32StringV(rv2i(rv).(map[int32]string), e) -} -func (_ fastpathT) EncMapInt32StringV(v map[int32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[int32(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[int32(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32UintV(rv2i(rv).(map[int32]uint), e) -} -func (_ fastpathT) EncMapInt32UintV(v map[int32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint8V(rv2i(rv).(map[int32]uint8), e) -} -func (_ fastpathT) EncMapInt32Uint8V(v map[int32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint16V(rv2i(rv).(map[int32]uint16), e) -} -func (_ fastpathT) EncMapInt32Uint16V(v map[int32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint32V(rv2i(rv).(map[int32]uint32), e) -} -func (_ fastpathT) EncMapInt32Uint32V(v map[int32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint64V(rv2i(rv).(map[int32]uint64), e) -} -func (_ fastpathT) EncMapInt32Uint64V(v map[int32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32UintptrV(rv2i(rv).(map[int32]uintptr), e) -} -func (_ fastpathT) EncMapInt32UintptrV(v map[int32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32IntV(rv2i(rv).(map[int32]int), e) -} -func (_ fastpathT) EncMapInt32IntV(v map[int32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int8V(rv2i(rv).(map[int32]int8), e) -} -func (_ fastpathT) EncMapInt32Int8V(v map[int32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int16V(rv2i(rv).(map[int32]int16), e) -} -func (_ fastpathT) EncMapInt32Int16V(v map[int32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int32V(rv2i(rv).(map[int32]int32), e) -} -func (_ fastpathT) EncMapInt32Int32V(v map[int32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int64V(rv2i(rv).(map[int32]int64), e) -} -func (_ fastpathT) EncMapInt32Int64V(v map[int32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Float32V(rv2i(rv).(map[int32]float32), e) -} -func (_ fastpathT) EncMapInt32Float32V(v map[int32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[int32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Float64V(rv2i(rv).(map[int32]float64), e) -} -func (_ fastpathT) EncMapInt32Float64V(v map[int32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[int32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32BoolV(rv2i(rv).(map[int32]bool), e) -} -func (_ fastpathT) EncMapInt32BoolV(v map[int32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int32(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[int32(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64IntfV(rv2i(rv).(map[int64]interface{}), e) -} -func (_ fastpathT) EncMapInt64IntfV(v map[int64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64StringV(rv2i(rv).(map[int64]string), e) -} -func (_ fastpathT) EncMapInt64StringV(v map[int64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[int64(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[int64(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64UintV(rv2i(rv).(map[int64]uint), e) -} -func (_ fastpathT) EncMapInt64UintV(v map[int64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint8V(rv2i(rv).(map[int64]uint8), e) -} -func (_ fastpathT) EncMapInt64Uint8V(v map[int64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint16V(rv2i(rv).(map[int64]uint16), e) -} -func (_ fastpathT) EncMapInt64Uint16V(v map[int64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint32V(rv2i(rv).(map[int64]uint32), e) -} -func (_ fastpathT) EncMapInt64Uint32V(v map[int64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint64V(rv2i(rv).(map[int64]uint64), e) -} -func (_ fastpathT) EncMapInt64Uint64V(v map[int64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64UintptrV(rv2i(rv).(map[int64]uintptr), e) -} -func (_ fastpathT) EncMapInt64UintptrV(v map[int64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[int64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64IntV(rv2i(rv).(map[int64]int), e) -} -func (_ fastpathT) EncMapInt64IntV(v map[int64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int8V(rv2i(rv).(map[int64]int8), e) -} -func (_ fastpathT) EncMapInt64Int8V(v map[int64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int16V(rv2i(rv).(map[int64]int16), e) -} -func (_ fastpathT) EncMapInt64Int16V(v map[int64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int32V(rv2i(rv).(map[int64]int32), e) -} -func (_ fastpathT) EncMapInt64Int32V(v map[int64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int64V(rv2i(rv).(map[int64]int64), e) -} -func (_ fastpathT) EncMapInt64Int64V(v map[int64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Float32V(rv2i(rv).(map[int64]float32), e) -} -func (_ fastpathT) EncMapInt64Float32V(v map[int64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[int64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Float64V(rv2i(rv).(map[int64]float64), e) -} -func (_ fastpathT) EncMapInt64Float64V(v map[int64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[int64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64BoolV(rv2i(rv).(map[int64]bool), e) -} -func (_ fastpathT) EncMapInt64BoolV(v map[int64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i uint - for k := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(int64(k2))) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[int64(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeInt(int64(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolIntfV(rv2i(rv).(map[bool]interface{}), e) -} -func (_ fastpathT) EncMapBoolIntfV(v map[bool]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[bool(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolStringV(rv2i(rv).(map[bool]string), e) -} -func (_ fastpathT) EncMapBoolStringV(v map[bool]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v[bool(k2)])) - } else { - ee.EncodeStringEnc(cUTF8, v[bool(k2)]) - } - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - if e.h.StringToRaw { - ee.EncodeStringBytesRaw(bytesView(v2)) - } else { - ee.EncodeStringEnc(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUintV(rv2i(rv).(map[bool]uint), e) -} -func (_ fastpathT) EncMapBoolUintV(v map[bool]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint8V(rv2i(rv).(map[bool]uint8), e) -} -func (_ fastpathT) EncMapBoolUint8V(v map[bool]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint16V(rv2i(rv).(map[bool]uint16), e) -} -func (_ fastpathT) EncMapBoolUint16V(v map[bool]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint32V(rv2i(rv).(map[bool]uint32), e) -} -func (_ fastpathT) EncMapBoolUint32V(v map[bool]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint64V(rv2i(rv).(map[bool]uint64), e) -} -func (_ fastpathT) EncMapBoolUint64V(v map[bool]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUintptrV(rv2i(rv).(map[bool]uintptr), e) -} -func (_ fastpathT) EncMapBoolUintptrV(v map[bool]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - e.encode(v[bool(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolIntV(rv2i(rv).(map[bool]int), e) -} -func (_ fastpathT) EncMapBoolIntV(v map[bool]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt8V(rv2i(rv).(map[bool]int8), e) -} -func (_ fastpathT) EncMapBoolInt8V(v map[bool]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt16V(rv2i(rv).(map[bool]int16), e) -} -func (_ fastpathT) EncMapBoolInt16V(v map[bool]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt32V(rv2i(rv).(map[bool]int32), e) -} -func (_ fastpathT) EncMapBoolInt32V(v map[bool]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt64V(rv2i(rv).(map[bool]int64), e) -} -func (_ fastpathT) EncMapBoolInt64V(v map[bool]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolFloat32V(rv2i(rv).(map[bool]float32), e) -} -func (_ fastpathT) EncMapBoolFloat32V(v map[bool]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v[bool(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolFloat64V(rv2i(rv).(map[bool]float64), e) -} -func (_ fastpathT) EncMapBoolFloat64V(v map[bool]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v[bool(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolBoolV(rv2i(rv).(map[bool]bool), e) -} -func (_ fastpathT) EncMapBoolBoolV(v map[bool]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i uint - for k := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - for _, k2 := range v2 { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(bool(k2)) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v[bool(k2)]) - } - } else { - for k2, v2 := range v { - if esep { - ee.WriteMapElemKey() - } - ee.EncodeBool(k2) - if esep { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -// -- decode - -// -- -- fast path type switch -func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { - var changed bool - switch v := iv.(type) { - - case []interface{}: - var v2 []interface{} - v2, changed = fastpathTV.DecSliceIntfV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]interface{}: - var v2 []interface{} - v2, changed = fastpathTV.DecSliceIntfV(*v, true, d) - if changed { - *v = v2 - } - case []string: - var v2 []string - v2, changed = fastpathTV.DecSliceStringV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]string: - var v2 []string - v2, changed = fastpathTV.DecSliceStringV(*v, true, d) - if changed { - *v = v2 - } - case []float32: - var v2 []float32 - v2, changed = fastpathTV.DecSliceFloat32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]float32: - var v2 []float32 - v2, changed = fastpathTV.DecSliceFloat32V(*v, true, d) - if changed { - *v = v2 - } - case []float64: - var v2 []float64 - v2, changed = fastpathTV.DecSliceFloat64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]float64: - var v2 []float64 - v2, changed = fastpathTV.DecSliceFloat64V(*v, true, d) - if changed { - *v = v2 - } - case []uint: - var v2 []uint - v2, changed = fastpathTV.DecSliceUintV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint: - var v2 []uint - v2, changed = fastpathTV.DecSliceUintV(*v, true, d) - if changed { - *v = v2 - } - case []uint16: - var v2 []uint16 - v2, changed = fastpathTV.DecSliceUint16V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint16: - var v2 []uint16 - v2, changed = fastpathTV.DecSliceUint16V(*v, true, d) - if changed { - *v = v2 - } - case []uint32: - var v2 []uint32 - v2, changed = fastpathTV.DecSliceUint32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint32: - var v2 []uint32 - v2, changed = fastpathTV.DecSliceUint32V(*v, true, d) - if changed { - *v = v2 - } - case []uint64: - var v2 []uint64 - v2, changed = fastpathTV.DecSliceUint64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint64: - var v2 []uint64 - v2, changed = fastpathTV.DecSliceUint64V(*v, true, d) - if changed { - *v = v2 - } - case []uintptr: - var v2 []uintptr - v2, changed = fastpathTV.DecSliceUintptrV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uintptr: - var v2 []uintptr - v2, changed = fastpathTV.DecSliceUintptrV(*v, true, d) - if changed { - *v = v2 - } - case []int: - var v2 []int - v2, changed = fastpathTV.DecSliceIntV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int: - var v2 []int - v2, changed = fastpathTV.DecSliceIntV(*v, true, d) - if changed { - *v = v2 - } - case []int8: - var v2 []int8 - v2, changed = fastpathTV.DecSliceInt8V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int8: - var v2 []int8 - v2, changed = fastpathTV.DecSliceInt8V(*v, true, d) - if changed { - *v = v2 - } - case []int16: - var v2 []int16 - v2, changed = fastpathTV.DecSliceInt16V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int16: - var v2 []int16 - v2, changed = fastpathTV.DecSliceInt16V(*v, true, d) - if changed { - *v = v2 - } - case []int32: - var v2 []int32 - v2, changed = fastpathTV.DecSliceInt32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int32: - var v2 []int32 - v2, changed = fastpathTV.DecSliceInt32V(*v, true, d) - if changed { - *v = v2 - } - case []int64: - var v2 []int64 - v2, changed = fastpathTV.DecSliceInt64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int64: - var v2 []int64 - v2, changed = fastpathTV.DecSliceInt64V(*v, true, d) - if changed { - *v = v2 - } - case []bool: - var v2 []bool - v2, changed = fastpathTV.DecSliceBoolV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]bool: - var v2 []bool - v2, changed = fastpathTV.DecSliceBoolV(*v, true, d) - if changed { - *v = v2 - } - - case map[interface{}]interface{}: - fastpathTV.DecMapIntfIntfV(v, false, d) - case *map[interface{}]interface{}: - var v2 map[interface{}]interface{} - v2, changed = fastpathTV.DecMapIntfIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]string: - fastpathTV.DecMapIntfStringV(v, false, d) - case *map[interface{}]string: - var v2 map[interface{}]string - v2, changed = fastpathTV.DecMapIntfStringV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint: - fastpathTV.DecMapIntfUintV(v, false, d) - case *map[interface{}]uint: - var v2 map[interface{}]uint - v2, changed = fastpathTV.DecMapIntfUintV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint8: - fastpathTV.DecMapIntfUint8V(v, false, d) - case *map[interface{}]uint8: - var v2 map[interface{}]uint8 - v2, changed = fastpathTV.DecMapIntfUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint16: - fastpathTV.DecMapIntfUint16V(v, false, d) - case *map[interface{}]uint16: - var v2 map[interface{}]uint16 - v2, changed = fastpathTV.DecMapIntfUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint32: - fastpathTV.DecMapIntfUint32V(v, false, d) - case *map[interface{}]uint32: - var v2 map[interface{}]uint32 - v2, changed = fastpathTV.DecMapIntfUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint64: - fastpathTV.DecMapIntfUint64V(v, false, d) - case *map[interface{}]uint64: - var v2 map[interface{}]uint64 - v2, changed = fastpathTV.DecMapIntfUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uintptr: - fastpathTV.DecMapIntfUintptrV(v, false, d) - case *map[interface{}]uintptr: - var v2 map[interface{}]uintptr - v2, changed = fastpathTV.DecMapIntfUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int: - fastpathTV.DecMapIntfIntV(v, false, d) - case *map[interface{}]int: - var v2 map[interface{}]int - v2, changed = fastpathTV.DecMapIntfIntV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int8: - fastpathTV.DecMapIntfInt8V(v, false, d) - case *map[interface{}]int8: - var v2 map[interface{}]int8 - v2, changed = fastpathTV.DecMapIntfInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int16: - fastpathTV.DecMapIntfInt16V(v, false, d) - case *map[interface{}]int16: - var v2 map[interface{}]int16 - v2, changed = fastpathTV.DecMapIntfInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int32: - fastpathTV.DecMapIntfInt32V(v, false, d) - case *map[interface{}]int32: - var v2 map[interface{}]int32 - v2, changed = fastpathTV.DecMapIntfInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int64: - fastpathTV.DecMapIntfInt64V(v, false, d) - case *map[interface{}]int64: - var v2 map[interface{}]int64 - v2, changed = fastpathTV.DecMapIntfInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]float32: - fastpathTV.DecMapIntfFloat32V(v, false, d) - case *map[interface{}]float32: - var v2 map[interface{}]float32 - v2, changed = fastpathTV.DecMapIntfFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]float64: - fastpathTV.DecMapIntfFloat64V(v, false, d) - case *map[interface{}]float64: - var v2 map[interface{}]float64 - v2, changed = fastpathTV.DecMapIntfFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]bool: - fastpathTV.DecMapIntfBoolV(v, false, d) - case *map[interface{}]bool: - var v2 map[interface{}]bool - v2, changed = fastpathTV.DecMapIntfBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[string]interface{}: - fastpathTV.DecMapStringIntfV(v, false, d) - case *map[string]interface{}: - var v2 map[string]interface{} - v2, changed = fastpathTV.DecMapStringIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[string]string: - fastpathTV.DecMapStringStringV(v, false, d) - case *map[string]string: - var v2 map[string]string - v2, changed = fastpathTV.DecMapStringStringV(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint: - fastpathTV.DecMapStringUintV(v, false, d) - case *map[string]uint: - var v2 map[string]uint - v2, changed = fastpathTV.DecMapStringUintV(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint8: - fastpathTV.DecMapStringUint8V(v, false, d) - case *map[string]uint8: - var v2 map[string]uint8 - v2, changed = fastpathTV.DecMapStringUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint16: - fastpathTV.DecMapStringUint16V(v, false, d) - case *map[string]uint16: - var v2 map[string]uint16 - v2, changed = fastpathTV.DecMapStringUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint32: - fastpathTV.DecMapStringUint32V(v, false, d) - case *map[string]uint32: - var v2 map[string]uint32 - v2, changed = fastpathTV.DecMapStringUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint64: - fastpathTV.DecMapStringUint64V(v, false, d) - case *map[string]uint64: - var v2 map[string]uint64 - v2, changed = fastpathTV.DecMapStringUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uintptr: - fastpathTV.DecMapStringUintptrV(v, false, d) - case *map[string]uintptr: - var v2 map[string]uintptr - v2, changed = fastpathTV.DecMapStringUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[string]int: - fastpathTV.DecMapStringIntV(v, false, d) - case *map[string]int: - var v2 map[string]int - v2, changed = fastpathTV.DecMapStringIntV(*v, true, d) - if changed { - *v = v2 - } - case map[string]int8: - fastpathTV.DecMapStringInt8V(v, false, d) - case *map[string]int8: - var v2 map[string]int8 - v2, changed = fastpathTV.DecMapStringInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int16: - fastpathTV.DecMapStringInt16V(v, false, d) - case *map[string]int16: - var v2 map[string]int16 - v2, changed = fastpathTV.DecMapStringInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int32: - fastpathTV.DecMapStringInt32V(v, false, d) - case *map[string]int32: - var v2 map[string]int32 - v2, changed = fastpathTV.DecMapStringInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int64: - fastpathTV.DecMapStringInt64V(v, false, d) - case *map[string]int64: - var v2 map[string]int64 - v2, changed = fastpathTV.DecMapStringInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]float32: - fastpathTV.DecMapStringFloat32V(v, false, d) - case *map[string]float32: - var v2 map[string]float32 - v2, changed = fastpathTV.DecMapStringFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]float64: - fastpathTV.DecMapStringFloat64V(v, false, d) - case *map[string]float64: - var v2 map[string]float64 - v2, changed = fastpathTV.DecMapStringFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]bool: - fastpathTV.DecMapStringBoolV(v, false, d) - case *map[string]bool: - var v2 map[string]bool - v2, changed = fastpathTV.DecMapStringBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]interface{}: - fastpathTV.DecMapFloat32IntfV(v, false, d) - case *map[float32]interface{}: - var v2 map[float32]interface{} - v2, changed = fastpathTV.DecMapFloat32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]string: - fastpathTV.DecMapFloat32StringV(v, false, d) - case *map[float32]string: - var v2 map[float32]string - v2, changed = fastpathTV.DecMapFloat32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint: - fastpathTV.DecMapFloat32UintV(v, false, d) - case *map[float32]uint: - var v2 map[float32]uint - v2, changed = fastpathTV.DecMapFloat32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint8: - fastpathTV.DecMapFloat32Uint8V(v, false, d) - case *map[float32]uint8: - var v2 map[float32]uint8 - v2, changed = fastpathTV.DecMapFloat32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint16: - fastpathTV.DecMapFloat32Uint16V(v, false, d) - case *map[float32]uint16: - var v2 map[float32]uint16 - v2, changed = fastpathTV.DecMapFloat32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint32: - fastpathTV.DecMapFloat32Uint32V(v, false, d) - case *map[float32]uint32: - var v2 map[float32]uint32 - v2, changed = fastpathTV.DecMapFloat32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint64: - fastpathTV.DecMapFloat32Uint64V(v, false, d) - case *map[float32]uint64: - var v2 map[float32]uint64 - v2, changed = fastpathTV.DecMapFloat32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uintptr: - fastpathTV.DecMapFloat32UintptrV(v, false, d) - case *map[float32]uintptr: - var v2 map[float32]uintptr - v2, changed = fastpathTV.DecMapFloat32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int: - fastpathTV.DecMapFloat32IntV(v, false, d) - case *map[float32]int: - var v2 map[float32]int - v2, changed = fastpathTV.DecMapFloat32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int8: - fastpathTV.DecMapFloat32Int8V(v, false, d) - case *map[float32]int8: - var v2 map[float32]int8 - v2, changed = fastpathTV.DecMapFloat32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int16: - fastpathTV.DecMapFloat32Int16V(v, false, d) - case *map[float32]int16: - var v2 map[float32]int16 - v2, changed = fastpathTV.DecMapFloat32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int32: - fastpathTV.DecMapFloat32Int32V(v, false, d) - case *map[float32]int32: - var v2 map[float32]int32 - v2, changed = fastpathTV.DecMapFloat32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int64: - fastpathTV.DecMapFloat32Int64V(v, false, d) - case *map[float32]int64: - var v2 map[float32]int64 - v2, changed = fastpathTV.DecMapFloat32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]float32: - fastpathTV.DecMapFloat32Float32V(v, false, d) - case *map[float32]float32: - var v2 map[float32]float32 - v2, changed = fastpathTV.DecMapFloat32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]float64: - fastpathTV.DecMapFloat32Float64V(v, false, d) - case *map[float32]float64: - var v2 map[float32]float64 - v2, changed = fastpathTV.DecMapFloat32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]bool: - fastpathTV.DecMapFloat32BoolV(v, false, d) - case *map[float32]bool: - var v2 map[float32]bool - v2, changed = fastpathTV.DecMapFloat32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]interface{}: - fastpathTV.DecMapFloat64IntfV(v, false, d) - case *map[float64]interface{}: - var v2 map[float64]interface{} - v2, changed = fastpathTV.DecMapFloat64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]string: - fastpathTV.DecMapFloat64StringV(v, false, d) - case *map[float64]string: - var v2 map[float64]string - v2, changed = fastpathTV.DecMapFloat64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint: - fastpathTV.DecMapFloat64UintV(v, false, d) - case *map[float64]uint: - var v2 map[float64]uint - v2, changed = fastpathTV.DecMapFloat64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint8: - fastpathTV.DecMapFloat64Uint8V(v, false, d) - case *map[float64]uint8: - var v2 map[float64]uint8 - v2, changed = fastpathTV.DecMapFloat64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint16: - fastpathTV.DecMapFloat64Uint16V(v, false, d) - case *map[float64]uint16: - var v2 map[float64]uint16 - v2, changed = fastpathTV.DecMapFloat64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint32: - fastpathTV.DecMapFloat64Uint32V(v, false, d) - case *map[float64]uint32: - var v2 map[float64]uint32 - v2, changed = fastpathTV.DecMapFloat64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint64: - fastpathTV.DecMapFloat64Uint64V(v, false, d) - case *map[float64]uint64: - var v2 map[float64]uint64 - v2, changed = fastpathTV.DecMapFloat64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uintptr: - fastpathTV.DecMapFloat64UintptrV(v, false, d) - case *map[float64]uintptr: - var v2 map[float64]uintptr - v2, changed = fastpathTV.DecMapFloat64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int: - fastpathTV.DecMapFloat64IntV(v, false, d) - case *map[float64]int: - var v2 map[float64]int - v2, changed = fastpathTV.DecMapFloat64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int8: - fastpathTV.DecMapFloat64Int8V(v, false, d) - case *map[float64]int8: - var v2 map[float64]int8 - v2, changed = fastpathTV.DecMapFloat64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int16: - fastpathTV.DecMapFloat64Int16V(v, false, d) - case *map[float64]int16: - var v2 map[float64]int16 - v2, changed = fastpathTV.DecMapFloat64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int32: - fastpathTV.DecMapFloat64Int32V(v, false, d) - case *map[float64]int32: - var v2 map[float64]int32 - v2, changed = fastpathTV.DecMapFloat64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int64: - fastpathTV.DecMapFloat64Int64V(v, false, d) - case *map[float64]int64: - var v2 map[float64]int64 - v2, changed = fastpathTV.DecMapFloat64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]float32: - fastpathTV.DecMapFloat64Float32V(v, false, d) - case *map[float64]float32: - var v2 map[float64]float32 - v2, changed = fastpathTV.DecMapFloat64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]float64: - fastpathTV.DecMapFloat64Float64V(v, false, d) - case *map[float64]float64: - var v2 map[float64]float64 - v2, changed = fastpathTV.DecMapFloat64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]bool: - fastpathTV.DecMapFloat64BoolV(v, false, d) - case *map[float64]bool: - var v2 map[float64]bool - v2, changed = fastpathTV.DecMapFloat64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]interface{}: - fastpathTV.DecMapUintIntfV(v, false, d) - case *map[uint]interface{}: - var v2 map[uint]interface{} - v2, changed = fastpathTV.DecMapUintIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]string: - fastpathTV.DecMapUintStringV(v, false, d) - case *map[uint]string: - var v2 map[uint]string - v2, changed = fastpathTV.DecMapUintStringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint: - fastpathTV.DecMapUintUintV(v, false, d) - case *map[uint]uint: - var v2 map[uint]uint - v2, changed = fastpathTV.DecMapUintUintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint8: - fastpathTV.DecMapUintUint8V(v, false, d) - case *map[uint]uint8: - var v2 map[uint]uint8 - v2, changed = fastpathTV.DecMapUintUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint16: - fastpathTV.DecMapUintUint16V(v, false, d) - case *map[uint]uint16: - var v2 map[uint]uint16 - v2, changed = fastpathTV.DecMapUintUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint32: - fastpathTV.DecMapUintUint32V(v, false, d) - case *map[uint]uint32: - var v2 map[uint]uint32 - v2, changed = fastpathTV.DecMapUintUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint64: - fastpathTV.DecMapUintUint64V(v, false, d) - case *map[uint]uint64: - var v2 map[uint]uint64 - v2, changed = fastpathTV.DecMapUintUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uintptr: - fastpathTV.DecMapUintUintptrV(v, false, d) - case *map[uint]uintptr: - var v2 map[uint]uintptr - v2, changed = fastpathTV.DecMapUintUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int: - fastpathTV.DecMapUintIntV(v, false, d) - case *map[uint]int: - var v2 map[uint]int - v2, changed = fastpathTV.DecMapUintIntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int8: - fastpathTV.DecMapUintInt8V(v, false, d) - case *map[uint]int8: - var v2 map[uint]int8 - v2, changed = fastpathTV.DecMapUintInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int16: - fastpathTV.DecMapUintInt16V(v, false, d) - case *map[uint]int16: - var v2 map[uint]int16 - v2, changed = fastpathTV.DecMapUintInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int32: - fastpathTV.DecMapUintInt32V(v, false, d) - case *map[uint]int32: - var v2 map[uint]int32 - v2, changed = fastpathTV.DecMapUintInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int64: - fastpathTV.DecMapUintInt64V(v, false, d) - case *map[uint]int64: - var v2 map[uint]int64 - v2, changed = fastpathTV.DecMapUintInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]float32: - fastpathTV.DecMapUintFloat32V(v, false, d) - case *map[uint]float32: - var v2 map[uint]float32 - v2, changed = fastpathTV.DecMapUintFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]float64: - fastpathTV.DecMapUintFloat64V(v, false, d) - case *map[uint]float64: - var v2 map[uint]float64 - v2, changed = fastpathTV.DecMapUintFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]bool: - fastpathTV.DecMapUintBoolV(v, false, d) - case *map[uint]bool: - var v2 map[uint]bool - v2, changed = fastpathTV.DecMapUintBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]interface{}: - fastpathTV.DecMapUint8IntfV(v, false, d) - case *map[uint8]interface{}: - var v2 map[uint8]interface{} - v2, changed = fastpathTV.DecMapUint8IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]string: - fastpathTV.DecMapUint8StringV(v, false, d) - case *map[uint8]string: - var v2 map[uint8]string - v2, changed = fastpathTV.DecMapUint8StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint: - fastpathTV.DecMapUint8UintV(v, false, d) - case *map[uint8]uint: - var v2 map[uint8]uint - v2, changed = fastpathTV.DecMapUint8UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint8: - fastpathTV.DecMapUint8Uint8V(v, false, d) - case *map[uint8]uint8: - var v2 map[uint8]uint8 - v2, changed = fastpathTV.DecMapUint8Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint16: - fastpathTV.DecMapUint8Uint16V(v, false, d) - case *map[uint8]uint16: - var v2 map[uint8]uint16 - v2, changed = fastpathTV.DecMapUint8Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint32: - fastpathTV.DecMapUint8Uint32V(v, false, d) - case *map[uint8]uint32: - var v2 map[uint8]uint32 - v2, changed = fastpathTV.DecMapUint8Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint64: - fastpathTV.DecMapUint8Uint64V(v, false, d) - case *map[uint8]uint64: - var v2 map[uint8]uint64 - v2, changed = fastpathTV.DecMapUint8Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uintptr: - fastpathTV.DecMapUint8UintptrV(v, false, d) - case *map[uint8]uintptr: - var v2 map[uint8]uintptr - v2, changed = fastpathTV.DecMapUint8UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int: - fastpathTV.DecMapUint8IntV(v, false, d) - case *map[uint8]int: - var v2 map[uint8]int - v2, changed = fastpathTV.DecMapUint8IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int8: - fastpathTV.DecMapUint8Int8V(v, false, d) - case *map[uint8]int8: - var v2 map[uint8]int8 - v2, changed = fastpathTV.DecMapUint8Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int16: - fastpathTV.DecMapUint8Int16V(v, false, d) - case *map[uint8]int16: - var v2 map[uint8]int16 - v2, changed = fastpathTV.DecMapUint8Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int32: - fastpathTV.DecMapUint8Int32V(v, false, d) - case *map[uint8]int32: - var v2 map[uint8]int32 - v2, changed = fastpathTV.DecMapUint8Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int64: - fastpathTV.DecMapUint8Int64V(v, false, d) - case *map[uint8]int64: - var v2 map[uint8]int64 - v2, changed = fastpathTV.DecMapUint8Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]float32: - fastpathTV.DecMapUint8Float32V(v, false, d) - case *map[uint8]float32: - var v2 map[uint8]float32 - v2, changed = fastpathTV.DecMapUint8Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]float64: - fastpathTV.DecMapUint8Float64V(v, false, d) - case *map[uint8]float64: - var v2 map[uint8]float64 - v2, changed = fastpathTV.DecMapUint8Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]bool: - fastpathTV.DecMapUint8BoolV(v, false, d) - case *map[uint8]bool: - var v2 map[uint8]bool - v2, changed = fastpathTV.DecMapUint8BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]interface{}: - fastpathTV.DecMapUint16IntfV(v, false, d) - case *map[uint16]interface{}: - var v2 map[uint16]interface{} - v2, changed = fastpathTV.DecMapUint16IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]string: - fastpathTV.DecMapUint16StringV(v, false, d) - case *map[uint16]string: - var v2 map[uint16]string - v2, changed = fastpathTV.DecMapUint16StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint: - fastpathTV.DecMapUint16UintV(v, false, d) - case *map[uint16]uint: - var v2 map[uint16]uint - v2, changed = fastpathTV.DecMapUint16UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint8: - fastpathTV.DecMapUint16Uint8V(v, false, d) - case *map[uint16]uint8: - var v2 map[uint16]uint8 - v2, changed = fastpathTV.DecMapUint16Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint16: - fastpathTV.DecMapUint16Uint16V(v, false, d) - case *map[uint16]uint16: - var v2 map[uint16]uint16 - v2, changed = fastpathTV.DecMapUint16Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint32: - fastpathTV.DecMapUint16Uint32V(v, false, d) - case *map[uint16]uint32: - var v2 map[uint16]uint32 - v2, changed = fastpathTV.DecMapUint16Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint64: - fastpathTV.DecMapUint16Uint64V(v, false, d) - case *map[uint16]uint64: - var v2 map[uint16]uint64 - v2, changed = fastpathTV.DecMapUint16Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uintptr: - fastpathTV.DecMapUint16UintptrV(v, false, d) - case *map[uint16]uintptr: - var v2 map[uint16]uintptr - v2, changed = fastpathTV.DecMapUint16UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int: - fastpathTV.DecMapUint16IntV(v, false, d) - case *map[uint16]int: - var v2 map[uint16]int - v2, changed = fastpathTV.DecMapUint16IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int8: - fastpathTV.DecMapUint16Int8V(v, false, d) - case *map[uint16]int8: - var v2 map[uint16]int8 - v2, changed = fastpathTV.DecMapUint16Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int16: - fastpathTV.DecMapUint16Int16V(v, false, d) - case *map[uint16]int16: - var v2 map[uint16]int16 - v2, changed = fastpathTV.DecMapUint16Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int32: - fastpathTV.DecMapUint16Int32V(v, false, d) - case *map[uint16]int32: - var v2 map[uint16]int32 - v2, changed = fastpathTV.DecMapUint16Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int64: - fastpathTV.DecMapUint16Int64V(v, false, d) - case *map[uint16]int64: - var v2 map[uint16]int64 - v2, changed = fastpathTV.DecMapUint16Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]float32: - fastpathTV.DecMapUint16Float32V(v, false, d) - case *map[uint16]float32: - var v2 map[uint16]float32 - v2, changed = fastpathTV.DecMapUint16Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]float64: - fastpathTV.DecMapUint16Float64V(v, false, d) - case *map[uint16]float64: - var v2 map[uint16]float64 - v2, changed = fastpathTV.DecMapUint16Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]bool: - fastpathTV.DecMapUint16BoolV(v, false, d) - case *map[uint16]bool: - var v2 map[uint16]bool - v2, changed = fastpathTV.DecMapUint16BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]interface{}: - fastpathTV.DecMapUint32IntfV(v, false, d) - case *map[uint32]interface{}: - var v2 map[uint32]interface{} - v2, changed = fastpathTV.DecMapUint32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]string: - fastpathTV.DecMapUint32StringV(v, false, d) - case *map[uint32]string: - var v2 map[uint32]string - v2, changed = fastpathTV.DecMapUint32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint: - fastpathTV.DecMapUint32UintV(v, false, d) - case *map[uint32]uint: - var v2 map[uint32]uint - v2, changed = fastpathTV.DecMapUint32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint8: - fastpathTV.DecMapUint32Uint8V(v, false, d) - case *map[uint32]uint8: - var v2 map[uint32]uint8 - v2, changed = fastpathTV.DecMapUint32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint16: - fastpathTV.DecMapUint32Uint16V(v, false, d) - case *map[uint32]uint16: - var v2 map[uint32]uint16 - v2, changed = fastpathTV.DecMapUint32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint32: - fastpathTV.DecMapUint32Uint32V(v, false, d) - case *map[uint32]uint32: - var v2 map[uint32]uint32 - v2, changed = fastpathTV.DecMapUint32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint64: - fastpathTV.DecMapUint32Uint64V(v, false, d) - case *map[uint32]uint64: - var v2 map[uint32]uint64 - v2, changed = fastpathTV.DecMapUint32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uintptr: - fastpathTV.DecMapUint32UintptrV(v, false, d) - case *map[uint32]uintptr: - var v2 map[uint32]uintptr - v2, changed = fastpathTV.DecMapUint32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int: - fastpathTV.DecMapUint32IntV(v, false, d) - case *map[uint32]int: - var v2 map[uint32]int - v2, changed = fastpathTV.DecMapUint32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int8: - fastpathTV.DecMapUint32Int8V(v, false, d) - case *map[uint32]int8: - var v2 map[uint32]int8 - v2, changed = fastpathTV.DecMapUint32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int16: - fastpathTV.DecMapUint32Int16V(v, false, d) - case *map[uint32]int16: - var v2 map[uint32]int16 - v2, changed = fastpathTV.DecMapUint32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int32: - fastpathTV.DecMapUint32Int32V(v, false, d) - case *map[uint32]int32: - var v2 map[uint32]int32 - v2, changed = fastpathTV.DecMapUint32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int64: - fastpathTV.DecMapUint32Int64V(v, false, d) - case *map[uint32]int64: - var v2 map[uint32]int64 - v2, changed = fastpathTV.DecMapUint32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]float32: - fastpathTV.DecMapUint32Float32V(v, false, d) - case *map[uint32]float32: - var v2 map[uint32]float32 - v2, changed = fastpathTV.DecMapUint32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]float64: - fastpathTV.DecMapUint32Float64V(v, false, d) - case *map[uint32]float64: - var v2 map[uint32]float64 - v2, changed = fastpathTV.DecMapUint32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]bool: - fastpathTV.DecMapUint32BoolV(v, false, d) - case *map[uint32]bool: - var v2 map[uint32]bool - v2, changed = fastpathTV.DecMapUint32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]interface{}: - fastpathTV.DecMapUint64IntfV(v, false, d) - case *map[uint64]interface{}: - var v2 map[uint64]interface{} - v2, changed = fastpathTV.DecMapUint64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]string: - fastpathTV.DecMapUint64StringV(v, false, d) - case *map[uint64]string: - var v2 map[uint64]string - v2, changed = fastpathTV.DecMapUint64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint: - fastpathTV.DecMapUint64UintV(v, false, d) - case *map[uint64]uint: - var v2 map[uint64]uint - v2, changed = fastpathTV.DecMapUint64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint8: - fastpathTV.DecMapUint64Uint8V(v, false, d) - case *map[uint64]uint8: - var v2 map[uint64]uint8 - v2, changed = fastpathTV.DecMapUint64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint16: - fastpathTV.DecMapUint64Uint16V(v, false, d) - case *map[uint64]uint16: - var v2 map[uint64]uint16 - v2, changed = fastpathTV.DecMapUint64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint32: - fastpathTV.DecMapUint64Uint32V(v, false, d) - case *map[uint64]uint32: - var v2 map[uint64]uint32 - v2, changed = fastpathTV.DecMapUint64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint64: - fastpathTV.DecMapUint64Uint64V(v, false, d) - case *map[uint64]uint64: - var v2 map[uint64]uint64 - v2, changed = fastpathTV.DecMapUint64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uintptr: - fastpathTV.DecMapUint64UintptrV(v, false, d) - case *map[uint64]uintptr: - var v2 map[uint64]uintptr - v2, changed = fastpathTV.DecMapUint64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int: - fastpathTV.DecMapUint64IntV(v, false, d) - case *map[uint64]int: - var v2 map[uint64]int - v2, changed = fastpathTV.DecMapUint64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int8: - fastpathTV.DecMapUint64Int8V(v, false, d) - case *map[uint64]int8: - var v2 map[uint64]int8 - v2, changed = fastpathTV.DecMapUint64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int16: - fastpathTV.DecMapUint64Int16V(v, false, d) - case *map[uint64]int16: - var v2 map[uint64]int16 - v2, changed = fastpathTV.DecMapUint64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int32: - fastpathTV.DecMapUint64Int32V(v, false, d) - case *map[uint64]int32: - var v2 map[uint64]int32 - v2, changed = fastpathTV.DecMapUint64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int64: - fastpathTV.DecMapUint64Int64V(v, false, d) - case *map[uint64]int64: - var v2 map[uint64]int64 - v2, changed = fastpathTV.DecMapUint64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]float32: - fastpathTV.DecMapUint64Float32V(v, false, d) - case *map[uint64]float32: - var v2 map[uint64]float32 - v2, changed = fastpathTV.DecMapUint64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]float64: - fastpathTV.DecMapUint64Float64V(v, false, d) - case *map[uint64]float64: - var v2 map[uint64]float64 - v2, changed = fastpathTV.DecMapUint64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]bool: - fastpathTV.DecMapUint64BoolV(v, false, d) - case *map[uint64]bool: - var v2 map[uint64]bool - v2, changed = fastpathTV.DecMapUint64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]interface{}: - fastpathTV.DecMapUintptrIntfV(v, false, d) - case *map[uintptr]interface{}: - var v2 map[uintptr]interface{} - v2, changed = fastpathTV.DecMapUintptrIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]string: - fastpathTV.DecMapUintptrStringV(v, false, d) - case *map[uintptr]string: - var v2 map[uintptr]string - v2, changed = fastpathTV.DecMapUintptrStringV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint: - fastpathTV.DecMapUintptrUintV(v, false, d) - case *map[uintptr]uint: - var v2 map[uintptr]uint - v2, changed = fastpathTV.DecMapUintptrUintV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint8: - fastpathTV.DecMapUintptrUint8V(v, false, d) - case *map[uintptr]uint8: - var v2 map[uintptr]uint8 - v2, changed = fastpathTV.DecMapUintptrUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint16: - fastpathTV.DecMapUintptrUint16V(v, false, d) - case *map[uintptr]uint16: - var v2 map[uintptr]uint16 - v2, changed = fastpathTV.DecMapUintptrUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint32: - fastpathTV.DecMapUintptrUint32V(v, false, d) - case *map[uintptr]uint32: - var v2 map[uintptr]uint32 - v2, changed = fastpathTV.DecMapUintptrUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint64: - fastpathTV.DecMapUintptrUint64V(v, false, d) - case *map[uintptr]uint64: - var v2 map[uintptr]uint64 - v2, changed = fastpathTV.DecMapUintptrUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uintptr: - fastpathTV.DecMapUintptrUintptrV(v, false, d) - case *map[uintptr]uintptr: - var v2 map[uintptr]uintptr - v2, changed = fastpathTV.DecMapUintptrUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int: - fastpathTV.DecMapUintptrIntV(v, false, d) - case *map[uintptr]int: - var v2 map[uintptr]int - v2, changed = fastpathTV.DecMapUintptrIntV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int8: - fastpathTV.DecMapUintptrInt8V(v, false, d) - case *map[uintptr]int8: - var v2 map[uintptr]int8 - v2, changed = fastpathTV.DecMapUintptrInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int16: - fastpathTV.DecMapUintptrInt16V(v, false, d) - case *map[uintptr]int16: - var v2 map[uintptr]int16 - v2, changed = fastpathTV.DecMapUintptrInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int32: - fastpathTV.DecMapUintptrInt32V(v, false, d) - case *map[uintptr]int32: - var v2 map[uintptr]int32 - v2, changed = fastpathTV.DecMapUintptrInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int64: - fastpathTV.DecMapUintptrInt64V(v, false, d) - case *map[uintptr]int64: - var v2 map[uintptr]int64 - v2, changed = fastpathTV.DecMapUintptrInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]float32: - fastpathTV.DecMapUintptrFloat32V(v, false, d) - case *map[uintptr]float32: - var v2 map[uintptr]float32 - v2, changed = fastpathTV.DecMapUintptrFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]float64: - fastpathTV.DecMapUintptrFloat64V(v, false, d) - case *map[uintptr]float64: - var v2 map[uintptr]float64 - v2, changed = fastpathTV.DecMapUintptrFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]bool: - fastpathTV.DecMapUintptrBoolV(v, false, d) - case *map[uintptr]bool: - var v2 map[uintptr]bool - v2, changed = fastpathTV.DecMapUintptrBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int]interface{}: - fastpathTV.DecMapIntIntfV(v, false, d) - case *map[int]interface{}: - var v2 map[int]interface{} - v2, changed = fastpathTV.DecMapIntIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int]string: - fastpathTV.DecMapIntStringV(v, false, d) - case *map[int]string: - var v2 map[int]string - v2, changed = fastpathTV.DecMapIntStringV(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint: - fastpathTV.DecMapIntUintV(v, false, d) - case *map[int]uint: - var v2 map[int]uint - v2, changed = fastpathTV.DecMapIntUintV(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint8: - fastpathTV.DecMapIntUint8V(v, false, d) - case *map[int]uint8: - var v2 map[int]uint8 - v2, changed = fastpathTV.DecMapIntUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint16: - fastpathTV.DecMapIntUint16V(v, false, d) - case *map[int]uint16: - var v2 map[int]uint16 - v2, changed = fastpathTV.DecMapIntUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint32: - fastpathTV.DecMapIntUint32V(v, false, d) - case *map[int]uint32: - var v2 map[int]uint32 - v2, changed = fastpathTV.DecMapIntUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint64: - fastpathTV.DecMapIntUint64V(v, false, d) - case *map[int]uint64: - var v2 map[int]uint64 - v2, changed = fastpathTV.DecMapIntUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uintptr: - fastpathTV.DecMapIntUintptrV(v, false, d) - case *map[int]uintptr: - var v2 map[int]uintptr - v2, changed = fastpathTV.DecMapIntUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int]int: - fastpathTV.DecMapIntIntV(v, false, d) - case *map[int]int: - var v2 map[int]int - v2, changed = fastpathTV.DecMapIntIntV(*v, true, d) - if changed { - *v = v2 - } - case map[int]int8: - fastpathTV.DecMapIntInt8V(v, false, d) - case *map[int]int8: - var v2 map[int]int8 - v2, changed = fastpathTV.DecMapIntInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int16: - fastpathTV.DecMapIntInt16V(v, false, d) - case *map[int]int16: - var v2 map[int]int16 - v2, changed = fastpathTV.DecMapIntInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int32: - fastpathTV.DecMapIntInt32V(v, false, d) - case *map[int]int32: - var v2 map[int]int32 - v2, changed = fastpathTV.DecMapIntInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int64: - fastpathTV.DecMapIntInt64V(v, false, d) - case *map[int]int64: - var v2 map[int]int64 - v2, changed = fastpathTV.DecMapIntInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]float32: - fastpathTV.DecMapIntFloat32V(v, false, d) - case *map[int]float32: - var v2 map[int]float32 - v2, changed = fastpathTV.DecMapIntFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]float64: - fastpathTV.DecMapIntFloat64V(v, false, d) - case *map[int]float64: - var v2 map[int]float64 - v2, changed = fastpathTV.DecMapIntFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]bool: - fastpathTV.DecMapIntBoolV(v, false, d) - case *map[int]bool: - var v2 map[int]bool - v2, changed = fastpathTV.DecMapIntBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]interface{}: - fastpathTV.DecMapInt8IntfV(v, false, d) - case *map[int8]interface{}: - var v2 map[int8]interface{} - v2, changed = fastpathTV.DecMapInt8IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]string: - fastpathTV.DecMapInt8StringV(v, false, d) - case *map[int8]string: - var v2 map[int8]string - v2, changed = fastpathTV.DecMapInt8StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint: - fastpathTV.DecMapInt8UintV(v, false, d) - case *map[int8]uint: - var v2 map[int8]uint - v2, changed = fastpathTV.DecMapInt8UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint8: - fastpathTV.DecMapInt8Uint8V(v, false, d) - case *map[int8]uint8: - var v2 map[int8]uint8 - v2, changed = fastpathTV.DecMapInt8Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint16: - fastpathTV.DecMapInt8Uint16V(v, false, d) - case *map[int8]uint16: - var v2 map[int8]uint16 - v2, changed = fastpathTV.DecMapInt8Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint32: - fastpathTV.DecMapInt8Uint32V(v, false, d) - case *map[int8]uint32: - var v2 map[int8]uint32 - v2, changed = fastpathTV.DecMapInt8Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint64: - fastpathTV.DecMapInt8Uint64V(v, false, d) - case *map[int8]uint64: - var v2 map[int8]uint64 - v2, changed = fastpathTV.DecMapInt8Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uintptr: - fastpathTV.DecMapInt8UintptrV(v, false, d) - case *map[int8]uintptr: - var v2 map[int8]uintptr - v2, changed = fastpathTV.DecMapInt8UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int: - fastpathTV.DecMapInt8IntV(v, false, d) - case *map[int8]int: - var v2 map[int8]int - v2, changed = fastpathTV.DecMapInt8IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int8: - fastpathTV.DecMapInt8Int8V(v, false, d) - case *map[int8]int8: - var v2 map[int8]int8 - v2, changed = fastpathTV.DecMapInt8Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int16: - fastpathTV.DecMapInt8Int16V(v, false, d) - case *map[int8]int16: - var v2 map[int8]int16 - v2, changed = fastpathTV.DecMapInt8Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int32: - fastpathTV.DecMapInt8Int32V(v, false, d) - case *map[int8]int32: - var v2 map[int8]int32 - v2, changed = fastpathTV.DecMapInt8Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int64: - fastpathTV.DecMapInt8Int64V(v, false, d) - case *map[int8]int64: - var v2 map[int8]int64 - v2, changed = fastpathTV.DecMapInt8Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]float32: - fastpathTV.DecMapInt8Float32V(v, false, d) - case *map[int8]float32: - var v2 map[int8]float32 - v2, changed = fastpathTV.DecMapInt8Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]float64: - fastpathTV.DecMapInt8Float64V(v, false, d) - case *map[int8]float64: - var v2 map[int8]float64 - v2, changed = fastpathTV.DecMapInt8Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]bool: - fastpathTV.DecMapInt8BoolV(v, false, d) - case *map[int8]bool: - var v2 map[int8]bool - v2, changed = fastpathTV.DecMapInt8BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]interface{}: - fastpathTV.DecMapInt16IntfV(v, false, d) - case *map[int16]interface{}: - var v2 map[int16]interface{} - v2, changed = fastpathTV.DecMapInt16IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]string: - fastpathTV.DecMapInt16StringV(v, false, d) - case *map[int16]string: - var v2 map[int16]string - v2, changed = fastpathTV.DecMapInt16StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint: - fastpathTV.DecMapInt16UintV(v, false, d) - case *map[int16]uint: - var v2 map[int16]uint - v2, changed = fastpathTV.DecMapInt16UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint8: - fastpathTV.DecMapInt16Uint8V(v, false, d) - case *map[int16]uint8: - var v2 map[int16]uint8 - v2, changed = fastpathTV.DecMapInt16Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint16: - fastpathTV.DecMapInt16Uint16V(v, false, d) - case *map[int16]uint16: - var v2 map[int16]uint16 - v2, changed = fastpathTV.DecMapInt16Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint32: - fastpathTV.DecMapInt16Uint32V(v, false, d) - case *map[int16]uint32: - var v2 map[int16]uint32 - v2, changed = fastpathTV.DecMapInt16Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint64: - fastpathTV.DecMapInt16Uint64V(v, false, d) - case *map[int16]uint64: - var v2 map[int16]uint64 - v2, changed = fastpathTV.DecMapInt16Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uintptr: - fastpathTV.DecMapInt16UintptrV(v, false, d) - case *map[int16]uintptr: - var v2 map[int16]uintptr - v2, changed = fastpathTV.DecMapInt16UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int: - fastpathTV.DecMapInt16IntV(v, false, d) - case *map[int16]int: - var v2 map[int16]int - v2, changed = fastpathTV.DecMapInt16IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int8: - fastpathTV.DecMapInt16Int8V(v, false, d) - case *map[int16]int8: - var v2 map[int16]int8 - v2, changed = fastpathTV.DecMapInt16Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int16: - fastpathTV.DecMapInt16Int16V(v, false, d) - case *map[int16]int16: - var v2 map[int16]int16 - v2, changed = fastpathTV.DecMapInt16Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int32: - fastpathTV.DecMapInt16Int32V(v, false, d) - case *map[int16]int32: - var v2 map[int16]int32 - v2, changed = fastpathTV.DecMapInt16Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int64: - fastpathTV.DecMapInt16Int64V(v, false, d) - case *map[int16]int64: - var v2 map[int16]int64 - v2, changed = fastpathTV.DecMapInt16Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]float32: - fastpathTV.DecMapInt16Float32V(v, false, d) - case *map[int16]float32: - var v2 map[int16]float32 - v2, changed = fastpathTV.DecMapInt16Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]float64: - fastpathTV.DecMapInt16Float64V(v, false, d) - case *map[int16]float64: - var v2 map[int16]float64 - v2, changed = fastpathTV.DecMapInt16Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]bool: - fastpathTV.DecMapInt16BoolV(v, false, d) - case *map[int16]bool: - var v2 map[int16]bool - v2, changed = fastpathTV.DecMapInt16BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]interface{}: - fastpathTV.DecMapInt32IntfV(v, false, d) - case *map[int32]interface{}: - var v2 map[int32]interface{} - v2, changed = fastpathTV.DecMapInt32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]string: - fastpathTV.DecMapInt32StringV(v, false, d) - case *map[int32]string: - var v2 map[int32]string - v2, changed = fastpathTV.DecMapInt32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint: - fastpathTV.DecMapInt32UintV(v, false, d) - case *map[int32]uint: - var v2 map[int32]uint - v2, changed = fastpathTV.DecMapInt32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint8: - fastpathTV.DecMapInt32Uint8V(v, false, d) - case *map[int32]uint8: - var v2 map[int32]uint8 - v2, changed = fastpathTV.DecMapInt32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint16: - fastpathTV.DecMapInt32Uint16V(v, false, d) - case *map[int32]uint16: - var v2 map[int32]uint16 - v2, changed = fastpathTV.DecMapInt32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint32: - fastpathTV.DecMapInt32Uint32V(v, false, d) - case *map[int32]uint32: - var v2 map[int32]uint32 - v2, changed = fastpathTV.DecMapInt32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint64: - fastpathTV.DecMapInt32Uint64V(v, false, d) - case *map[int32]uint64: - var v2 map[int32]uint64 - v2, changed = fastpathTV.DecMapInt32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uintptr: - fastpathTV.DecMapInt32UintptrV(v, false, d) - case *map[int32]uintptr: - var v2 map[int32]uintptr - v2, changed = fastpathTV.DecMapInt32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int: - fastpathTV.DecMapInt32IntV(v, false, d) - case *map[int32]int: - var v2 map[int32]int - v2, changed = fastpathTV.DecMapInt32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int8: - fastpathTV.DecMapInt32Int8V(v, false, d) - case *map[int32]int8: - var v2 map[int32]int8 - v2, changed = fastpathTV.DecMapInt32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int16: - fastpathTV.DecMapInt32Int16V(v, false, d) - case *map[int32]int16: - var v2 map[int32]int16 - v2, changed = fastpathTV.DecMapInt32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int32: - fastpathTV.DecMapInt32Int32V(v, false, d) - case *map[int32]int32: - var v2 map[int32]int32 - v2, changed = fastpathTV.DecMapInt32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int64: - fastpathTV.DecMapInt32Int64V(v, false, d) - case *map[int32]int64: - var v2 map[int32]int64 - v2, changed = fastpathTV.DecMapInt32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]float32: - fastpathTV.DecMapInt32Float32V(v, false, d) - case *map[int32]float32: - var v2 map[int32]float32 - v2, changed = fastpathTV.DecMapInt32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]float64: - fastpathTV.DecMapInt32Float64V(v, false, d) - case *map[int32]float64: - var v2 map[int32]float64 - v2, changed = fastpathTV.DecMapInt32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]bool: - fastpathTV.DecMapInt32BoolV(v, false, d) - case *map[int32]bool: - var v2 map[int32]bool - v2, changed = fastpathTV.DecMapInt32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]interface{}: - fastpathTV.DecMapInt64IntfV(v, false, d) - case *map[int64]interface{}: - var v2 map[int64]interface{} - v2, changed = fastpathTV.DecMapInt64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]string: - fastpathTV.DecMapInt64StringV(v, false, d) - case *map[int64]string: - var v2 map[int64]string - v2, changed = fastpathTV.DecMapInt64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint: - fastpathTV.DecMapInt64UintV(v, false, d) - case *map[int64]uint: - var v2 map[int64]uint - v2, changed = fastpathTV.DecMapInt64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint8: - fastpathTV.DecMapInt64Uint8V(v, false, d) - case *map[int64]uint8: - var v2 map[int64]uint8 - v2, changed = fastpathTV.DecMapInt64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint16: - fastpathTV.DecMapInt64Uint16V(v, false, d) - case *map[int64]uint16: - var v2 map[int64]uint16 - v2, changed = fastpathTV.DecMapInt64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint32: - fastpathTV.DecMapInt64Uint32V(v, false, d) - case *map[int64]uint32: - var v2 map[int64]uint32 - v2, changed = fastpathTV.DecMapInt64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint64: - fastpathTV.DecMapInt64Uint64V(v, false, d) - case *map[int64]uint64: - var v2 map[int64]uint64 - v2, changed = fastpathTV.DecMapInt64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uintptr: - fastpathTV.DecMapInt64UintptrV(v, false, d) - case *map[int64]uintptr: - var v2 map[int64]uintptr - v2, changed = fastpathTV.DecMapInt64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int: - fastpathTV.DecMapInt64IntV(v, false, d) - case *map[int64]int: - var v2 map[int64]int - v2, changed = fastpathTV.DecMapInt64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int8: - fastpathTV.DecMapInt64Int8V(v, false, d) - case *map[int64]int8: - var v2 map[int64]int8 - v2, changed = fastpathTV.DecMapInt64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int16: - fastpathTV.DecMapInt64Int16V(v, false, d) - case *map[int64]int16: - var v2 map[int64]int16 - v2, changed = fastpathTV.DecMapInt64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int32: - fastpathTV.DecMapInt64Int32V(v, false, d) - case *map[int64]int32: - var v2 map[int64]int32 - v2, changed = fastpathTV.DecMapInt64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int64: - fastpathTV.DecMapInt64Int64V(v, false, d) - case *map[int64]int64: - var v2 map[int64]int64 - v2, changed = fastpathTV.DecMapInt64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]float32: - fastpathTV.DecMapInt64Float32V(v, false, d) - case *map[int64]float32: - var v2 map[int64]float32 - v2, changed = fastpathTV.DecMapInt64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]float64: - fastpathTV.DecMapInt64Float64V(v, false, d) - case *map[int64]float64: - var v2 map[int64]float64 - v2, changed = fastpathTV.DecMapInt64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]bool: - fastpathTV.DecMapInt64BoolV(v, false, d) - case *map[int64]bool: - var v2 map[int64]bool - v2, changed = fastpathTV.DecMapInt64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]interface{}: - fastpathTV.DecMapBoolIntfV(v, false, d) - case *map[bool]interface{}: - var v2 map[bool]interface{} - v2, changed = fastpathTV.DecMapBoolIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]string: - fastpathTV.DecMapBoolStringV(v, false, d) - case *map[bool]string: - var v2 map[bool]string - v2, changed = fastpathTV.DecMapBoolStringV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint: - fastpathTV.DecMapBoolUintV(v, false, d) - case *map[bool]uint: - var v2 map[bool]uint - v2, changed = fastpathTV.DecMapBoolUintV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint8: - fastpathTV.DecMapBoolUint8V(v, false, d) - case *map[bool]uint8: - var v2 map[bool]uint8 - v2, changed = fastpathTV.DecMapBoolUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint16: - fastpathTV.DecMapBoolUint16V(v, false, d) - case *map[bool]uint16: - var v2 map[bool]uint16 - v2, changed = fastpathTV.DecMapBoolUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint32: - fastpathTV.DecMapBoolUint32V(v, false, d) - case *map[bool]uint32: - var v2 map[bool]uint32 - v2, changed = fastpathTV.DecMapBoolUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint64: - fastpathTV.DecMapBoolUint64V(v, false, d) - case *map[bool]uint64: - var v2 map[bool]uint64 - v2, changed = fastpathTV.DecMapBoolUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uintptr: - fastpathTV.DecMapBoolUintptrV(v, false, d) - case *map[bool]uintptr: - var v2 map[bool]uintptr - v2, changed = fastpathTV.DecMapBoolUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int: - fastpathTV.DecMapBoolIntV(v, false, d) - case *map[bool]int: - var v2 map[bool]int - v2, changed = fastpathTV.DecMapBoolIntV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int8: - fastpathTV.DecMapBoolInt8V(v, false, d) - case *map[bool]int8: - var v2 map[bool]int8 - v2, changed = fastpathTV.DecMapBoolInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int16: - fastpathTV.DecMapBoolInt16V(v, false, d) - case *map[bool]int16: - var v2 map[bool]int16 - v2, changed = fastpathTV.DecMapBoolInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int32: - fastpathTV.DecMapBoolInt32V(v, false, d) - case *map[bool]int32: - var v2 map[bool]int32 - v2, changed = fastpathTV.DecMapBoolInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int64: - fastpathTV.DecMapBoolInt64V(v, false, d) - case *map[bool]int64: - var v2 map[bool]int64 - v2, changed = fastpathTV.DecMapBoolInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]float32: - fastpathTV.DecMapBoolFloat32V(v, false, d) - case *map[bool]float32: - var v2 map[bool]float32 - v2, changed = fastpathTV.DecMapBoolFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]float64: - fastpathTV.DecMapBoolFloat64V(v, false, d) - case *map[bool]float64: - var v2 map[bool]float64 - v2, changed = fastpathTV.DecMapBoolFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]bool: - fastpathTV.DecMapBoolBoolV(v, false, d) - case *map[bool]bool: - var v2 map[bool]bool - v2, changed = fastpathTV.DecMapBoolBoolV(*v, true, d) - if changed { - *v = v2 - } - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { - switch v := iv.(type) { - - case *[]interface{}: - *v = nil - case *[]string: - *v = nil - case *[]float32: - *v = nil - case *[]float64: - *v = nil - case *[]uint: - *v = nil - case *[]uint8: - *v = nil - case *[]uint16: - *v = nil - case *[]uint32: - *v = nil - case *[]uint64: - *v = nil - case *[]uintptr: - *v = nil - case *[]int: - *v = nil - case *[]int8: - *v = nil - case *[]int16: - *v = nil - case *[]int32: - *v = nil - case *[]int64: - *v = nil - case *[]bool: - *v = nil - - case *map[interface{}]interface{}: - *v = nil - case *map[interface{}]string: - *v = nil - case *map[interface{}]uint: - *v = nil - case *map[interface{}]uint8: - *v = nil - case *map[interface{}]uint16: - *v = nil - case *map[interface{}]uint32: - *v = nil - case *map[interface{}]uint64: - *v = nil - case *map[interface{}]uintptr: - *v = nil - case *map[interface{}]int: - *v = nil - case *map[interface{}]int8: - *v = nil - case *map[interface{}]int16: - *v = nil - case *map[interface{}]int32: - *v = nil - case *map[interface{}]int64: - *v = nil - case *map[interface{}]float32: - *v = nil - case *map[interface{}]float64: - *v = nil - case *map[interface{}]bool: - *v = nil - case *map[string]interface{}: - *v = nil - case *map[string]string: - *v = nil - case *map[string]uint: - *v = nil - case *map[string]uint8: - *v = nil - case *map[string]uint16: - *v = nil - case *map[string]uint32: - *v = nil - case *map[string]uint64: - *v = nil - case *map[string]uintptr: - *v = nil - case *map[string]int: - *v = nil - case *map[string]int8: - *v = nil - case *map[string]int16: - *v = nil - case *map[string]int32: - *v = nil - case *map[string]int64: - *v = nil - case *map[string]float32: - *v = nil - case *map[string]float64: - *v = nil - case *map[string]bool: - *v = nil - case *map[float32]interface{}: - *v = nil - case *map[float32]string: - *v = nil - case *map[float32]uint: - *v = nil - case *map[float32]uint8: - *v = nil - case *map[float32]uint16: - *v = nil - case *map[float32]uint32: - *v = nil - case *map[float32]uint64: - *v = nil - case *map[float32]uintptr: - *v = nil - case *map[float32]int: - *v = nil - case *map[float32]int8: - *v = nil - case *map[float32]int16: - *v = nil - case *map[float32]int32: - *v = nil - case *map[float32]int64: - *v = nil - case *map[float32]float32: - *v = nil - case *map[float32]float64: - *v = nil - case *map[float32]bool: - *v = nil - case *map[float64]interface{}: - *v = nil - case *map[float64]string: - *v = nil - case *map[float64]uint: - *v = nil - case *map[float64]uint8: - *v = nil - case *map[float64]uint16: - *v = nil - case *map[float64]uint32: - *v = nil - case *map[float64]uint64: - *v = nil - case *map[float64]uintptr: - *v = nil - case *map[float64]int: - *v = nil - case *map[float64]int8: - *v = nil - case *map[float64]int16: - *v = nil - case *map[float64]int32: - *v = nil - case *map[float64]int64: - *v = nil - case *map[float64]float32: - *v = nil - case *map[float64]float64: - *v = nil - case *map[float64]bool: - *v = nil - case *map[uint]interface{}: - *v = nil - case *map[uint]string: - *v = nil - case *map[uint]uint: - *v = nil - case *map[uint]uint8: - *v = nil - case *map[uint]uint16: - *v = nil - case *map[uint]uint32: - *v = nil - case *map[uint]uint64: - *v = nil - case *map[uint]uintptr: - *v = nil - case *map[uint]int: - *v = nil - case *map[uint]int8: - *v = nil - case *map[uint]int16: - *v = nil - case *map[uint]int32: - *v = nil - case *map[uint]int64: - *v = nil - case *map[uint]float32: - *v = nil - case *map[uint]float64: - *v = nil - case *map[uint]bool: - *v = nil - case *map[uint8]interface{}: - *v = nil - case *map[uint8]string: - *v = nil - case *map[uint8]uint: - *v = nil - case *map[uint8]uint8: - *v = nil - case *map[uint8]uint16: - *v = nil - case *map[uint8]uint32: - *v = nil - case *map[uint8]uint64: - *v = nil - case *map[uint8]uintptr: - *v = nil - case *map[uint8]int: - *v = nil - case *map[uint8]int8: - *v = nil - case *map[uint8]int16: - *v = nil - case *map[uint8]int32: - *v = nil - case *map[uint8]int64: - *v = nil - case *map[uint8]float32: - *v = nil - case *map[uint8]float64: - *v = nil - case *map[uint8]bool: - *v = nil - case *map[uint16]interface{}: - *v = nil - case *map[uint16]string: - *v = nil - case *map[uint16]uint: - *v = nil - case *map[uint16]uint8: - *v = nil - case *map[uint16]uint16: - *v = nil - case *map[uint16]uint32: - *v = nil - case *map[uint16]uint64: - *v = nil - case *map[uint16]uintptr: - *v = nil - case *map[uint16]int: - *v = nil - case *map[uint16]int8: - *v = nil - case *map[uint16]int16: - *v = nil - case *map[uint16]int32: - *v = nil - case *map[uint16]int64: - *v = nil - case *map[uint16]float32: - *v = nil - case *map[uint16]float64: - *v = nil - case *map[uint16]bool: - *v = nil - case *map[uint32]interface{}: - *v = nil - case *map[uint32]string: - *v = nil - case *map[uint32]uint: - *v = nil - case *map[uint32]uint8: - *v = nil - case *map[uint32]uint16: - *v = nil - case *map[uint32]uint32: - *v = nil - case *map[uint32]uint64: - *v = nil - case *map[uint32]uintptr: - *v = nil - case *map[uint32]int: - *v = nil - case *map[uint32]int8: - *v = nil - case *map[uint32]int16: - *v = nil - case *map[uint32]int32: - *v = nil - case *map[uint32]int64: - *v = nil - case *map[uint32]float32: - *v = nil - case *map[uint32]float64: - *v = nil - case *map[uint32]bool: - *v = nil - case *map[uint64]interface{}: - *v = nil - case *map[uint64]string: - *v = nil - case *map[uint64]uint: - *v = nil - case *map[uint64]uint8: - *v = nil - case *map[uint64]uint16: - *v = nil - case *map[uint64]uint32: - *v = nil - case *map[uint64]uint64: - *v = nil - case *map[uint64]uintptr: - *v = nil - case *map[uint64]int: - *v = nil - case *map[uint64]int8: - *v = nil - case *map[uint64]int16: - *v = nil - case *map[uint64]int32: - *v = nil - case *map[uint64]int64: - *v = nil - case *map[uint64]float32: - *v = nil - case *map[uint64]float64: - *v = nil - case *map[uint64]bool: - *v = nil - case *map[uintptr]interface{}: - *v = nil - case *map[uintptr]string: - *v = nil - case *map[uintptr]uint: - *v = nil - case *map[uintptr]uint8: - *v = nil - case *map[uintptr]uint16: - *v = nil - case *map[uintptr]uint32: - *v = nil - case *map[uintptr]uint64: - *v = nil - case *map[uintptr]uintptr: - *v = nil - case *map[uintptr]int: - *v = nil - case *map[uintptr]int8: - *v = nil - case *map[uintptr]int16: - *v = nil - case *map[uintptr]int32: - *v = nil - case *map[uintptr]int64: - *v = nil - case *map[uintptr]float32: - *v = nil - case *map[uintptr]float64: - *v = nil - case *map[uintptr]bool: - *v = nil - case *map[int]interface{}: - *v = nil - case *map[int]string: - *v = nil - case *map[int]uint: - *v = nil - case *map[int]uint8: - *v = nil - case *map[int]uint16: - *v = nil - case *map[int]uint32: - *v = nil - case *map[int]uint64: - *v = nil - case *map[int]uintptr: - *v = nil - case *map[int]int: - *v = nil - case *map[int]int8: - *v = nil - case *map[int]int16: - *v = nil - case *map[int]int32: - *v = nil - case *map[int]int64: - *v = nil - case *map[int]float32: - *v = nil - case *map[int]float64: - *v = nil - case *map[int]bool: - *v = nil - case *map[int8]interface{}: - *v = nil - case *map[int8]string: - *v = nil - case *map[int8]uint: - *v = nil - case *map[int8]uint8: - *v = nil - case *map[int8]uint16: - *v = nil - case *map[int8]uint32: - *v = nil - case *map[int8]uint64: - *v = nil - case *map[int8]uintptr: - *v = nil - case *map[int8]int: - *v = nil - case *map[int8]int8: - *v = nil - case *map[int8]int16: - *v = nil - case *map[int8]int32: - *v = nil - case *map[int8]int64: - *v = nil - case *map[int8]float32: - *v = nil - case *map[int8]float64: - *v = nil - case *map[int8]bool: - *v = nil - case *map[int16]interface{}: - *v = nil - case *map[int16]string: - *v = nil - case *map[int16]uint: - *v = nil - case *map[int16]uint8: - *v = nil - case *map[int16]uint16: - *v = nil - case *map[int16]uint32: - *v = nil - case *map[int16]uint64: - *v = nil - case *map[int16]uintptr: - *v = nil - case *map[int16]int: - *v = nil - case *map[int16]int8: - *v = nil - case *map[int16]int16: - *v = nil - case *map[int16]int32: - *v = nil - case *map[int16]int64: - *v = nil - case *map[int16]float32: - *v = nil - case *map[int16]float64: - *v = nil - case *map[int16]bool: - *v = nil - case *map[int32]interface{}: - *v = nil - case *map[int32]string: - *v = nil - case *map[int32]uint: - *v = nil - case *map[int32]uint8: - *v = nil - case *map[int32]uint16: - *v = nil - case *map[int32]uint32: - *v = nil - case *map[int32]uint64: - *v = nil - case *map[int32]uintptr: - *v = nil - case *map[int32]int: - *v = nil - case *map[int32]int8: - *v = nil - case *map[int32]int16: - *v = nil - case *map[int32]int32: - *v = nil - case *map[int32]int64: - *v = nil - case *map[int32]float32: - *v = nil - case *map[int32]float64: - *v = nil - case *map[int32]bool: - *v = nil - case *map[int64]interface{}: - *v = nil - case *map[int64]string: - *v = nil - case *map[int64]uint: - *v = nil - case *map[int64]uint8: - *v = nil - case *map[int64]uint16: - *v = nil - case *map[int64]uint32: - *v = nil - case *map[int64]uint64: - *v = nil - case *map[int64]uintptr: - *v = nil - case *map[int64]int: - *v = nil - case *map[int64]int8: - *v = nil - case *map[int64]int16: - *v = nil - case *map[int64]int32: - *v = nil - case *map[int64]int64: - *v = nil - case *map[int64]float32: - *v = nil - case *map[int64]float64: - *v = nil - case *map[int64]bool: - *v = nil - case *map[bool]interface{}: - *v = nil - case *map[bool]string: - *v = nil - case *map[bool]uint: - *v = nil - case *map[bool]uint8: - *v = nil - case *map[bool]uint16: - *v = nil - case *map[bool]uint32: - *v = nil - case *map[bool]uint64: - *v = nil - case *map[bool]uintptr: - *v = nil - case *map[bool]int: - *v = nil - case *map[bool]int8: - *v = nil - case *map[bool]int16: - *v = nil - case *map[bool]int32: - *v = nil - case *map[bool]int64: - *v = nil - case *map[bool]float32: - *v = nil - case *map[bool]float64: - *v = nil - case *map[bool]bool: - *v = nil - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -// -- -- fast path functions - -func (d *Decoder) fastpathDecSliceIntfR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]interface{}) - v, changed := fastpathTV.DecSliceIntfV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]interface{}) - v2, changed := fastpathTV.DecSliceIntfV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceIntfX(vp *[]interface{}, d *Decoder) { - v, changed := f.DecSliceIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceIntfV(v []interface{}, canChange bool, d *Decoder) (_ []interface{}, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []interface{}{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]interface{}, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - } else { - xlen = 8 - } - v = make([]interface{}, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, nil) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = nil - } else { - d.decode(&v[uint(j)]) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]interface{}, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceStringR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]string) - v, changed := fastpathTV.DecSliceStringV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]string) - v2, changed := fastpathTV.DecSliceStringV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceStringX(vp *[]string, d *Decoder) { - v, changed := f.DecSliceStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceStringV(v []string, canChange bool, d *Decoder) (_ []string, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []string{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]string, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - } else { - xlen = 8 - } - v = make([]string, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, "") - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = "" - } else { - v[uint(j)] = dd.DecodeString() - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]string, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceFloat32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]float32) - v, changed := fastpathTV.DecSliceFloat32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]float32) - v2, changed := fastpathTV.DecSliceFloat32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceFloat32X(vp *[]float32, d *Decoder) { - v, changed := f.DecSliceFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceFloat32V(v []float32, canChange bool, d *Decoder) (_ []float32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []float32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]float32, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]float32, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = float32(chkOvf.Float32V(dd.DecodeFloat64())) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]float32, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceFloat64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]float64) - v, changed := fastpathTV.DecSliceFloat64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]float64) - v2, changed := fastpathTV.DecSliceFloat64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceFloat64X(vp *[]float64, d *Decoder) { - v, changed := f.DecSliceFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceFloat64V(v []float64, canChange bool, d *Decoder) (_ []float64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []float64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]float64, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]float64, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = dd.DecodeFloat64() - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]float64, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUintR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint) - v, changed := fastpathTV.DecSliceUintV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint) - v2, changed := fastpathTV.DecSliceUintV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUintX(vp *[]uint, d *Decoder) { - v, changed := f.DecSliceUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUintV(v []uint, canChange bool, d *Decoder) (_ []uint, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uint, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uint, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uint, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint8R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint8) - v, changed := fastpathTV.DecSliceUint8V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint8) - v2, changed := fastpathTV.DecSliceUint8V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint8X(vp *[]uint8, d *Decoder) { - v, changed := f.DecSliceUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint8V(v []uint8, canChange bool, d *Decoder) (_ []uint8, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint8{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uint8, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]uint8, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uint8, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint16R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint16) - v, changed := fastpathTV.DecSliceUint16V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint16) - v2, changed := fastpathTV.DecSliceUint16V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint16X(vp *[]uint16, d *Decoder) { - v, changed := f.DecSliceUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint16V(v []uint16, canChange bool, d *Decoder) (_ []uint16, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint16{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uint16, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - } else { - xlen = 8 - } - v = make([]uint16, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uint16, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint32) - v, changed := fastpathTV.DecSliceUint32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint32) - v2, changed := fastpathTV.DecSliceUint32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint32X(vp *[]uint32, d *Decoder) { - v, changed := f.DecSliceUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint32V(v []uint32, canChange bool, d *Decoder) (_ []uint32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uint32, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]uint32, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uint32, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint64) - v, changed := fastpathTV.DecSliceUint64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint64) - v2, changed := fastpathTV.DecSliceUint64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint64X(vp *[]uint64, d *Decoder) { - v, changed := f.DecSliceUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint64V(v []uint64, canChange bool, d *Decoder) (_ []uint64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uint64, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uint64, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = dd.DecodeUint64() - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uint64, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUintptrR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uintptr) - v, changed := fastpathTV.DecSliceUintptrV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uintptr) - v2, changed := fastpathTV.DecSliceUintptrV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUintptrX(vp *[]uintptr, d *Decoder) { - v, changed := f.DecSliceUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUintptrV(v []uintptr, canChange bool, d *Decoder) (_ []uintptr, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uintptr{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]uintptr, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uintptr, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]uintptr, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceIntR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int) - v, changed := fastpathTV.DecSliceIntV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int) - v2, changed := fastpathTV.DecSliceIntV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceIntX(vp *[]int, d *Decoder) { - v, changed := f.DecSliceIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceIntV(v []int, canChange bool, d *Decoder) (_ []int, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]int, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]int, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]int, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt8R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int8) - v, changed := fastpathTV.DecSliceInt8V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int8) - v2, changed := fastpathTV.DecSliceInt8V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt8X(vp *[]int8, d *Decoder) { - v, changed := f.DecSliceInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt8V(v []int8, canChange bool, d *Decoder) (_ []int8, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int8{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]int8, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]int8, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]int8, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt16R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int16) - v, changed := fastpathTV.DecSliceInt16V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int16) - v2, changed := fastpathTV.DecSliceInt16V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt16X(vp *[]int16, d *Decoder) { - v, changed := f.DecSliceInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt16V(v []int16, canChange bool, d *Decoder) (_ []int16, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int16{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]int16, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - } else { - xlen = 8 - } - v = make([]int16, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]int16, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int32) - v, changed := fastpathTV.DecSliceInt32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int32) - v2, changed := fastpathTV.DecSliceInt32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt32X(vp *[]int32, d *Decoder) { - v, changed := f.DecSliceInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt32V(v []int32, canChange bool, d *Decoder) (_ []int32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]int32, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]int32, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]int32, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int64) - v, changed := fastpathTV.DecSliceInt64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int64) - v2, changed := fastpathTV.DecSliceInt64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt64X(vp *[]int64, d *Decoder) { - v, changed := f.DecSliceInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt64V(v []int64, canChange bool, d *Decoder) (_ []int64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]int64, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]int64, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = 0 - } else { - v[uint(j)] = dd.DecodeInt64() - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]int64, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecSliceBoolR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]bool) - v, changed := fastpathTV.DecSliceBoolV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]bool) - v2, changed := fastpathTV.DecSliceBoolV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceBoolX(vp *[]bool, d *Decoder) { - v, changed := f.DecSliceBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceBoolV(v []bool, canChange bool, d *Decoder) (_ []bool, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []bool{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]bool, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]bool, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, false) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = false - } else { - v[uint(j)] = dd.DecodeBool() - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]bool, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]interface{}) - v, changed := fastpathTV.DecMapIntfIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfIntfV(rv2i(rv).(map[interface{}]interface{}), false, d) - } -} -func (f fastpathT) DecMapIntfIntfX(vp *map[interface{}]interface{}, d *Decoder) { - v, changed := f.DecMapIntfIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfIntfV(v map[interface{}]interface{}, canChange bool, - d *Decoder) (_ map[interface{}]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[interface{}]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk interface{} - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]string) - v, changed := fastpathTV.DecMapIntfStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfStringV(rv2i(rv).(map[interface{}]string), false, d) - } -} -func (f fastpathT) DecMapIntfStringX(vp *map[interface{}]string, d *Decoder) { - v, changed := f.DecMapIntfStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfStringV(v map[interface{}]string, canChange bool, - d *Decoder) (_ map[interface{}]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[interface{}]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint) - v, changed := fastpathTV.DecMapIntfUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUintV(rv2i(rv).(map[interface{}]uint), false, d) - } -} -func (f fastpathT) DecMapIntfUintX(vp *map[interface{}]uint, d *Decoder) { - v, changed := f.DecMapIntfUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUintV(v map[interface{}]uint, canChange bool, - d *Decoder) (_ map[interface{}]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint8) - v, changed := fastpathTV.DecMapIntfUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint8V(rv2i(rv).(map[interface{}]uint8), false, d) - } -} -func (f fastpathT) DecMapIntfUint8X(vp *map[interface{}]uint8, d *Decoder) { - v, changed := f.DecMapIntfUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint8V(v map[interface{}]uint8, canChange bool, - d *Decoder) (_ map[interface{}]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint16) - v, changed := fastpathTV.DecMapIntfUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint16V(rv2i(rv).(map[interface{}]uint16), false, d) - } -} -func (f fastpathT) DecMapIntfUint16X(vp *map[interface{}]uint16, d *Decoder) { - v, changed := f.DecMapIntfUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint16V(v map[interface{}]uint16, canChange bool, - d *Decoder) (_ map[interface{}]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[interface{}]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint32) - v, changed := fastpathTV.DecMapIntfUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint32V(rv2i(rv).(map[interface{}]uint32), false, d) - } -} -func (f fastpathT) DecMapIntfUint32X(vp *map[interface{}]uint32, d *Decoder) { - v, changed := f.DecMapIntfUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint32V(v map[interface{}]uint32, canChange bool, - d *Decoder) (_ map[interface{}]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint64) - v, changed := fastpathTV.DecMapIntfUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint64V(rv2i(rv).(map[interface{}]uint64), false, d) - } -} -func (f fastpathT) DecMapIntfUint64X(vp *map[interface{}]uint64, d *Decoder) { - v, changed := f.DecMapIntfUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint64V(v map[interface{}]uint64, canChange bool, - d *Decoder) (_ map[interface{}]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uintptr) - v, changed := fastpathTV.DecMapIntfUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUintptrV(rv2i(rv).(map[interface{}]uintptr), false, d) - } -} -func (f fastpathT) DecMapIntfUintptrX(vp *map[interface{}]uintptr, d *Decoder) { - v, changed := f.DecMapIntfUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUintptrV(v map[interface{}]uintptr, canChange bool, - d *Decoder) (_ map[interface{}]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int) - v, changed := fastpathTV.DecMapIntfIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfIntV(rv2i(rv).(map[interface{}]int), false, d) - } -} -func (f fastpathT) DecMapIntfIntX(vp *map[interface{}]int, d *Decoder) { - v, changed := f.DecMapIntfIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfIntV(v map[interface{}]int, canChange bool, - d *Decoder) (_ map[interface{}]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int8) - v, changed := fastpathTV.DecMapIntfInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt8V(rv2i(rv).(map[interface{}]int8), false, d) - } -} -func (f fastpathT) DecMapIntfInt8X(vp *map[interface{}]int8, d *Decoder) { - v, changed := f.DecMapIntfInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt8V(v map[interface{}]int8, canChange bool, - d *Decoder) (_ map[interface{}]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int16) - v, changed := fastpathTV.DecMapIntfInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt16V(rv2i(rv).(map[interface{}]int16), false, d) - } -} -func (f fastpathT) DecMapIntfInt16X(vp *map[interface{}]int16, d *Decoder) { - v, changed := f.DecMapIntfInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt16V(v map[interface{}]int16, canChange bool, - d *Decoder) (_ map[interface{}]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[interface{}]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int32) - v, changed := fastpathTV.DecMapIntfInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt32V(rv2i(rv).(map[interface{}]int32), false, d) - } -} -func (f fastpathT) DecMapIntfInt32X(vp *map[interface{}]int32, d *Decoder) { - v, changed := f.DecMapIntfInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt32V(v map[interface{}]int32, canChange bool, - d *Decoder) (_ map[interface{}]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int64) - v, changed := fastpathTV.DecMapIntfInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt64V(rv2i(rv).(map[interface{}]int64), false, d) - } -} -func (f fastpathT) DecMapIntfInt64X(vp *map[interface{}]int64, d *Decoder) { - v, changed := f.DecMapIntfInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt64V(v map[interface{}]int64, canChange bool, - d *Decoder) (_ map[interface{}]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]float32) - v, changed := fastpathTV.DecMapIntfFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfFloat32V(rv2i(rv).(map[interface{}]float32), false, d) - } -} -func (f fastpathT) DecMapIntfFloat32X(vp *map[interface{}]float32, d *Decoder) { - v, changed := f.DecMapIntfFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfFloat32V(v map[interface{}]float32, canChange bool, - d *Decoder) (_ map[interface{}]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]float64) - v, changed := fastpathTV.DecMapIntfFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfFloat64V(rv2i(rv).(map[interface{}]float64), false, d) - } -} -func (f fastpathT) DecMapIntfFloat64X(vp *map[interface{}]float64, d *Decoder) { - v, changed := f.DecMapIntfFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfFloat64V(v map[interface{}]float64, canChange bool, - d *Decoder) (_ map[interface{}]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]bool) - v, changed := fastpathTV.DecMapIntfBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfBoolV(rv2i(rv).(map[interface{}]bool), false, d) - } -} -func (f fastpathT) DecMapIntfBoolX(vp *map[interface{}]bool, d *Decoder) { - v, changed := f.DecMapIntfBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfBoolV(v map[interface{}]bool, canChange bool, - d *Decoder) (_ map[interface{}]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk interface{} - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]interface{}) - v, changed := fastpathTV.DecMapStringIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringIntfV(rv2i(rv).(map[string]interface{}), false, d) - } -} -func (f fastpathT) DecMapStringIntfX(vp *map[string]interface{}, d *Decoder) { - v, changed := f.DecMapStringIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringIntfV(v map[string]interface{}, canChange bool, - d *Decoder) (_ map[string]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[string]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk string - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]string) - v, changed := fastpathTV.DecMapStringStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringStringV(rv2i(rv).(map[string]string), false, d) - } -} -func (f fastpathT) DecMapStringStringX(vp *map[string]string, d *Decoder) { - v, changed := f.DecMapStringStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringStringV(v map[string]string, canChange bool, - d *Decoder) (_ map[string]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[string]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint) - v, changed := fastpathTV.DecMapStringUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUintV(rv2i(rv).(map[string]uint), false, d) - } -} -func (f fastpathT) DecMapStringUintX(vp *map[string]uint, d *Decoder) { - v, changed := f.DecMapStringUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUintV(v map[string]uint, canChange bool, - d *Decoder) (_ map[string]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint8) - v, changed := fastpathTV.DecMapStringUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint8V(rv2i(rv).(map[string]uint8), false, d) - } -} -func (f fastpathT) DecMapStringUint8X(vp *map[string]uint8, d *Decoder) { - v, changed := f.DecMapStringUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint8V(v map[string]uint8, canChange bool, - d *Decoder) (_ map[string]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint16) - v, changed := fastpathTV.DecMapStringUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint16V(rv2i(rv).(map[string]uint16), false, d) - } -} -func (f fastpathT) DecMapStringUint16X(vp *map[string]uint16, d *Decoder) { - v, changed := f.DecMapStringUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint16V(v map[string]uint16, canChange bool, - d *Decoder) (_ map[string]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[string]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint32) - v, changed := fastpathTV.DecMapStringUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint32V(rv2i(rv).(map[string]uint32), false, d) - } -} -func (f fastpathT) DecMapStringUint32X(vp *map[string]uint32, d *Decoder) { - v, changed := f.DecMapStringUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint32V(v map[string]uint32, canChange bool, - d *Decoder) (_ map[string]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint64) - v, changed := fastpathTV.DecMapStringUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint64V(rv2i(rv).(map[string]uint64), false, d) - } -} -func (f fastpathT) DecMapStringUint64X(vp *map[string]uint64, d *Decoder) { - v, changed := f.DecMapStringUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint64V(v map[string]uint64, canChange bool, - d *Decoder) (_ map[string]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uintptr) - v, changed := fastpathTV.DecMapStringUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUintptrV(rv2i(rv).(map[string]uintptr), false, d) - } -} -func (f fastpathT) DecMapStringUintptrX(vp *map[string]uintptr, d *Decoder) { - v, changed := f.DecMapStringUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUintptrV(v map[string]uintptr, canChange bool, - d *Decoder) (_ map[string]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int) - v, changed := fastpathTV.DecMapStringIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringIntV(rv2i(rv).(map[string]int), false, d) - } -} -func (f fastpathT) DecMapStringIntX(vp *map[string]int, d *Decoder) { - v, changed := f.DecMapStringIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringIntV(v map[string]int, canChange bool, - d *Decoder) (_ map[string]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int8) - v, changed := fastpathTV.DecMapStringInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt8V(rv2i(rv).(map[string]int8), false, d) - } -} -func (f fastpathT) DecMapStringInt8X(vp *map[string]int8, d *Decoder) { - v, changed := f.DecMapStringInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt8V(v map[string]int8, canChange bool, - d *Decoder) (_ map[string]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int16) - v, changed := fastpathTV.DecMapStringInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt16V(rv2i(rv).(map[string]int16), false, d) - } -} -func (f fastpathT) DecMapStringInt16X(vp *map[string]int16, d *Decoder) { - v, changed := f.DecMapStringInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt16V(v map[string]int16, canChange bool, - d *Decoder) (_ map[string]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[string]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int32) - v, changed := fastpathTV.DecMapStringInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt32V(rv2i(rv).(map[string]int32), false, d) - } -} -func (f fastpathT) DecMapStringInt32X(vp *map[string]int32, d *Decoder) { - v, changed := f.DecMapStringInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt32V(v map[string]int32, canChange bool, - d *Decoder) (_ map[string]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int64) - v, changed := fastpathTV.DecMapStringInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt64V(rv2i(rv).(map[string]int64), false, d) - } -} -func (f fastpathT) DecMapStringInt64X(vp *map[string]int64, d *Decoder) { - v, changed := f.DecMapStringInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt64V(v map[string]int64, canChange bool, - d *Decoder) (_ map[string]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]float32) - v, changed := fastpathTV.DecMapStringFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringFloat32V(rv2i(rv).(map[string]float32), false, d) - } -} -func (f fastpathT) DecMapStringFloat32X(vp *map[string]float32, d *Decoder) { - v, changed := f.DecMapStringFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringFloat32V(v map[string]float32, canChange bool, - d *Decoder) (_ map[string]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]float64) - v, changed := fastpathTV.DecMapStringFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringFloat64V(rv2i(rv).(map[string]float64), false, d) - } -} -func (f fastpathT) DecMapStringFloat64X(vp *map[string]float64, d *Decoder) { - v, changed := f.DecMapStringFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringFloat64V(v map[string]float64, canChange bool, - d *Decoder) (_ map[string]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]bool) - v, changed := fastpathTV.DecMapStringBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringBoolV(rv2i(rv).(map[string]bool), false, d) - } -} -func (f fastpathT) DecMapStringBoolX(vp *map[string]bool, d *Decoder) { - v, changed := f.DecMapStringBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringBoolV(v map[string]bool, canChange bool, - d *Decoder) (_ map[string]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk string - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]interface{}) - v, changed := fastpathTV.DecMapFloat32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32IntfV(rv2i(rv).(map[float32]interface{}), false, d) - } -} -func (f fastpathT) DecMapFloat32IntfX(vp *map[float32]interface{}, d *Decoder) { - v, changed := f.DecMapFloat32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32IntfV(v map[float32]interface{}, canChange bool, - d *Decoder) (_ map[float32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[float32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk float32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]string) - v, changed := fastpathTV.DecMapFloat32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32StringV(rv2i(rv).(map[float32]string), false, d) - } -} -func (f fastpathT) DecMapFloat32StringX(vp *map[float32]string, d *Decoder) { - v, changed := f.DecMapFloat32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32StringV(v map[float32]string, canChange bool, - d *Decoder) (_ map[float32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[float32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint) - v, changed := fastpathTV.DecMapFloat32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32UintV(rv2i(rv).(map[float32]uint), false, d) - } -} -func (f fastpathT) DecMapFloat32UintX(vp *map[float32]uint, d *Decoder) { - v, changed := f.DecMapFloat32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32UintV(v map[float32]uint, canChange bool, - d *Decoder) (_ map[float32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint8) - v, changed := fastpathTV.DecMapFloat32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint8V(rv2i(rv).(map[float32]uint8), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint8X(vp *map[float32]uint8, d *Decoder) { - v, changed := f.DecMapFloat32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint8V(v map[float32]uint8, canChange bool, - d *Decoder) (_ map[float32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint16) - v, changed := fastpathTV.DecMapFloat32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint16V(rv2i(rv).(map[float32]uint16), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint16X(vp *map[float32]uint16, d *Decoder) { - v, changed := f.DecMapFloat32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint16V(v map[float32]uint16, canChange bool, - d *Decoder) (_ map[float32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[float32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint32) - v, changed := fastpathTV.DecMapFloat32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint32V(rv2i(rv).(map[float32]uint32), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint32X(vp *map[float32]uint32, d *Decoder) { - v, changed := f.DecMapFloat32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint32V(v map[float32]uint32, canChange bool, - d *Decoder) (_ map[float32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint64) - v, changed := fastpathTV.DecMapFloat32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint64V(rv2i(rv).(map[float32]uint64), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint64X(vp *map[float32]uint64, d *Decoder) { - v, changed := f.DecMapFloat32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint64V(v map[float32]uint64, canChange bool, - d *Decoder) (_ map[float32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uintptr) - v, changed := fastpathTV.DecMapFloat32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32UintptrV(rv2i(rv).(map[float32]uintptr), false, d) - } -} -func (f fastpathT) DecMapFloat32UintptrX(vp *map[float32]uintptr, d *Decoder) { - v, changed := f.DecMapFloat32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32UintptrV(v map[float32]uintptr, canChange bool, - d *Decoder) (_ map[float32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int) - v, changed := fastpathTV.DecMapFloat32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32IntV(rv2i(rv).(map[float32]int), false, d) - } -} -func (f fastpathT) DecMapFloat32IntX(vp *map[float32]int, d *Decoder) { - v, changed := f.DecMapFloat32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32IntV(v map[float32]int, canChange bool, - d *Decoder) (_ map[float32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int8) - v, changed := fastpathTV.DecMapFloat32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int8V(rv2i(rv).(map[float32]int8), false, d) - } -} -func (f fastpathT) DecMapFloat32Int8X(vp *map[float32]int8, d *Decoder) { - v, changed := f.DecMapFloat32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int8V(v map[float32]int8, canChange bool, - d *Decoder) (_ map[float32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int16) - v, changed := fastpathTV.DecMapFloat32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int16V(rv2i(rv).(map[float32]int16), false, d) - } -} -func (f fastpathT) DecMapFloat32Int16X(vp *map[float32]int16, d *Decoder) { - v, changed := f.DecMapFloat32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int16V(v map[float32]int16, canChange bool, - d *Decoder) (_ map[float32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[float32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int32) - v, changed := fastpathTV.DecMapFloat32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int32V(rv2i(rv).(map[float32]int32), false, d) - } -} -func (f fastpathT) DecMapFloat32Int32X(vp *map[float32]int32, d *Decoder) { - v, changed := f.DecMapFloat32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int32V(v map[float32]int32, canChange bool, - d *Decoder) (_ map[float32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int64) - v, changed := fastpathTV.DecMapFloat32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int64V(rv2i(rv).(map[float32]int64), false, d) - } -} -func (f fastpathT) DecMapFloat32Int64X(vp *map[float32]int64, d *Decoder) { - v, changed := f.DecMapFloat32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int64V(v map[float32]int64, canChange bool, - d *Decoder) (_ map[float32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]float32) - v, changed := fastpathTV.DecMapFloat32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Float32V(rv2i(rv).(map[float32]float32), false, d) - } -} -func (f fastpathT) DecMapFloat32Float32X(vp *map[float32]float32, d *Decoder) { - v, changed := f.DecMapFloat32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Float32V(v map[float32]float32, canChange bool, - d *Decoder) (_ map[float32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]float64) - v, changed := fastpathTV.DecMapFloat32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Float64V(rv2i(rv).(map[float32]float64), false, d) - } -} -func (f fastpathT) DecMapFloat32Float64X(vp *map[float32]float64, d *Decoder) { - v, changed := f.DecMapFloat32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Float64V(v map[float32]float64, canChange bool, - d *Decoder) (_ map[float32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]bool) - v, changed := fastpathTV.DecMapFloat32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32BoolV(rv2i(rv).(map[float32]bool), false, d) - } -} -func (f fastpathT) DecMapFloat32BoolX(vp *map[float32]bool, d *Decoder) { - v, changed := f.DecMapFloat32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32BoolV(v map[float32]bool, canChange bool, - d *Decoder) (_ map[float32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]interface{}) - v, changed := fastpathTV.DecMapFloat64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64IntfV(rv2i(rv).(map[float64]interface{}), false, d) - } -} -func (f fastpathT) DecMapFloat64IntfX(vp *map[float64]interface{}, d *Decoder) { - v, changed := f.DecMapFloat64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64IntfV(v map[float64]interface{}, canChange bool, - d *Decoder) (_ map[float64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[float64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk float64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]string) - v, changed := fastpathTV.DecMapFloat64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64StringV(rv2i(rv).(map[float64]string), false, d) - } -} -func (f fastpathT) DecMapFloat64StringX(vp *map[float64]string, d *Decoder) { - v, changed := f.DecMapFloat64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64StringV(v map[float64]string, canChange bool, - d *Decoder) (_ map[float64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[float64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint) - v, changed := fastpathTV.DecMapFloat64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64UintV(rv2i(rv).(map[float64]uint), false, d) - } -} -func (f fastpathT) DecMapFloat64UintX(vp *map[float64]uint, d *Decoder) { - v, changed := f.DecMapFloat64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64UintV(v map[float64]uint, canChange bool, - d *Decoder) (_ map[float64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint8) - v, changed := fastpathTV.DecMapFloat64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint8V(rv2i(rv).(map[float64]uint8), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint8X(vp *map[float64]uint8, d *Decoder) { - v, changed := f.DecMapFloat64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint8V(v map[float64]uint8, canChange bool, - d *Decoder) (_ map[float64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint16) - v, changed := fastpathTV.DecMapFloat64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint16V(rv2i(rv).(map[float64]uint16), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint16X(vp *map[float64]uint16, d *Decoder) { - v, changed := f.DecMapFloat64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint16V(v map[float64]uint16, canChange bool, - d *Decoder) (_ map[float64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[float64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint32) - v, changed := fastpathTV.DecMapFloat64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint32V(rv2i(rv).(map[float64]uint32), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint32X(vp *map[float64]uint32, d *Decoder) { - v, changed := f.DecMapFloat64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint32V(v map[float64]uint32, canChange bool, - d *Decoder) (_ map[float64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint64) - v, changed := fastpathTV.DecMapFloat64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint64V(rv2i(rv).(map[float64]uint64), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint64X(vp *map[float64]uint64, d *Decoder) { - v, changed := f.DecMapFloat64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint64V(v map[float64]uint64, canChange bool, - d *Decoder) (_ map[float64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uintptr) - v, changed := fastpathTV.DecMapFloat64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64UintptrV(rv2i(rv).(map[float64]uintptr), false, d) - } -} -func (f fastpathT) DecMapFloat64UintptrX(vp *map[float64]uintptr, d *Decoder) { - v, changed := f.DecMapFloat64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64UintptrV(v map[float64]uintptr, canChange bool, - d *Decoder) (_ map[float64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int) - v, changed := fastpathTV.DecMapFloat64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64IntV(rv2i(rv).(map[float64]int), false, d) - } -} -func (f fastpathT) DecMapFloat64IntX(vp *map[float64]int, d *Decoder) { - v, changed := f.DecMapFloat64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64IntV(v map[float64]int, canChange bool, - d *Decoder) (_ map[float64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int8) - v, changed := fastpathTV.DecMapFloat64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int8V(rv2i(rv).(map[float64]int8), false, d) - } -} -func (f fastpathT) DecMapFloat64Int8X(vp *map[float64]int8, d *Decoder) { - v, changed := f.DecMapFloat64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int8V(v map[float64]int8, canChange bool, - d *Decoder) (_ map[float64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int16) - v, changed := fastpathTV.DecMapFloat64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int16V(rv2i(rv).(map[float64]int16), false, d) - } -} -func (f fastpathT) DecMapFloat64Int16X(vp *map[float64]int16, d *Decoder) { - v, changed := f.DecMapFloat64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int16V(v map[float64]int16, canChange bool, - d *Decoder) (_ map[float64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[float64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int32) - v, changed := fastpathTV.DecMapFloat64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int32V(rv2i(rv).(map[float64]int32), false, d) - } -} -func (f fastpathT) DecMapFloat64Int32X(vp *map[float64]int32, d *Decoder) { - v, changed := f.DecMapFloat64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int32V(v map[float64]int32, canChange bool, - d *Decoder) (_ map[float64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int64) - v, changed := fastpathTV.DecMapFloat64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int64V(rv2i(rv).(map[float64]int64), false, d) - } -} -func (f fastpathT) DecMapFloat64Int64X(vp *map[float64]int64, d *Decoder) { - v, changed := f.DecMapFloat64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int64V(v map[float64]int64, canChange bool, - d *Decoder) (_ map[float64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]float32) - v, changed := fastpathTV.DecMapFloat64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Float32V(rv2i(rv).(map[float64]float32), false, d) - } -} -func (f fastpathT) DecMapFloat64Float32X(vp *map[float64]float32, d *Decoder) { - v, changed := f.DecMapFloat64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Float32V(v map[float64]float32, canChange bool, - d *Decoder) (_ map[float64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]float64) - v, changed := fastpathTV.DecMapFloat64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Float64V(rv2i(rv).(map[float64]float64), false, d) - } -} -func (f fastpathT) DecMapFloat64Float64X(vp *map[float64]float64, d *Decoder) { - v, changed := f.DecMapFloat64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Float64V(v map[float64]float64, canChange bool, - d *Decoder) (_ map[float64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]bool) - v, changed := fastpathTV.DecMapFloat64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64BoolV(rv2i(rv).(map[float64]bool), false, d) - } -} -func (f fastpathT) DecMapFloat64BoolX(vp *map[float64]bool, d *Decoder) { - v, changed := f.DecMapFloat64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64BoolV(v map[float64]bool, canChange bool, - d *Decoder) (_ map[float64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk float64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]interface{}) - v, changed := fastpathTV.DecMapUintIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintIntfV(rv2i(rv).(map[uint]interface{}), false, d) - } -} -func (f fastpathT) DecMapUintIntfX(vp *map[uint]interface{}, d *Decoder) { - v, changed := f.DecMapUintIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintIntfV(v map[uint]interface{}, canChange bool, - d *Decoder) (_ map[uint]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]string) - v, changed := fastpathTV.DecMapUintStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintStringV(rv2i(rv).(map[uint]string), false, d) - } -} -func (f fastpathT) DecMapUintStringX(vp *map[uint]string, d *Decoder) { - v, changed := f.DecMapUintStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintStringV(v map[uint]string, canChange bool, - d *Decoder) (_ map[uint]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint) - v, changed := fastpathTV.DecMapUintUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUintV(rv2i(rv).(map[uint]uint), false, d) - } -} -func (f fastpathT) DecMapUintUintX(vp *map[uint]uint, d *Decoder) { - v, changed := f.DecMapUintUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUintV(v map[uint]uint, canChange bool, - d *Decoder) (_ map[uint]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint8) - v, changed := fastpathTV.DecMapUintUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint8V(rv2i(rv).(map[uint]uint8), false, d) - } -} -func (f fastpathT) DecMapUintUint8X(vp *map[uint]uint8, d *Decoder) { - v, changed := f.DecMapUintUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint8V(v map[uint]uint8, canChange bool, - d *Decoder) (_ map[uint]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint16) - v, changed := fastpathTV.DecMapUintUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint16V(rv2i(rv).(map[uint]uint16), false, d) - } -} -func (f fastpathT) DecMapUintUint16X(vp *map[uint]uint16, d *Decoder) { - v, changed := f.DecMapUintUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint16V(v map[uint]uint16, canChange bool, - d *Decoder) (_ map[uint]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint32) - v, changed := fastpathTV.DecMapUintUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint32V(rv2i(rv).(map[uint]uint32), false, d) - } -} -func (f fastpathT) DecMapUintUint32X(vp *map[uint]uint32, d *Decoder) { - v, changed := f.DecMapUintUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint32V(v map[uint]uint32, canChange bool, - d *Decoder) (_ map[uint]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint64) - v, changed := fastpathTV.DecMapUintUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint64V(rv2i(rv).(map[uint]uint64), false, d) - } -} -func (f fastpathT) DecMapUintUint64X(vp *map[uint]uint64, d *Decoder) { - v, changed := f.DecMapUintUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint64V(v map[uint]uint64, canChange bool, - d *Decoder) (_ map[uint]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uintptr) - v, changed := fastpathTV.DecMapUintUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUintptrV(rv2i(rv).(map[uint]uintptr), false, d) - } -} -func (f fastpathT) DecMapUintUintptrX(vp *map[uint]uintptr, d *Decoder) { - v, changed := f.DecMapUintUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUintptrV(v map[uint]uintptr, canChange bool, - d *Decoder) (_ map[uint]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int) - v, changed := fastpathTV.DecMapUintIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintIntV(rv2i(rv).(map[uint]int), false, d) - } -} -func (f fastpathT) DecMapUintIntX(vp *map[uint]int, d *Decoder) { - v, changed := f.DecMapUintIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintIntV(v map[uint]int, canChange bool, - d *Decoder) (_ map[uint]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int8) - v, changed := fastpathTV.DecMapUintInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt8V(rv2i(rv).(map[uint]int8), false, d) - } -} -func (f fastpathT) DecMapUintInt8X(vp *map[uint]int8, d *Decoder) { - v, changed := f.DecMapUintInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt8V(v map[uint]int8, canChange bool, - d *Decoder) (_ map[uint]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int16) - v, changed := fastpathTV.DecMapUintInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt16V(rv2i(rv).(map[uint]int16), false, d) - } -} -func (f fastpathT) DecMapUintInt16X(vp *map[uint]int16, d *Decoder) { - v, changed := f.DecMapUintInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt16V(v map[uint]int16, canChange bool, - d *Decoder) (_ map[uint]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int32) - v, changed := fastpathTV.DecMapUintInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt32V(rv2i(rv).(map[uint]int32), false, d) - } -} -func (f fastpathT) DecMapUintInt32X(vp *map[uint]int32, d *Decoder) { - v, changed := f.DecMapUintInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt32V(v map[uint]int32, canChange bool, - d *Decoder) (_ map[uint]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int64) - v, changed := fastpathTV.DecMapUintInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt64V(rv2i(rv).(map[uint]int64), false, d) - } -} -func (f fastpathT) DecMapUintInt64X(vp *map[uint]int64, d *Decoder) { - v, changed := f.DecMapUintInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt64V(v map[uint]int64, canChange bool, - d *Decoder) (_ map[uint]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]float32) - v, changed := fastpathTV.DecMapUintFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintFloat32V(rv2i(rv).(map[uint]float32), false, d) - } -} -func (f fastpathT) DecMapUintFloat32X(vp *map[uint]float32, d *Decoder) { - v, changed := f.DecMapUintFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintFloat32V(v map[uint]float32, canChange bool, - d *Decoder) (_ map[uint]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]float64) - v, changed := fastpathTV.DecMapUintFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintFloat64V(rv2i(rv).(map[uint]float64), false, d) - } -} -func (f fastpathT) DecMapUintFloat64X(vp *map[uint]float64, d *Decoder) { - v, changed := f.DecMapUintFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintFloat64V(v map[uint]float64, canChange bool, - d *Decoder) (_ map[uint]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]bool) - v, changed := fastpathTV.DecMapUintBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintBoolV(rv2i(rv).(map[uint]bool), false, d) - } -} -func (f fastpathT) DecMapUintBoolX(vp *map[uint]bool, d *Decoder) { - v, changed := f.DecMapUintBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintBoolV(v map[uint]bool, canChange bool, - d *Decoder) (_ map[uint]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]interface{}) - v, changed := fastpathTV.DecMapUint8IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint8IntfX(vp *map[uint8]interface{}, d *Decoder) { - v, changed := f.DecMapUint8IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8IntfV(v map[uint8]interface{}, canChange bool, - d *Decoder) (_ map[uint8]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[uint8]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint8 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]string) - v, changed := fastpathTV.DecMapUint8StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8StringV(rv2i(rv).(map[uint8]string), false, d) - } -} -func (f fastpathT) DecMapUint8StringX(vp *map[uint8]string, d *Decoder) { - v, changed := f.DecMapUint8StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8StringV(v map[uint8]string, canChange bool, - d *Decoder) (_ map[uint8]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[uint8]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint) - v, changed := fastpathTV.DecMapUint8UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8UintV(rv2i(rv).(map[uint8]uint), false, d) - } -} -func (f fastpathT) DecMapUint8UintX(vp *map[uint8]uint, d *Decoder) { - v, changed := f.DecMapUint8UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8UintV(v map[uint8]uint, canChange bool, - d *Decoder) (_ map[uint8]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint8) - v, changed := fastpathTV.DecMapUint8Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint8V(rv2i(rv).(map[uint8]uint8), false, d) - } -} -func (f fastpathT) DecMapUint8Uint8X(vp *map[uint8]uint8, d *Decoder) { - v, changed := f.DecMapUint8Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint8V(v map[uint8]uint8, canChange bool, - d *Decoder) (_ map[uint8]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint16) - v, changed := fastpathTV.DecMapUint8Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint16V(rv2i(rv).(map[uint8]uint16), false, d) - } -} -func (f fastpathT) DecMapUint8Uint16X(vp *map[uint8]uint16, d *Decoder) { - v, changed := f.DecMapUint8Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint16V(v map[uint8]uint16, canChange bool, - d *Decoder) (_ map[uint8]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint8]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint32) - v, changed := fastpathTV.DecMapUint8Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint32V(rv2i(rv).(map[uint8]uint32), false, d) - } -} -func (f fastpathT) DecMapUint8Uint32X(vp *map[uint8]uint32, d *Decoder) { - v, changed := f.DecMapUint8Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint32V(v map[uint8]uint32, canChange bool, - d *Decoder) (_ map[uint8]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint64) - v, changed := fastpathTV.DecMapUint8Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint64V(rv2i(rv).(map[uint8]uint64), false, d) - } -} -func (f fastpathT) DecMapUint8Uint64X(vp *map[uint8]uint64, d *Decoder) { - v, changed := f.DecMapUint8Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint64V(v map[uint8]uint64, canChange bool, - d *Decoder) (_ map[uint8]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uintptr) - v, changed := fastpathTV.DecMapUint8UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8UintptrV(rv2i(rv).(map[uint8]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint8UintptrX(vp *map[uint8]uintptr, d *Decoder) { - v, changed := f.DecMapUint8UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8UintptrV(v map[uint8]uintptr, canChange bool, - d *Decoder) (_ map[uint8]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int) - v, changed := fastpathTV.DecMapUint8IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8IntV(rv2i(rv).(map[uint8]int), false, d) - } -} -func (f fastpathT) DecMapUint8IntX(vp *map[uint8]int, d *Decoder) { - v, changed := f.DecMapUint8IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8IntV(v map[uint8]int, canChange bool, - d *Decoder) (_ map[uint8]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int8) - v, changed := fastpathTV.DecMapUint8Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int8V(rv2i(rv).(map[uint8]int8), false, d) - } -} -func (f fastpathT) DecMapUint8Int8X(vp *map[uint8]int8, d *Decoder) { - v, changed := f.DecMapUint8Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int8V(v map[uint8]int8, canChange bool, - d *Decoder) (_ map[uint8]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int16) - v, changed := fastpathTV.DecMapUint8Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int16V(rv2i(rv).(map[uint8]int16), false, d) - } -} -func (f fastpathT) DecMapUint8Int16X(vp *map[uint8]int16, d *Decoder) { - v, changed := f.DecMapUint8Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int16V(v map[uint8]int16, canChange bool, - d *Decoder) (_ map[uint8]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint8]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int32) - v, changed := fastpathTV.DecMapUint8Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int32V(rv2i(rv).(map[uint8]int32), false, d) - } -} -func (f fastpathT) DecMapUint8Int32X(vp *map[uint8]int32, d *Decoder) { - v, changed := f.DecMapUint8Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int32V(v map[uint8]int32, canChange bool, - d *Decoder) (_ map[uint8]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int64) - v, changed := fastpathTV.DecMapUint8Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int64V(rv2i(rv).(map[uint8]int64), false, d) - } -} -func (f fastpathT) DecMapUint8Int64X(vp *map[uint8]int64, d *Decoder) { - v, changed := f.DecMapUint8Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int64V(v map[uint8]int64, canChange bool, - d *Decoder) (_ map[uint8]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]float32) - v, changed := fastpathTV.DecMapUint8Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Float32V(rv2i(rv).(map[uint8]float32), false, d) - } -} -func (f fastpathT) DecMapUint8Float32X(vp *map[uint8]float32, d *Decoder) { - v, changed := f.DecMapUint8Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Float32V(v map[uint8]float32, canChange bool, - d *Decoder) (_ map[uint8]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]float64) - v, changed := fastpathTV.DecMapUint8Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Float64V(rv2i(rv).(map[uint8]float64), false, d) - } -} -func (f fastpathT) DecMapUint8Float64X(vp *map[uint8]float64, d *Decoder) { - v, changed := f.DecMapUint8Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Float64V(v map[uint8]float64, canChange bool, - d *Decoder) (_ map[uint8]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]bool) - v, changed := fastpathTV.DecMapUint8BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8BoolV(rv2i(rv).(map[uint8]bool), false, d) - } -} -func (f fastpathT) DecMapUint8BoolX(vp *map[uint8]bool, d *Decoder) { - v, changed := f.DecMapUint8BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8BoolV(v map[uint8]bool, canChange bool, - d *Decoder) (_ map[uint8]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint8 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]interface{}) - v, changed := fastpathTV.DecMapUint16IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16IntfV(rv2i(rv).(map[uint16]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint16IntfX(vp *map[uint16]interface{}, d *Decoder) { - v, changed := f.DecMapUint16IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16IntfV(v map[uint16]interface{}, canChange bool, - d *Decoder) (_ map[uint16]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[uint16]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint16 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]string) - v, changed := fastpathTV.DecMapUint16StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16StringV(rv2i(rv).(map[uint16]string), false, d) - } -} -func (f fastpathT) DecMapUint16StringX(vp *map[uint16]string, d *Decoder) { - v, changed := f.DecMapUint16StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16StringV(v map[uint16]string, canChange bool, - d *Decoder) (_ map[uint16]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[uint16]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint) - v, changed := fastpathTV.DecMapUint16UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16UintV(rv2i(rv).(map[uint16]uint), false, d) - } -} -func (f fastpathT) DecMapUint16UintX(vp *map[uint16]uint, d *Decoder) { - v, changed := f.DecMapUint16UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16UintV(v map[uint16]uint, canChange bool, - d *Decoder) (_ map[uint16]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint8) - v, changed := fastpathTV.DecMapUint16Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint8V(rv2i(rv).(map[uint16]uint8), false, d) - } -} -func (f fastpathT) DecMapUint16Uint8X(vp *map[uint16]uint8, d *Decoder) { - v, changed := f.DecMapUint16Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint8V(v map[uint16]uint8, canChange bool, - d *Decoder) (_ map[uint16]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint16) - v, changed := fastpathTV.DecMapUint16Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint16V(rv2i(rv).(map[uint16]uint16), false, d) - } -} -func (f fastpathT) DecMapUint16Uint16X(vp *map[uint16]uint16, d *Decoder) { - v, changed := f.DecMapUint16Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint16V(v map[uint16]uint16, canChange bool, - d *Decoder) (_ map[uint16]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[uint16]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint32) - v, changed := fastpathTV.DecMapUint16Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint32V(rv2i(rv).(map[uint16]uint32), false, d) - } -} -func (f fastpathT) DecMapUint16Uint32X(vp *map[uint16]uint32, d *Decoder) { - v, changed := f.DecMapUint16Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint32V(v map[uint16]uint32, canChange bool, - d *Decoder) (_ map[uint16]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint64) - v, changed := fastpathTV.DecMapUint16Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint64V(rv2i(rv).(map[uint16]uint64), false, d) - } -} -func (f fastpathT) DecMapUint16Uint64X(vp *map[uint16]uint64, d *Decoder) { - v, changed := f.DecMapUint16Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint64V(v map[uint16]uint64, canChange bool, - d *Decoder) (_ map[uint16]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uintptr) - v, changed := fastpathTV.DecMapUint16UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16UintptrV(rv2i(rv).(map[uint16]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint16UintptrX(vp *map[uint16]uintptr, d *Decoder) { - v, changed := f.DecMapUint16UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16UintptrV(v map[uint16]uintptr, canChange bool, - d *Decoder) (_ map[uint16]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int) - v, changed := fastpathTV.DecMapUint16IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16IntV(rv2i(rv).(map[uint16]int), false, d) - } -} -func (f fastpathT) DecMapUint16IntX(vp *map[uint16]int, d *Decoder) { - v, changed := f.DecMapUint16IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16IntV(v map[uint16]int, canChange bool, - d *Decoder) (_ map[uint16]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int8) - v, changed := fastpathTV.DecMapUint16Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int8V(rv2i(rv).(map[uint16]int8), false, d) - } -} -func (f fastpathT) DecMapUint16Int8X(vp *map[uint16]int8, d *Decoder) { - v, changed := f.DecMapUint16Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int8V(v map[uint16]int8, canChange bool, - d *Decoder) (_ map[uint16]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int16) - v, changed := fastpathTV.DecMapUint16Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int16V(rv2i(rv).(map[uint16]int16), false, d) - } -} -func (f fastpathT) DecMapUint16Int16X(vp *map[uint16]int16, d *Decoder) { - v, changed := f.DecMapUint16Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int16V(v map[uint16]int16, canChange bool, - d *Decoder) (_ map[uint16]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[uint16]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int32) - v, changed := fastpathTV.DecMapUint16Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int32V(rv2i(rv).(map[uint16]int32), false, d) - } -} -func (f fastpathT) DecMapUint16Int32X(vp *map[uint16]int32, d *Decoder) { - v, changed := f.DecMapUint16Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int32V(v map[uint16]int32, canChange bool, - d *Decoder) (_ map[uint16]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int64) - v, changed := fastpathTV.DecMapUint16Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int64V(rv2i(rv).(map[uint16]int64), false, d) - } -} -func (f fastpathT) DecMapUint16Int64X(vp *map[uint16]int64, d *Decoder) { - v, changed := f.DecMapUint16Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int64V(v map[uint16]int64, canChange bool, - d *Decoder) (_ map[uint16]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]float32) - v, changed := fastpathTV.DecMapUint16Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Float32V(rv2i(rv).(map[uint16]float32), false, d) - } -} -func (f fastpathT) DecMapUint16Float32X(vp *map[uint16]float32, d *Decoder) { - v, changed := f.DecMapUint16Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Float32V(v map[uint16]float32, canChange bool, - d *Decoder) (_ map[uint16]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]float64) - v, changed := fastpathTV.DecMapUint16Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Float64V(rv2i(rv).(map[uint16]float64), false, d) - } -} -func (f fastpathT) DecMapUint16Float64X(vp *map[uint16]float64, d *Decoder) { - v, changed := f.DecMapUint16Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Float64V(v map[uint16]float64, canChange bool, - d *Decoder) (_ map[uint16]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]bool) - v, changed := fastpathTV.DecMapUint16BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16BoolV(rv2i(rv).(map[uint16]bool), false, d) - } -} -func (f fastpathT) DecMapUint16BoolX(vp *map[uint16]bool, d *Decoder) { - v, changed := f.DecMapUint16BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16BoolV(v map[uint16]bool, canChange bool, - d *Decoder) (_ map[uint16]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint16 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]interface{}) - v, changed := fastpathTV.DecMapUint32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32IntfV(rv2i(rv).(map[uint32]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint32IntfX(vp *map[uint32]interface{}, d *Decoder) { - v, changed := f.DecMapUint32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32IntfV(v map[uint32]interface{}, canChange bool, - d *Decoder) (_ map[uint32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[uint32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]string) - v, changed := fastpathTV.DecMapUint32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32StringV(rv2i(rv).(map[uint32]string), false, d) - } -} -func (f fastpathT) DecMapUint32StringX(vp *map[uint32]string, d *Decoder) { - v, changed := f.DecMapUint32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32StringV(v map[uint32]string, canChange bool, - d *Decoder) (_ map[uint32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[uint32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint) - v, changed := fastpathTV.DecMapUint32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32UintV(rv2i(rv).(map[uint32]uint), false, d) - } -} -func (f fastpathT) DecMapUint32UintX(vp *map[uint32]uint, d *Decoder) { - v, changed := f.DecMapUint32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32UintV(v map[uint32]uint, canChange bool, - d *Decoder) (_ map[uint32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint8) - v, changed := fastpathTV.DecMapUint32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint8V(rv2i(rv).(map[uint32]uint8), false, d) - } -} -func (f fastpathT) DecMapUint32Uint8X(vp *map[uint32]uint8, d *Decoder) { - v, changed := f.DecMapUint32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint8V(v map[uint32]uint8, canChange bool, - d *Decoder) (_ map[uint32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint16) - v, changed := fastpathTV.DecMapUint32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint16V(rv2i(rv).(map[uint32]uint16), false, d) - } -} -func (f fastpathT) DecMapUint32Uint16X(vp *map[uint32]uint16, d *Decoder) { - v, changed := f.DecMapUint32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint16V(v map[uint32]uint16, canChange bool, - d *Decoder) (_ map[uint32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint32) - v, changed := fastpathTV.DecMapUint32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint32V(rv2i(rv).(map[uint32]uint32), false, d) - } -} -func (f fastpathT) DecMapUint32Uint32X(vp *map[uint32]uint32, d *Decoder) { - v, changed := f.DecMapUint32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint32V(v map[uint32]uint32, canChange bool, - d *Decoder) (_ map[uint32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint64) - v, changed := fastpathTV.DecMapUint32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint64V(rv2i(rv).(map[uint32]uint64), false, d) - } -} -func (f fastpathT) DecMapUint32Uint64X(vp *map[uint32]uint64, d *Decoder) { - v, changed := f.DecMapUint32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint64V(v map[uint32]uint64, canChange bool, - d *Decoder) (_ map[uint32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uintptr) - v, changed := fastpathTV.DecMapUint32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32UintptrV(rv2i(rv).(map[uint32]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint32UintptrX(vp *map[uint32]uintptr, d *Decoder) { - v, changed := f.DecMapUint32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32UintptrV(v map[uint32]uintptr, canChange bool, - d *Decoder) (_ map[uint32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int) - v, changed := fastpathTV.DecMapUint32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32IntV(rv2i(rv).(map[uint32]int), false, d) - } -} -func (f fastpathT) DecMapUint32IntX(vp *map[uint32]int, d *Decoder) { - v, changed := f.DecMapUint32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32IntV(v map[uint32]int, canChange bool, - d *Decoder) (_ map[uint32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int8) - v, changed := fastpathTV.DecMapUint32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int8V(rv2i(rv).(map[uint32]int8), false, d) - } -} -func (f fastpathT) DecMapUint32Int8X(vp *map[uint32]int8, d *Decoder) { - v, changed := f.DecMapUint32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int8V(v map[uint32]int8, canChange bool, - d *Decoder) (_ map[uint32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int16) - v, changed := fastpathTV.DecMapUint32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int16V(rv2i(rv).(map[uint32]int16), false, d) - } -} -func (f fastpathT) DecMapUint32Int16X(vp *map[uint32]int16, d *Decoder) { - v, changed := f.DecMapUint32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int16V(v map[uint32]int16, canChange bool, - d *Decoder) (_ map[uint32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int32) - v, changed := fastpathTV.DecMapUint32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int32V(rv2i(rv).(map[uint32]int32), false, d) - } -} -func (f fastpathT) DecMapUint32Int32X(vp *map[uint32]int32, d *Decoder) { - v, changed := f.DecMapUint32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int32V(v map[uint32]int32, canChange bool, - d *Decoder) (_ map[uint32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int64) - v, changed := fastpathTV.DecMapUint32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int64V(rv2i(rv).(map[uint32]int64), false, d) - } -} -func (f fastpathT) DecMapUint32Int64X(vp *map[uint32]int64, d *Decoder) { - v, changed := f.DecMapUint32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int64V(v map[uint32]int64, canChange bool, - d *Decoder) (_ map[uint32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]float32) - v, changed := fastpathTV.DecMapUint32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Float32V(rv2i(rv).(map[uint32]float32), false, d) - } -} -func (f fastpathT) DecMapUint32Float32X(vp *map[uint32]float32, d *Decoder) { - v, changed := f.DecMapUint32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Float32V(v map[uint32]float32, canChange bool, - d *Decoder) (_ map[uint32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]float64) - v, changed := fastpathTV.DecMapUint32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Float64V(rv2i(rv).(map[uint32]float64), false, d) - } -} -func (f fastpathT) DecMapUint32Float64X(vp *map[uint32]float64, d *Decoder) { - v, changed := f.DecMapUint32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Float64V(v map[uint32]float64, canChange bool, - d *Decoder) (_ map[uint32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]bool) - v, changed := fastpathTV.DecMapUint32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32BoolV(rv2i(rv).(map[uint32]bool), false, d) - } -} -func (f fastpathT) DecMapUint32BoolX(vp *map[uint32]bool, d *Decoder) { - v, changed := f.DecMapUint32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32BoolV(v map[uint32]bool, canChange bool, - d *Decoder) (_ map[uint32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]interface{}) - v, changed := fastpathTV.DecMapUint64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64IntfV(rv2i(rv).(map[uint64]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint64IntfX(vp *map[uint64]interface{}, d *Decoder) { - v, changed := f.DecMapUint64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64IntfV(v map[uint64]interface{}, canChange bool, - d *Decoder) (_ map[uint64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]string) - v, changed := fastpathTV.DecMapUint64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64StringV(rv2i(rv).(map[uint64]string), false, d) - } -} -func (f fastpathT) DecMapUint64StringX(vp *map[uint64]string, d *Decoder) { - v, changed := f.DecMapUint64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64StringV(v map[uint64]string, canChange bool, - d *Decoder) (_ map[uint64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint) - v, changed := fastpathTV.DecMapUint64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64UintV(rv2i(rv).(map[uint64]uint), false, d) - } -} -func (f fastpathT) DecMapUint64UintX(vp *map[uint64]uint, d *Decoder) { - v, changed := f.DecMapUint64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64UintV(v map[uint64]uint, canChange bool, - d *Decoder) (_ map[uint64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint8) - v, changed := fastpathTV.DecMapUint64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint8V(rv2i(rv).(map[uint64]uint8), false, d) - } -} -func (f fastpathT) DecMapUint64Uint8X(vp *map[uint64]uint8, d *Decoder) { - v, changed := f.DecMapUint64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint8V(v map[uint64]uint8, canChange bool, - d *Decoder) (_ map[uint64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint16) - v, changed := fastpathTV.DecMapUint64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint16V(rv2i(rv).(map[uint64]uint16), false, d) - } -} -func (f fastpathT) DecMapUint64Uint16X(vp *map[uint64]uint16, d *Decoder) { - v, changed := f.DecMapUint64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint16V(v map[uint64]uint16, canChange bool, - d *Decoder) (_ map[uint64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint32) - v, changed := fastpathTV.DecMapUint64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint32V(rv2i(rv).(map[uint64]uint32), false, d) - } -} -func (f fastpathT) DecMapUint64Uint32X(vp *map[uint64]uint32, d *Decoder) { - v, changed := f.DecMapUint64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint32V(v map[uint64]uint32, canChange bool, - d *Decoder) (_ map[uint64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint64) - v, changed := fastpathTV.DecMapUint64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint64V(rv2i(rv).(map[uint64]uint64), false, d) - } -} -func (f fastpathT) DecMapUint64Uint64X(vp *map[uint64]uint64, d *Decoder) { - v, changed := f.DecMapUint64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint64V(v map[uint64]uint64, canChange bool, - d *Decoder) (_ map[uint64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uintptr) - v, changed := fastpathTV.DecMapUint64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64UintptrV(rv2i(rv).(map[uint64]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint64UintptrX(vp *map[uint64]uintptr, d *Decoder) { - v, changed := f.DecMapUint64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64UintptrV(v map[uint64]uintptr, canChange bool, - d *Decoder) (_ map[uint64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int) - v, changed := fastpathTV.DecMapUint64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64IntV(rv2i(rv).(map[uint64]int), false, d) - } -} -func (f fastpathT) DecMapUint64IntX(vp *map[uint64]int, d *Decoder) { - v, changed := f.DecMapUint64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64IntV(v map[uint64]int, canChange bool, - d *Decoder) (_ map[uint64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int8) - v, changed := fastpathTV.DecMapUint64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int8V(rv2i(rv).(map[uint64]int8), false, d) - } -} -func (f fastpathT) DecMapUint64Int8X(vp *map[uint64]int8, d *Decoder) { - v, changed := f.DecMapUint64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int8V(v map[uint64]int8, canChange bool, - d *Decoder) (_ map[uint64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int16) - v, changed := fastpathTV.DecMapUint64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int16V(rv2i(rv).(map[uint64]int16), false, d) - } -} -func (f fastpathT) DecMapUint64Int16X(vp *map[uint64]int16, d *Decoder) { - v, changed := f.DecMapUint64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int16V(v map[uint64]int16, canChange bool, - d *Decoder) (_ map[uint64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int32) - v, changed := fastpathTV.DecMapUint64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int32V(rv2i(rv).(map[uint64]int32), false, d) - } -} -func (f fastpathT) DecMapUint64Int32X(vp *map[uint64]int32, d *Decoder) { - v, changed := f.DecMapUint64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int32V(v map[uint64]int32, canChange bool, - d *Decoder) (_ map[uint64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int64) - v, changed := fastpathTV.DecMapUint64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int64V(rv2i(rv).(map[uint64]int64), false, d) - } -} -func (f fastpathT) DecMapUint64Int64X(vp *map[uint64]int64, d *Decoder) { - v, changed := f.DecMapUint64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int64V(v map[uint64]int64, canChange bool, - d *Decoder) (_ map[uint64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]float32) - v, changed := fastpathTV.DecMapUint64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Float32V(rv2i(rv).(map[uint64]float32), false, d) - } -} -func (f fastpathT) DecMapUint64Float32X(vp *map[uint64]float32, d *Decoder) { - v, changed := f.DecMapUint64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Float32V(v map[uint64]float32, canChange bool, - d *Decoder) (_ map[uint64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]float64) - v, changed := fastpathTV.DecMapUint64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Float64V(rv2i(rv).(map[uint64]float64), false, d) - } -} -func (f fastpathT) DecMapUint64Float64X(vp *map[uint64]float64, d *Decoder) { - v, changed := f.DecMapUint64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Float64V(v map[uint64]float64, canChange bool, - d *Decoder) (_ map[uint64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]bool) - v, changed := fastpathTV.DecMapUint64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64BoolV(rv2i(rv).(map[uint64]bool), false, d) - } -} -func (f fastpathT) DecMapUint64BoolX(vp *map[uint64]bool, d *Decoder) { - v, changed := f.DecMapUint64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64BoolV(v map[uint64]bool, canChange bool, - d *Decoder) (_ map[uint64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uint64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]interface{}) - v, changed := fastpathTV.DecMapUintptrIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrIntfV(rv2i(rv).(map[uintptr]interface{}), false, d) - } -} -func (f fastpathT) DecMapUintptrIntfX(vp *map[uintptr]interface{}, d *Decoder) { - v, changed := f.DecMapUintptrIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrIntfV(v map[uintptr]interface{}, canChange bool, - d *Decoder) (_ map[uintptr]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uintptr]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uintptr - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]string) - v, changed := fastpathTV.DecMapUintptrStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrStringV(rv2i(rv).(map[uintptr]string), false, d) - } -} -func (f fastpathT) DecMapUintptrStringX(vp *map[uintptr]string, d *Decoder) { - v, changed := f.DecMapUintptrStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrStringV(v map[uintptr]string, canChange bool, - d *Decoder) (_ map[uintptr]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uintptr]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint) - v, changed := fastpathTV.DecMapUintptrUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUintV(rv2i(rv).(map[uintptr]uint), false, d) - } -} -func (f fastpathT) DecMapUintptrUintX(vp *map[uintptr]uint, d *Decoder) { - v, changed := f.DecMapUintptrUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUintV(v map[uintptr]uint, canChange bool, - d *Decoder) (_ map[uintptr]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint8) - v, changed := fastpathTV.DecMapUintptrUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint8V(rv2i(rv).(map[uintptr]uint8), false, d) - } -} -func (f fastpathT) DecMapUintptrUint8X(vp *map[uintptr]uint8, d *Decoder) { - v, changed := f.DecMapUintptrUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint8V(v map[uintptr]uint8, canChange bool, - d *Decoder) (_ map[uintptr]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint16) - v, changed := fastpathTV.DecMapUintptrUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint16V(rv2i(rv).(map[uintptr]uint16), false, d) - } -} -func (f fastpathT) DecMapUintptrUint16X(vp *map[uintptr]uint16, d *Decoder) { - v, changed := f.DecMapUintptrUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint16V(v map[uintptr]uint16, canChange bool, - d *Decoder) (_ map[uintptr]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uintptr]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint32) - v, changed := fastpathTV.DecMapUintptrUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint32V(rv2i(rv).(map[uintptr]uint32), false, d) - } -} -func (f fastpathT) DecMapUintptrUint32X(vp *map[uintptr]uint32, d *Decoder) { - v, changed := f.DecMapUintptrUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint32V(v map[uintptr]uint32, canChange bool, - d *Decoder) (_ map[uintptr]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint64) - v, changed := fastpathTV.DecMapUintptrUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint64V(rv2i(rv).(map[uintptr]uint64), false, d) - } -} -func (f fastpathT) DecMapUintptrUint64X(vp *map[uintptr]uint64, d *Decoder) { - v, changed := f.DecMapUintptrUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint64V(v map[uintptr]uint64, canChange bool, - d *Decoder) (_ map[uintptr]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uintptr) - v, changed := fastpathTV.DecMapUintptrUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUintptrV(rv2i(rv).(map[uintptr]uintptr), false, d) - } -} -func (f fastpathT) DecMapUintptrUintptrX(vp *map[uintptr]uintptr, d *Decoder) { - v, changed := f.DecMapUintptrUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUintptrV(v map[uintptr]uintptr, canChange bool, - d *Decoder) (_ map[uintptr]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int) - v, changed := fastpathTV.DecMapUintptrIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrIntV(rv2i(rv).(map[uintptr]int), false, d) - } -} -func (f fastpathT) DecMapUintptrIntX(vp *map[uintptr]int, d *Decoder) { - v, changed := f.DecMapUintptrIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrIntV(v map[uintptr]int, canChange bool, - d *Decoder) (_ map[uintptr]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int8) - v, changed := fastpathTV.DecMapUintptrInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt8V(rv2i(rv).(map[uintptr]int8), false, d) - } -} -func (f fastpathT) DecMapUintptrInt8X(vp *map[uintptr]int8, d *Decoder) { - v, changed := f.DecMapUintptrInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt8V(v map[uintptr]int8, canChange bool, - d *Decoder) (_ map[uintptr]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int16) - v, changed := fastpathTV.DecMapUintptrInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt16V(rv2i(rv).(map[uintptr]int16), false, d) - } -} -func (f fastpathT) DecMapUintptrInt16X(vp *map[uintptr]int16, d *Decoder) { - v, changed := f.DecMapUintptrInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt16V(v map[uintptr]int16, canChange bool, - d *Decoder) (_ map[uintptr]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uintptr]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int32) - v, changed := fastpathTV.DecMapUintptrInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt32V(rv2i(rv).(map[uintptr]int32), false, d) - } -} -func (f fastpathT) DecMapUintptrInt32X(vp *map[uintptr]int32, d *Decoder) { - v, changed := f.DecMapUintptrInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt32V(v map[uintptr]int32, canChange bool, - d *Decoder) (_ map[uintptr]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int64) - v, changed := fastpathTV.DecMapUintptrInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt64V(rv2i(rv).(map[uintptr]int64), false, d) - } -} -func (f fastpathT) DecMapUintptrInt64X(vp *map[uintptr]int64, d *Decoder) { - v, changed := f.DecMapUintptrInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt64V(v map[uintptr]int64, canChange bool, - d *Decoder) (_ map[uintptr]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]float32) - v, changed := fastpathTV.DecMapUintptrFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrFloat32V(rv2i(rv).(map[uintptr]float32), false, d) - } -} -func (f fastpathT) DecMapUintptrFloat32X(vp *map[uintptr]float32, d *Decoder) { - v, changed := f.DecMapUintptrFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrFloat32V(v map[uintptr]float32, canChange bool, - d *Decoder) (_ map[uintptr]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]float64) - v, changed := fastpathTV.DecMapUintptrFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrFloat64V(rv2i(rv).(map[uintptr]float64), false, d) - } -} -func (f fastpathT) DecMapUintptrFloat64X(vp *map[uintptr]float64, d *Decoder) { - v, changed := f.DecMapUintptrFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrFloat64V(v map[uintptr]float64, canChange bool, - d *Decoder) (_ map[uintptr]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]bool) - v, changed := fastpathTV.DecMapUintptrBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrBoolV(rv2i(rv).(map[uintptr]bool), false, d) - } -} -func (f fastpathT) DecMapUintptrBoolX(vp *map[uintptr]bool, d *Decoder) { - v, changed := f.DecMapUintptrBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrBoolV(v map[uintptr]bool, canChange bool, - d *Decoder) (_ map[uintptr]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk uintptr - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]interface{}) - v, changed := fastpathTV.DecMapIntIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntIntfV(rv2i(rv).(map[int]interface{}), false, d) - } -} -func (f fastpathT) DecMapIntIntfX(vp *map[int]interface{}, d *Decoder) { - v, changed := f.DecMapIntIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntIntfV(v map[int]interface{}, canChange bool, - d *Decoder) (_ map[int]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]string) - v, changed := fastpathTV.DecMapIntStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntStringV(rv2i(rv).(map[int]string), false, d) - } -} -func (f fastpathT) DecMapIntStringX(vp *map[int]string, d *Decoder) { - v, changed := f.DecMapIntStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntStringV(v map[int]string, canChange bool, - d *Decoder) (_ map[int]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint) - v, changed := fastpathTV.DecMapIntUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUintV(rv2i(rv).(map[int]uint), false, d) - } -} -func (f fastpathT) DecMapIntUintX(vp *map[int]uint, d *Decoder) { - v, changed := f.DecMapIntUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUintV(v map[int]uint, canChange bool, - d *Decoder) (_ map[int]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint8) - v, changed := fastpathTV.DecMapIntUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint8V(rv2i(rv).(map[int]uint8), false, d) - } -} -func (f fastpathT) DecMapIntUint8X(vp *map[int]uint8, d *Decoder) { - v, changed := f.DecMapIntUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint8V(v map[int]uint8, canChange bool, - d *Decoder) (_ map[int]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint16) - v, changed := fastpathTV.DecMapIntUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint16V(rv2i(rv).(map[int]uint16), false, d) - } -} -func (f fastpathT) DecMapIntUint16X(vp *map[int]uint16, d *Decoder) { - v, changed := f.DecMapIntUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint16V(v map[int]uint16, canChange bool, - d *Decoder) (_ map[int]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint32) - v, changed := fastpathTV.DecMapIntUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint32V(rv2i(rv).(map[int]uint32), false, d) - } -} -func (f fastpathT) DecMapIntUint32X(vp *map[int]uint32, d *Decoder) { - v, changed := f.DecMapIntUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint32V(v map[int]uint32, canChange bool, - d *Decoder) (_ map[int]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint64) - v, changed := fastpathTV.DecMapIntUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint64V(rv2i(rv).(map[int]uint64), false, d) - } -} -func (f fastpathT) DecMapIntUint64X(vp *map[int]uint64, d *Decoder) { - v, changed := f.DecMapIntUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint64V(v map[int]uint64, canChange bool, - d *Decoder) (_ map[int]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uintptr) - v, changed := fastpathTV.DecMapIntUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUintptrV(rv2i(rv).(map[int]uintptr), false, d) - } -} -func (f fastpathT) DecMapIntUintptrX(vp *map[int]uintptr, d *Decoder) { - v, changed := f.DecMapIntUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUintptrV(v map[int]uintptr, canChange bool, - d *Decoder) (_ map[int]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int) - v, changed := fastpathTV.DecMapIntIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntIntV(rv2i(rv).(map[int]int), false, d) - } -} -func (f fastpathT) DecMapIntIntX(vp *map[int]int, d *Decoder) { - v, changed := f.DecMapIntIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntIntV(v map[int]int, canChange bool, - d *Decoder) (_ map[int]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int8) - v, changed := fastpathTV.DecMapIntInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt8V(rv2i(rv).(map[int]int8), false, d) - } -} -func (f fastpathT) DecMapIntInt8X(vp *map[int]int8, d *Decoder) { - v, changed := f.DecMapIntInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt8V(v map[int]int8, canChange bool, - d *Decoder) (_ map[int]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int16) - v, changed := fastpathTV.DecMapIntInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt16V(rv2i(rv).(map[int]int16), false, d) - } -} -func (f fastpathT) DecMapIntInt16X(vp *map[int]int16, d *Decoder) { - v, changed := f.DecMapIntInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt16V(v map[int]int16, canChange bool, - d *Decoder) (_ map[int]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int32) - v, changed := fastpathTV.DecMapIntInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt32V(rv2i(rv).(map[int]int32), false, d) - } -} -func (f fastpathT) DecMapIntInt32X(vp *map[int]int32, d *Decoder) { - v, changed := f.DecMapIntInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt32V(v map[int]int32, canChange bool, - d *Decoder) (_ map[int]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int64) - v, changed := fastpathTV.DecMapIntInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt64V(rv2i(rv).(map[int]int64), false, d) - } -} -func (f fastpathT) DecMapIntInt64X(vp *map[int]int64, d *Decoder) { - v, changed := f.DecMapIntInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt64V(v map[int]int64, canChange bool, - d *Decoder) (_ map[int]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]float32) - v, changed := fastpathTV.DecMapIntFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntFloat32V(rv2i(rv).(map[int]float32), false, d) - } -} -func (f fastpathT) DecMapIntFloat32X(vp *map[int]float32, d *Decoder) { - v, changed := f.DecMapIntFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntFloat32V(v map[int]float32, canChange bool, - d *Decoder) (_ map[int]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]float64) - v, changed := fastpathTV.DecMapIntFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntFloat64V(rv2i(rv).(map[int]float64), false, d) - } -} -func (f fastpathT) DecMapIntFloat64X(vp *map[int]float64, d *Decoder) { - v, changed := f.DecMapIntFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntFloat64V(v map[int]float64, canChange bool, - d *Decoder) (_ map[int]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]bool) - v, changed := fastpathTV.DecMapIntBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntBoolV(rv2i(rv).(map[int]bool), false, d) - } -} -func (f fastpathT) DecMapIntBoolX(vp *map[int]bool, d *Decoder) { - v, changed := f.DecMapIntBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntBoolV(v map[int]bool, canChange bool, - d *Decoder) (_ map[int]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]interface{}) - v, changed := fastpathTV.DecMapInt8IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8IntfV(rv2i(rv).(map[int8]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt8IntfX(vp *map[int8]interface{}, d *Decoder) { - v, changed := f.DecMapInt8IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8IntfV(v map[int8]interface{}, canChange bool, - d *Decoder) (_ map[int8]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[int8]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int8 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]string) - v, changed := fastpathTV.DecMapInt8StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8StringV(rv2i(rv).(map[int8]string), false, d) - } -} -func (f fastpathT) DecMapInt8StringX(vp *map[int8]string, d *Decoder) { - v, changed := f.DecMapInt8StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8StringV(v map[int8]string, canChange bool, - d *Decoder) (_ map[int8]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[int8]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint) - v, changed := fastpathTV.DecMapInt8UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8UintV(rv2i(rv).(map[int8]uint), false, d) - } -} -func (f fastpathT) DecMapInt8UintX(vp *map[int8]uint, d *Decoder) { - v, changed := f.DecMapInt8UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8UintV(v map[int8]uint, canChange bool, - d *Decoder) (_ map[int8]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint8) - v, changed := fastpathTV.DecMapInt8Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint8V(rv2i(rv).(map[int8]uint8), false, d) - } -} -func (f fastpathT) DecMapInt8Uint8X(vp *map[int8]uint8, d *Decoder) { - v, changed := f.DecMapInt8Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint8V(v map[int8]uint8, canChange bool, - d *Decoder) (_ map[int8]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint16) - v, changed := fastpathTV.DecMapInt8Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint16V(rv2i(rv).(map[int8]uint16), false, d) - } -} -func (f fastpathT) DecMapInt8Uint16X(vp *map[int8]uint16, d *Decoder) { - v, changed := f.DecMapInt8Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint16V(v map[int8]uint16, canChange bool, - d *Decoder) (_ map[int8]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int8]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint32) - v, changed := fastpathTV.DecMapInt8Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint32V(rv2i(rv).(map[int8]uint32), false, d) - } -} -func (f fastpathT) DecMapInt8Uint32X(vp *map[int8]uint32, d *Decoder) { - v, changed := f.DecMapInt8Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint32V(v map[int8]uint32, canChange bool, - d *Decoder) (_ map[int8]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint64) - v, changed := fastpathTV.DecMapInt8Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint64V(rv2i(rv).(map[int8]uint64), false, d) - } -} -func (f fastpathT) DecMapInt8Uint64X(vp *map[int8]uint64, d *Decoder) { - v, changed := f.DecMapInt8Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint64V(v map[int8]uint64, canChange bool, - d *Decoder) (_ map[int8]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uintptr) - v, changed := fastpathTV.DecMapInt8UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8UintptrV(rv2i(rv).(map[int8]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt8UintptrX(vp *map[int8]uintptr, d *Decoder) { - v, changed := f.DecMapInt8UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8UintptrV(v map[int8]uintptr, canChange bool, - d *Decoder) (_ map[int8]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int) - v, changed := fastpathTV.DecMapInt8IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8IntV(rv2i(rv).(map[int8]int), false, d) - } -} -func (f fastpathT) DecMapInt8IntX(vp *map[int8]int, d *Decoder) { - v, changed := f.DecMapInt8IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8IntV(v map[int8]int, canChange bool, - d *Decoder) (_ map[int8]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int8) - v, changed := fastpathTV.DecMapInt8Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int8V(rv2i(rv).(map[int8]int8), false, d) - } -} -func (f fastpathT) DecMapInt8Int8X(vp *map[int8]int8, d *Decoder) { - v, changed := f.DecMapInt8Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int8V(v map[int8]int8, canChange bool, - d *Decoder) (_ map[int8]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int16) - v, changed := fastpathTV.DecMapInt8Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int16V(rv2i(rv).(map[int8]int16), false, d) - } -} -func (f fastpathT) DecMapInt8Int16X(vp *map[int8]int16, d *Decoder) { - v, changed := f.DecMapInt8Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int16V(v map[int8]int16, canChange bool, - d *Decoder) (_ map[int8]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int8]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int32) - v, changed := fastpathTV.DecMapInt8Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int32V(rv2i(rv).(map[int8]int32), false, d) - } -} -func (f fastpathT) DecMapInt8Int32X(vp *map[int8]int32, d *Decoder) { - v, changed := f.DecMapInt8Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int32V(v map[int8]int32, canChange bool, - d *Decoder) (_ map[int8]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int64) - v, changed := fastpathTV.DecMapInt8Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int64V(rv2i(rv).(map[int8]int64), false, d) - } -} -func (f fastpathT) DecMapInt8Int64X(vp *map[int8]int64, d *Decoder) { - v, changed := f.DecMapInt8Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int64V(v map[int8]int64, canChange bool, - d *Decoder) (_ map[int8]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]float32) - v, changed := fastpathTV.DecMapInt8Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Float32V(rv2i(rv).(map[int8]float32), false, d) - } -} -func (f fastpathT) DecMapInt8Float32X(vp *map[int8]float32, d *Decoder) { - v, changed := f.DecMapInt8Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Float32V(v map[int8]float32, canChange bool, - d *Decoder) (_ map[int8]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]float64) - v, changed := fastpathTV.DecMapInt8Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Float64V(rv2i(rv).(map[int8]float64), false, d) - } -} -func (f fastpathT) DecMapInt8Float64X(vp *map[int8]float64, d *Decoder) { - v, changed := f.DecMapInt8Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Float64V(v map[int8]float64, canChange bool, - d *Decoder) (_ map[int8]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]bool) - v, changed := fastpathTV.DecMapInt8BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8BoolV(rv2i(rv).(map[int8]bool), false, d) - } -} -func (f fastpathT) DecMapInt8BoolX(vp *map[int8]bool, d *Decoder) { - v, changed := f.DecMapInt8BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8BoolV(v map[int8]bool, canChange bool, - d *Decoder) (_ map[int8]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int8 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]interface{}) - v, changed := fastpathTV.DecMapInt16IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16IntfV(rv2i(rv).(map[int16]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt16IntfX(vp *map[int16]interface{}, d *Decoder) { - v, changed := f.DecMapInt16IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16IntfV(v map[int16]interface{}, canChange bool, - d *Decoder) (_ map[int16]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[int16]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int16 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]string) - v, changed := fastpathTV.DecMapInt16StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16StringV(rv2i(rv).(map[int16]string), false, d) - } -} -func (f fastpathT) DecMapInt16StringX(vp *map[int16]string, d *Decoder) { - v, changed := f.DecMapInt16StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16StringV(v map[int16]string, canChange bool, - d *Decoder) (_ map[int16]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[int16]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint) - v, changed := fastpathTV.DecMapInt16UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16UintV(rv2i(rv).(map[int16]uint), false, d) - } -} -func (f fastpathT) DecMapInt16UintX(vp *map[int16]uint, d *Decoder) { - v, changed := f.DecMapInt16UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16UintV(v map[int16]uint, canChange bool, - d *Decoder) (_ map[int16]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint8) - v, changed := fastpathTV.DecMapInt16Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint8V(rv2i(rv).(map[int16]uint8), false, d) - } -} -func (f fastpathT) DecMapInt16Uint8X(vp *map[int16]uint8, d *Decoder) { - v, changed := f.DecMapInt16Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint8V(v map[int16]uint8, canChange bool, - d *Decoder) (_ map[int16]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint16) - v, changed := fastpathTV.DecMapInt16Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint16V(rv2i(rv).(map[int16]uint16), false, d) - } -} -func (f fastpathT) DecMapInt16Uint16X(vp *map[int16]uint16, d *Decoder) { - v, changed := f.DecMapInt16Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint16V(v map[int16]uint16, canChange bool, - d *Decoder) (_ map[int16]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[int16]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint32) - v, changed := fastpathTV.DecMapInt16Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint32V(rv2i(rv).(map[int16]uint32), false, d) - } -} -func (f fastpathT) DecMapInt16Uint32X(vp *map[int16]uint32, d *Decoder) { - v, changed := f.DecMapInt16Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint32V(v map[int16]uint32, canChange bool, - d *Decoder) (_ map[int16]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint64) - v, changed := fastpathTV.DecMapInt16Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint64V(rv2i(rv).(map[int16]uint64), false, d) - } -} -func (f fastpathT) DecMapInt16Uint64X(vp *map[int16]uint64, d *Decoder) { - v, changed := f.DecMapInt16Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint64V(v map[int16]uint64, canChange bool, - d *Decoder) (_ map[int16]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uintptr) - v, changed := fastpathTV.DecMapInt16UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16UintptrV(rv2i(rv).(map[int16]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt16UintptrX(vp *map[int16]uintptr, d *Decoder) { - v, changed := f.DecMapInt16UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16UintptrV(v map[int16]uintptr, canChange bool, - d *Decoder) (_ map[int16]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int) - v, changed := fastpathTV.DecMapInt16IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16IntV(rv2i(rv).(map[int16]int), false, d) - } -} -func (f fastpathT) DecMapInt16IntX(vp *map[int16]int, d *Decoder) { - v, changed := f.DecMapInt16IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16IntV(v map[int16]int, canChange bool, - d *Decoder) (_ map[int16]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int8) - v, changed := fastpathTV.DecMapInt16Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int8V(rv2i(rv).(map[int16]int8), false, d) - } -} -func (f fastpathT) DecMapInt16Int8X(vp *map[int16]int8, d *Decoder) { - v, changed := f.DecMapInt16Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int8V(v map[int16]int8, canChange bool, - d *Decoder) (_ map[int16]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int16) - v, changed := fastpathTV.DecMapInt16Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int16V(rv2i(rv).(map[int16]int16), false, d) - } -} -func (f fastpathT) DecMapInt16Int16X(vp *map[int16]int16, d *Decoder) { - v, changed := f.DecMapInt16Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int16V(v map[int16]int16, canChange bool, - d *Decoder) (_ map[int16]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[int16]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int32) - v, changed := fastpathTV.DecMapInt16Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int32V(rv2i(rv).(map[int16]int32), false, d) - } -} -func (f fastpathT) DecMapInt16Int32X(vp *map[int16]int32, d *Decoder) { - v, changed := f.DecMapInt16Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int32V(v map[int16]int32, canChange bool, - d *Decoder) (_ map[int16]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int64) - v, changed := fastpathTV.DecMapInt16Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int64V(rv2i(rv).(map[int16]int64), false, d) - } -} -func (f fastpathT) DecMapInt16Int64X(vp *map[int16]int64, d *Decoder) { - v, changed := f.DecMapInt16Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int64V(v map[int16]int64, canChange bool, - d *Decoder) (_ map[int16]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]float32) - v, changed := fastpathTV.DecMapInt16Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Float32V(rv2i(rv).(map[int16]float32), false, d) - } -} -func (f fastpathT) DecMapInt16Float32X(vp *map[int16]float32, d *Decoder) { - v, changed := f.DecMapInt16Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Float32V(v map[int16]float32, canChange bool, - d *Decoder) (_ map[int16]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]float64) - v, changed := fastpathTV.DecMapInt16Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Float64V(rv2i(rv).(map[int16]float64), false, d) - } -} -func (f fastpathT) DecMapInt16Float64X(vp *map[int16]float64, d *Decoder) { - v, changed := f.DecMapInt16Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Float64V(v map[int16]float64, canChange bool, - d *Decoder) (_ map[int16]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]bool) - v, changed := fastpathTV.DecMapInt16BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16BoolV(rv2i(rv).(map[int16]bool), false, d) - } -} -func (f fastpathT) DecMapInt16BoolX(vp *map[int16]bool, d *Decoder) { - v, changed := f.DecMapInt16BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16BoolV(v map[int16]bool, canChange bool, - d *Decoder) (_ map[int16]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int16 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]interface{}) - v, changed := fastpathTV.DecMapInt32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32IntfV(rv2i(rv).(map[int32]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt32IntfX(vp *map[int32]interface{}, d *Decoder) { - v, changed := f.DecMapInt32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32IntfV(v map[int32]interface{}, canChange bool, - d *Decoder) (_ map[int32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[int32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]string) - v, changed := fastpathTV.DecMapInt32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32StringV(rv2i(rv).(map[int32]string), false, d) - } -} -func (f fastpathT) DecMapInt32StringX(vp *map[int32]string, d *Decoder) { - v, changed := f.DecMapInt32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32StringV(v map[int32]string, canChange bool, - d *Decoder) (_ map[int32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[int32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint) - v, changed := fastpathTV.DecMapInt32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32UintV(rv2i(rv).(map[int32]uint), false, d) - } -} -func (f fastpathT) DecMapInt32UintX(vp *map[int32]uint, d *Decoder) { - v, changed := f.DecMapInt32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32UintV(v map[int32]uint, canChange bool, - d *Decoder) (_ map[int32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint8) - v, changed := fastpathTV.DecMapInt32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint8V(rv2i(rv).(map[int32]uint8), false, d) - } -} -func (f fastpathT) DecMapInt32Uint8X(vp *map[int32]uint8, d *Decoder) { - v, changed := f.DecMapInt32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint8V(v map[int32]uint8, canChange bool, - d *Decoder) (_ map[int32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint16) - v, changed := fastpathTV.DecMapInt32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint16V(rv2i(rv).(map[int32]uint16), false, d) - } -} -func (f fastpathT) DecMapInt32Uint16X(vp *map[int32]uint16, d *Decoder) { - v, changed := f.DecMapInt32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint16V(v map[int32]uint16, canChange bool, - d *Decoder) (_ map[int32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint32) - v, changed := fastpathTV.DecMapInt32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint32V(rv2i(rv).(map[int32]uint32), false, d) - } -} -func (f fastpathT) DecMapInt32Uint32X(vp *map[int32]uint32, d *Decoder) { - v, changed := f.DecMapInt32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint32V(v map[int32]uint32, canChange bool, - d *Decoder) (_ map[int32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint64) - v, changed := fastpathTV.DecMapInt32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint64V(rv2i(rv).(map[int32]uint64), false, d) - } -} -func (f fastpathT) DecMapInt32Uint64X(vp *map[int32]uint64, d *Decoder) { - v, changed := f.DecMapInt32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint64V(v map[int32]uint64, canChange bool, - d *Decoder) (_ map[int32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uintptr) - v, changed := fastpathTV.DecMapInt32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32UintptrV(rv2i(rv).(map[int32]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt32UintptrX(vp *map[int32]uintptr, d *Decoder) { - v, changed := f.DecMapInt32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32UintptrV(v map[int32]uintptr, canChange bool, - d *Decoder) (_ map[int32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int) - v, changed := fastpathTV.DecMapInt32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32IntV(rv2i(rv).(map[int32]int), false, d) - } -} -func (f fastpathT) DecMapInt32IntX(vp *map[int32]int, d *Decoder) { - v, changed := f.DecMapInt32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32IntV(v map[int32]int, canChange bool, - d *Decoder) (_ map[int32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int8) - v, changed := fastpathTV.DecMapInt32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int8V(rv2i(rv).(map[int32]int8), false, d) - } -} -func (f fastpathT) DecMapInt32Int8X(vp *map[int32]int8, d *Decoder) { - v, changed := f.DecMapInt32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int8V(v map[int32]int8, canChange bool, - d *Decoder) (_ map[int32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int16) - v, changed := fastpathTV.DecMapInt32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int16V(rv2i(rv).(map[int32]int16), false, d) - } -} -func (f fastpathT) DecMapInt32Int16X(vp *map[int32]int16, d *Decoder) { - v, changed := f.DecMapInt32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int16V(v map[int32]int16, canChange bool, - d *Decoder) (_ map[int32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int32) - v, changed := fastpathTV.DecMapInt32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int32V(rv2i(rv).(map[int32]int32), false, d) - } -} -func (f fastpathT) DecMapInt32Int32X(vp *map[int32]int32, d *Decoder) { - v, changed := f.DecMapInt32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int32V(v map[int32]int32, canChange bool, - d *Decoder) (_ map[int32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int64) - v, changed := fastpathTV.DecMapInt32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int64V(rv2i(rv).(map[int32]int64), false, d) - } -} -func (f fastpathT) DecMapInt32Int64X(vp *map[int32]int64, d *Decoder) { - v, changed := f.DecMapInt32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int64V(v map[int32]int64, canChange bool, - d *Decoder) (_ map[int32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]float32) - v, changed := fastpathTV.DecMapInt32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Float32V(rv2i(rv).(map[int32]float32), false, d) - } -} -func (f fastpathT) DecMapInt32Float32X(vp *map[int32]float32, d *Decoder) { - v, changed := f.DecMapInt32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Float32V(v map[int32]float32, canChange bool, - d *Decoder) (_ map[int32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]float64) - v, changed := fastpathTV.DecMapInt32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Float64V(rv2i(rv).(map[int32]float64), false, d) - } -} -func (f fastpathT) DecMapInt32Float64X(vp *map[int32]float64, d *Decoder) { - v, changed := f.DecMapInt32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Float64V(v map[int32]float64, canChange bool, - d *Decoder) (_ map[int32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]bool) - v, changed := fastpathTV.DecMapInt32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32BoolV(rv2i(rv).(map[int32]bool), false, d) - } -} -func (f fastpathT) DecMapInt32BoolX(vp *map[int32]bool, d *Decoder) { - v, changed := f.DecMapInt32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32BoolV(v map[int32]bool, canChange bool, - d *Decoder) (_ map[int32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]interface{}) - v, changed := fastpathTV.DecMapInt64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64IntfV(rv2i(rv).(map[int64]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt64IntfX(vp *map[int64]interface{}, d *Decoder) { - v, changed := f.DecMapInt64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64IntfV(v map[int64]interface{}, canChange bool, - d *Decoder) (_ map[int64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]string) - v, changed := fastpathTV.DecMapInt64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64StringV(rv2i(rv).(map[int64]string), false, d) - } -} -func (f fastpathT) DecMapInt64StringX(vp *map[int64]string, d *Decoder) { - v, changed := f.DecMapInt64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64StringV(v map[int64]string, canChange bool, - d *Decoder) (_ map[int64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint) - v, changed := fastpathTV.DecMapInt64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64UintV(rv2i(rv).(map[int64]uint), false, d) - } -} -func (f fastpathT) DecMapInt64UintX(vp *map[int64]uint, d *Decoder) { - v, changed := f.DecMapInt64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64UintV(v map[int64]uint, canChange bool, - d *Decoder) (_ map[int64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint8) - v, changed := fastpathTV.DecMapInt64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint8V(rv2i(rv).(map[int64]uint8), false, d) - } -} -func (f fastpathT) DecMapInt64Uint8X(vp *map[int64]uint8, d *Decoder) { - v, changed := f.DecMapInt64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint8V(v map[int64]uint8, canChange bool, - d *Decoder) (_ map[int64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint16) - v, changed := fastpathTV.DecMapInt64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint16V(rv2i(rv).(map[int64]uint16), false, d) - } -} -func (f fastpathT) DecMapInt64Uint16X(vp *map[int64]uint16, d *Decoder) { - v, changed := f.DecMapInt64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint16V(v map[int64]uint16, canChange bool, - d *Decoder) (_ map[int64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint32) - v, changed := fastpathTV.DecMapInt64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint32V(rv2i(rv).(map[int64]uint32), false, d) - } -} -func (f fastpathT) DecMapInt64Uint32X(vp *map[int64]uint32, d *Decoder) { - v, changed := f.DecMapInt64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint32V(v map[int64]uint32, canChange bool, - d *Decoder) (_ map[int64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint64) - v, changed := fastpathTV.DecMapInt64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint64V(rv2i(rv).(map[int64]uint64), false, d) - } -} -func (f fastpathT) DecMapInt64Uint64X(vp *map[int64]uint64, d *Decoder) { - v, changed := f.DecMapInt64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint64V(v map[int64]uint64, canChange bool, - d *Decoder) (_ map[int64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uintptr) - v, changed := fastpathTV.DecMapInt64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64UintptrV(rv2i(rv).(map[int64]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt64UintptrX(vp *map[int64]uintptr, d *Decoder) { - v, changed := f.DecMapInt64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64UintptrV(v map[int64]uintptr, canChange bool, - d *Decoder) (_ map[int64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int) - v, changed := fastpathTV.DecMapInt64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64IntV(rv2i(rv).(map[int64]int), false, d) - } -} -func (f fastpathT) DecMapInt64IntX(vp *map[int64]int, d *Decoder) { - v, changed := f.DecMapInt64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64IntV(v map[int64]int, canChange bool, - d *Decoder) (_ map[int64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int8) - v, changed := fastpathTV.DecMapInt64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int8V(rv2i(rv).(map[int64]int8), false, d) - } -} -func (f fastpathT) DecMapInt64Int8X(vp *map[int64]int8, d *Decoder) { - v, changed := f.DecMapInt64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int8V(v map[int64]int8, canChange bool, - d *Decoder) (_ map[int64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int16) - v, changed := fastpathTV.DecMapInt64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int16V(rv2i(rv).(map[int64]int16), false, d) - } -} -func (f fastpathT) DecMapInt64Int16X(vp *map[int64]int16, d *Decoder) { - v, changed := f.DecMapInt64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int16V(v map[int64]int16, canChange bool, - d *Decoder) (_ map[int64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int32) - v, changed := fastpathTV.DecMapInt64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int32V(rv2i(rv).(map[int64]int32), false, d) - } -} -func (f fastpathT) DecMapInt64Int32X(vp *map[int64]int32, d *Decoder) { - v, changed := f.DecMapInt64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int32V(v map[int64]int32, canChange bool, - d *Decoder) (_ map[int64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int64) - v, changed := fastpathTV.DecMapInt64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int64V(rv2i(rv).(map[int64]int64), false, d) - } -} -func (f fastpathT) DecMapInt64Int64X(vp *map[int64]int64, d *Decoder) { - v, changed := f.DecMapInt64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int64V(v map[int64]int64, canChange bool, - d *Decoder) (_ map[int64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]float32) - v, changed := fastpathTV.DecMapInt64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Float32V(rv2i(rv).(map[int64]float32), false, d) - } -} -func (f fastpathT) DecMapInt64Float32X(vp *map[int64]float32, d *Decoder) { - v, changed := f.DecMapInt64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Float32V(v map[int64]float32, canChange bool, - d *Decoder) (_ map[int64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]float64) - v, changed := fastpathTV.DecMapInt64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Float64V(rv2i(rv).(map[int64]float64), false, d) - } -} -func (f fastpathT) DecMapInt64Float64X(vp *map[int64]float64, d *Decoder) { - v, changed := f.DecMapInt64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Float64V(v map[int64]float64, canChange bool, - d *Decoder) (_ map[int64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]bool) - v, changed := fastpathTV.DecMapInt64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64BoolV(rv2i(rv).(map[int64]bool), false, d) - } -} -func (f fastpathT) DecMapInt64BoolX(vp *map[int64]bool, d *Decoder) { - v, changed := f.DecMapInt64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64BoolV(v map[int64]bool, canChange bool, - d *Decoder) (_ map[int64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk int64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]interface{}) - v, changed := fastpathTV.DecMapBoolIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolIntfV(rv2i(rv).(map[bool]interface{}), false, d) - } -} -func (f fastpathT) DecMapBoolIntfX(vp *map[bool]interface{}, d *Decoder) { - v, changed := f.DecMapBoolIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolIntfV(v map[bool]interface{}, canChange bool, - d *Decoder) (_ map[bool]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[bool]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk bool - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]string) - v, changed := fastpathTV.DecMapBoolStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolStringV(rv2i(rv).(map[bool]string), false, d) - } -} -func (f fastpathT) DecMapBoolStringX(vp *map[bool]string, d *Decoder) { - v, changed := f.DecMapBoolStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolStringV(v map[bool]string, canChange bool, - d *Decoder) (_ map[bool]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[bool]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint) - v, changed := fastpathTV.DecMapBoolUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUintV(rv2i(rv).(map[bool]uint), false, d) - } -} -func (f fastpathT) DecMapBoolUintX(vp *map[bool]uint, d *Decoder) { - v, changed := f.DecMapBoolUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUintV(v map[bool]uint, canChange bool, - d *Decoder) (_ map[bool]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint8) - v, changed := fastpathTV.DecMapBoolUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint8V(rv2i(rv).(map[bool]uint8), false, d) - } -} -func (f fastpathT) DecMapBoolUint8X(vp *map[bool]uint8, d *Decoder) { - v, changed := f.DecMapBoolUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint8V(v map[bool]uint8, canChange bool, - d *Decoder) (_ map[bool]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint16) - v, changed := fastpathTV.DecMapBoolUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint16V(rv2i(rv).(map[bool]uint16), false, d) - } -} -func (f fastpathT) DecMapBoolUint16X(vp *map[bool]uint16, d *Decoder) { - v, changed := f.DecMapBoolUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint16V(v map[bool]uint16, canChange bool, - d *Decoder) (_ map[bool]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[bool]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint32) - v, changed := fastpathTV.DecMapBoolUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint32V(rv2i(rv).(map[bool]uint32), false, d) - } -} -func (f fastpathT) DecMapBoolUint32X(vp *map[bool]uint32, d *Decoder) { - v, changed := f.DecMapBoolUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint32V(v map[bool]uint32, canChange bool, - d *Decoder) (_ map[bool]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint64) - v, changed := fastpathTV.DecMapBoolUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint64V(rv2i(rv).(map[bool]uint64), false, d) - } -} -func (f fastpathT) DecMapBoolUint64X(vp *map[bool]uint64, d *Decoder) { - v, changed := f.DecMapBoolUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint64V(v map[bool]uint64, canChange bool, - d *Decoder) (_ map[bool]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uintptr) - v, changed := fastpathTV.DecMapBoolUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUintptrV(rv2i(rv).(map[bool]uintptr), false, d) - } -} -func (f fastpathT) DecMapBoolUintptrX(vp *map[bool]uintptr, d *Decoder) { - v, changed := f.DecMapBoolUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUintptrV(v map[bool]uintptr, canChange bool, - d *Decoder) (_ map[bool]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int) - v, changed := fastpathTV.DecMapBoolIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolIntV(rv2i(rv).(map[bool]int), false, d) - } -} -func (f fastpathT) DecMapBoolIntX(vp *map[bool]int, d *Decoder) { - v, changed := f.DecMapBoolIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolIntV(v map[bool]int, canChange bool, - d *Decoder) (_ map[bool]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int8) - v, changed := fastpathTV.DecMapBoolInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt8V(rv2i(rv).(map[bool]int8), false, d) - } -} -func (f fastpathT) DecMapBoolInt8X(vp *map[bool]int8, d *Decoder) { - v, changed := f.DecMapBoolInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt8V(v map[bool]int8, canChange bool, - d *Decoder) (_ map[bool]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int16) - v, changed := fastpathTV.DecMapBoolInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt16V(rv2i(rv).(map[bool]int16), false, d) - } -} -func (f fastpathT) DecMapBoolInt16X(vp *map[bool]int16, d *Decoder) { - v, changed := f.DecMapBoolInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt16V(v map[bool]int16, canChange bool, - d *Decoder) (_ map[bool]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[bool]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int32) - v, changed := fastpathTV.DecMapBoolInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt32V(rv2i(rv).(map[bool]int32), false, d) - } -} -func (f fastpathT) DecMapBoolInt32X(vp *map[bool]int32, d *Decoder) { - v, changed := f.DecMapBoolInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt32V(v map[bool]int32, canChange bool, - d *Decoder) (_ map[bool]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int64) - v, changed := fastpathTV.DecMapBoolInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt64V(rv2i(rv).(map[bool]int64), false, d) - } -} -func (f fastpathT) DecMapBoolInt64X(vp *map[bool]int64, d *Decoder) { - v, changed := f.DecMapBoolInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt64V(v map[bool]int64, canChange bool, - d *Decoder) (_ map[bool]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]float32) - v, changed := fastpathTV.DecMapBoolFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolFloat32V(rv2i(rv).(map[bool]float32), false, d) - } -} -func (f fastpathT) DecMapBoolFloat32X(vp *map[bool]float32, d *Decoder) { - v, changed := f.DecMapBoolFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolFloat32V(v map[bool]float32, canChange bool, - d *Decoder) (_ map[bool]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]float64) - v, changed := fastpathTV.DecMapBoolFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolFloat64V(rv2i(rv).(map[bool]float64), false, d) - } -} -func (f fastpathT) DecMapBoolFloat64X(vp *map[bool]float64, d *Decoder) { - v, changed := f.DecMapBoolFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolFloat64V(v map[bool]float64, canChange bool, - d *Decoder) (_ map[bool]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]bool) - v, changed := fastpathTV.DecMapBoolBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolBoolV(rv2i(rv).(map[bool]bool), false, d) - } -} -func (f fastpathT) DecMapBoolBoolX(vp *map[bool]bool, d *Decoder) { - v, changed := f.DecMapBoolBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolBoolV(v map[bool]bool, canChange bool, - d *Decoder) (_ map[bool]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - var mk bool - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.go.tmpl deleted file mode 100644 index 7617c43506423..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.go.tmpl +++ /dev/null @@ -1,491 +0,0 @@ -// +build !notfastpath - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from fast-path.go.tmpl - DO NOT EDIT. - -package codec - -// Fast path functions try to create a fast path encode or decode implementation -// for common maps and slices. -// -// We define the functions and register then in this single file -// so as not to pollute the encode.go and decode.go, and create a dependency in there. -// This file can be omitted without causing a build failure. -// -// The advantage of fast paths is: -// - Many calls bypass reflection altogether -// -// Currently support -// - slice of all builtin types, -// - map of all builtin types to string or interface value -// - symmetrical maps of all builtin types (e.g. str-str, uint8-uint8) -// This should provide adequate "typical" implementations. -// -// Note that fast track decode functions must handle values for which an address cannot be obtained. -// For example: -// m2 := map[string]int{} -// p2 := []interface{}{m2} -// // decoding into p2 will bomb if fast track functions do not treat like unaddressable. -// - -import ( - "reflect" - "sort" -) - -const fastpathEnabled = true - -const fastpathMapBySliceErrMsg = "mapBySlice requires even slice length, but got %v" - -type fastpathT struct {} - -var fastpathTV fastpathT - -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} - -type fastpathA [{{ .FastpathLen }}]fastpathE - -func (x *fastpathA) index(rtid uintptr) int { - // use binary search to grab the index (adapted from sort/search.go) - // Note: we use goto (instead of for loop) so this can be inlined. - // h, i, j := 0, 0, len(x) - var h, i uint - var j = uint(len(x)) -LOOP: - if i < j { - h = i + (j-i)/2 - if x[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - goto LOOP - } - if i < uint(len(x)) && x[i].rtid == rtid { - return int(i) - } - return -1 -} - -type fastpathAslice []fastpathE - -func (x fastpathAslice) Len() int { return len(x) } -func (x fastpathAslice) Less(i, j int) bool { return x[uint(i)].rtid < x[uint(j)].rtid } -func (x fastpathAslice) Swap(i, j int) { x[uint(i)], x[uint(j)] = x[uint(j)], x[uint(i)] } - -var fastpathAV fastpathA - -// due to possible initialization loop error, make fastpath in an init() -func init() { - var i uint = 0 - fn := func(v interface{}, - fe func(*Encoder, *codecFnInfo, reflect.Value), - fd func(*Decoder, *codecFnInfo, reflect.Value)) { - xrt := reflect.TypeOf(v) - xptr := rt2id(xrt) - fastpathAV[i] = fastpathE{xptr, xrt, fe, fd} - i++ - } - {{/* do not register []uint8 in fast-path */}} - {{range .Values}}{{if not .Primitive}}{{if not .MapKey }}{{if ne .Elem "uint8"}} - fn([]{{ .Elem }}(nil), (*Encoder).{{ .MethodNamePfx "fastpathEnc" false }}R, (*Decoder).{{ .MethodNamePfx "fastpathDec" false }}R){{end}}{{end}}{{end}}{{end}} - - {{range .Values}}{{if not .Primitive}}{{if .MapKey }} - fn(map[{{ .MapKey }}]{{ .Elem }}(nil), (*Encoder).{{ .MethodNamePfx "fastpathEnc" false }}R, (*Decoder).{{ .MethodNamePfx "fastpathDec" false }}R){{end}}{{end}}{{end}} - - sort.Sort(fastpathAslice(fastpathAV[:])) -} - -// -- encode - -// -- -- fast path type switch -func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { - switch v := iv.(type) { - -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }}{{if ne .Elem "uint8"}} - case []{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(v, e) - case *[]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(*v, e){{/* -*/}}{{end}}{{end}}{{end}}{{end}} - -{{range .Values}}{{if not .Primitive}}{{if .MapKey }} - case map[{{ .MapKey }}]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(v, e) - case *map[{{ .MapKey }}]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(*v, e){{/* -*/}}{{end}}{{end}}{{end}} - - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -{{/* -**** removing this block, as they are never called directly **** - - - -**** removing this block, as they are never called directly **** - - - -func fastpathEncodeTypeSwitchSlice(iv interface{}, e *Encoder) bool { - switch v := iv.(type) { -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }} - case []{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(v, e) - case *[]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(*v, e) -{{end}}{{end}}{{end}} - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { - switch v := iv.(type) { -{{range .Values}}{{if not .Primitive}}{{if .MapKey }} - case map[{{ .MapKey }}]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(v, e) - case *map[{{ .MapKey }}]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(*v, e) -{{end}}{{end}}{{end}} - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - - - -**** removing this block, as they are never called directly **** - - - -**** removing this block, as they are never called directly **** -*/}} - -// -- -- fast path functions -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }} -func (e *Encoder) {{ .MethodNamePfx "fastpathEnc" false }}R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.{{ .MethodNamePfx "EncAsMap" false }}V(rv2i(rv).([]{{ .Elem }}), e) - } else { - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(rv2i(rv).([]{{ .Elem }}), e) - } -} -func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v []{{ .Elem }}, e *Encoder) { - if v == nil { e.e.EncodeNil(); return } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - for _, v2 := range v { - if esep { ee.WriteArrayElem() } - {{ encmd .Elem "v2"}} - } - ee.WriteArrayEnd() -} -func (_ fastpathT) {{ .MethodNamePfx "EncAsMap" false }}V(v []{{ .Elem }}, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf(fastpathMapBySliceErrMsg, len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - for j, v2 := range v { - if esep { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } - {{ encmd .Elem "v2"}} - } - ee.WriteMapEnd() -} -{{end}}{{end}}{{end}} - -{{range .Values}}{{if not .Primitive}}{{if .MapKey }} -func (e *Encoder) {{ .MethodNamePfx "fastpathEnc" false }}R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(rv2i(rv).(map[{{ .MapKey }}]{{ .Elem }}), e) -} -func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v map[{{ .MapKey }}]{{ .Elem }}, e *Encoder) { - if v == nil { e.e.EncodeNil(); return } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - {{if eq .MapKey "interface{}"}}{{/* out of band - */}}var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l uint - var vp *bytesI {{/* put loop variables outside. seems currently needed for better perf */}} - for k2 := range v { - l = uint(len(mksv)) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - for j := range v2 { - if esep { ee.WriteMapElemKey() } - e.asis(v2[j].v) - if esep { ee.WriteMapElemValue() } - e.encode(v[v2[j].i]) - } {{else}}{{ $x := sorttype .MapKey true}}v2 := make([]{{ $x }}, len(v)) - var i uint - for k := range v { - v2[i] = {{ $x }}(k) - i++ - } - sort.Sort({{ sorttype .MapKey false}}(v2)) - for _, k2 := range v2 { - if esep { ee.WriteMapElemKey() } - {{if eq .MapKey "string"}} if e.h.StringToRaw {ee.EncodeStringBytesRaw(bytesView(k2))} else {ee.EncodeStringEnc(cUTF8, k2)} {{else}}{{ $y := printf "%s(k2)" .MapKey }}{{ encmd .MapKey $y }}{{end}} - if esep { ee.WriteMapElemValue() } - {{ $y := printf "v[%s(k2)]" .MapKey }}{{ encmd .Elem $y }} - } {{end}} - } else { - for k2, v2 := range v { - if esep { ee.WriteMapElemKey() } - {{if eq .MapKey "string"}} if e.h.StringToRaw {ee.EncodeStringBytesRaw(bytesView(k2))} else {ee.EncodeStringEnc(cUTF8, k2)} {{else}}{{ encmd .MapKey "k2"}}{{end}} - if esep { ee.WriteMapElemValue() } - {{ encmd .Elem "v2"}} - } - } - ee.WriteMapEnd() -} -{{end}}{{end}}{{end}} - -// -- decode - -// -- -- fast path type switch -func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { - var changed bool - switch v := iv.(type) { -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }}{{if ne .Elem "uint8"}} - case []{{ .Elem }}: - var v2 []{{ .Elem }} - v2, changed = fastpathTV.{{ .MethodNamePfx "Dec" false }}V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]{{ .Elem }}: - var v2 []{{ .Elem }} - v2, changed = fastpathTV.{{ .MethodNamePfx "Dec" false }}V(*v, true, d) - if changed { - *v = v2 - }{{/* -*/}}{{end}}{{end}}{{end}}{{end}} -{{range .Values}}{{if not .Primitive}}{{if .MapKey }}{{/* -// maps only change if nil, and in that case, there's no point copying -*/}} - case map[{{ .MapKey }}]{{ .Elem }}: - fastpathTV.{{ .MethodNamePfx "Dec" false }}V(v, false, d) - case *map[{{ .MapKey }}]{{ .Elem }}: - var v2 map[{{ .MapKey }}]{{ .Elem }} - v2, changed = fastpathTV.{{ .MethodNamePfx "Dec" false }}V(*v, true, d) - if changed { - *v = v2 - }{{/* -*/}}{{end}}{{end}}{{end}} - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { - switch v := iv.(type) { -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }} - case *[]{{ .Elem }}: - *v = nil {{/* -*/}}{{end}}{{end}}{{end}} -{{range .Values}}{{if not .Primitive}}{{if .MapKey }} - case *map[{{ .MapKey }}]{{ .Elem }}: - *v = nil {{/* -*/}}{{end}}{{end}}{{end}} - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -// -- -- fast path functions -{{range .Values}}{{if not .Primitive}}{{if not .MapKey }} -{{/* -Slices can change if they -- did not come from an array -- are addressable (from a ptr) -- are settable (e.g. contained in an interface{}) -*/}} -func (d *Decoder) {{ .MethodNamePfx "fastpathDec" false }}R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]{{ .Elem }}) - v, changed := fastpathTV.{{ .MethodNamePfx "Dec" false }}V(*vp, !array, d) - if changed { *vp = v } - } else { - v := rv2i(rv).([]{{ .Elem }}) - v2, changed := fastpathTV.{{ .MethodNamePfx "Dec" false }}V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) {{ .MethodNamePfx "Dec" false }}X(vp *[]{{ .Elem }}, d *Decoder) { - v, changed := f.{{ .MethodNamePfx "Dec" false }}V(*vp, true, d) - if changed { *vp = v } -} -func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v []{{ .Elem }}, canChange bool, d *Decoder) (_ []{{ .Elem }}, changed bool) { - dd := d.d{{/* - // if dd.isContainerType(valueTypeNil) { dd.TryDecodeAsNil() - */}} - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { v = []{{ .Elem }}{} } else if len(v) != 0 { v = v[:0] } - changed = true - } - slh.End() - return v, changed - } - d.depthIncr() - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, {{ .Size }}) - if xlen <= cap(v) { - v = v[:uint(xlen)] - } else { - v = make([]{{ .Elem }}, uint(xlen)) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - var j int - for j = 0; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, {{ .Size }}) - } else { - xlen = 8 - } - v = make([]{{ .Elem }}, uint(xlen)) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, {{ zerocmd .Elem }}) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[uint(j)] = {{ zerocmd .Elem }} - } else { - {{ if eq .Elem "interface{}" }}d.decode(&v[uint(j)]){{ else }}v[uint(j)] = {{ decmd .Elem }}{{ end }} - } - } - if canChange { - if j < len(v) { - v = v[:uint(j)] - changed = true - } else if j == 0 && v == nil { - v = make([]{{ .Elem }}, 0) - changed = true - } - } - slh.End() - d.depthDecr() - return v, changed -} -{{end}}{{end}}{{end}} - -{{range .Values}}{{if not .Primitive}}{{if .MapKey }} -{{/* -Maps can change if they are -- addressable (from a ptr) -- settable (e.g. contained in an interface{}) -*/}} -func (d *Decoder) {{ .MethodNamePfx "fastpathDec" false }}R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[{{ .MapKey }}]{{ .Elem }}) - v, changed := fastpathTV.{{ .MethodNamePfx "Dec" false }}V(*vp, true, d); - if changed { *vp = v } - } else { - fastpathTV.{{ .MethodNamePfx "Dec" false }}V(rv2i(rv).(map[{{ .MapKey }}]{{ .Elem }}), false, d) - } -} -func (f fastpathT) {{ .MethodNamePfx "Dec" false }}X(vp *map[{{ .MapKey }}]{{ .Elem }}, d *Decoder) { - v, changed := f.{{ .MethodNamePfx "Dec" false }}V(*vp, true, d) - if changed { *vp = v } -} -func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v map[{{ .MapKey }}]{{ .Elem }}, canChange bool, - d *Decoder) (_ map[{{ .MapKey }}]{{ .Elem }}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators(){{/* - // if dd.isContainerType(valueTypeNil) {dd.TryDecodeAsNil() - */}} - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, {{ .Size }}) - v = make(map[{{ .MapKey }}]{{ .Elem }}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - d.depthIncr() - {{ if eq .Elem "interface{}" }}mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - {{end}}var mk {{ .MapKey }} - var mv {{ .Elem }} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { dd.ReadMapElemKey() } - {{ if eq .MapKey "interface{}" }}mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) {{/* // maps cannot have []byte as key. switch to string. */}} - }{{ else }}mk = {{ decmd .MapKey }}{{ end }} - if esep { dd.ReadMapElemValue() } - if dd.TryDecodeAsNil() { - if v == nil {} else if d.h.DeleteOnNilMapValue { delete(v, mk) } else { v[mk] = {{ zerocmd .Elem }} } - continue - } - {{ if eq .Elem "interface{}" }}if mapGet { mv = v[mk] } else { mv = nil } - d.decode(&mv){{ else }}mv = {{ decmd .Elem }}{{ end }} - if v != nil { v[mk] = mv } - } - dd.ReadMapEnd() - d.depthDecr() - return v, changed -} -{{end}}{{end}}{{end}} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.not.go b/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.not.go deleted file mode 100644 index cf97db0f27c1e..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/fast-path.not.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build notfastpath - -package codec - -import "reflect" - -const fastpathEnabled = false - -// The generated fast-path code is very large, and adds a few seconds to the build time. -// This causes test execution, execution of small tools which use codec, etc -// to take a long time. -// -// To mitigate, we now support the notfastpath tag. -// This tag disables fastpath during build, allowing for faster build, test execution, -// short-program runs, etc. - -func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { return false } -func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { return false } -func fastpathEncodeTypeSwitchSlice(iv interface{}, e *Encoder) bool { return false } -func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { return false } -func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { return false } - -type fastpathT struct{} -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} -type fastpathA [0]fastpathE - -func (x fastpathA) index(rtid uintptr) int { return -1 } - -func (_ fastpathT) DecSliceUint8V(v []uint8, canChange bool, d *Decoder) (_ []uint8, changed bool) { - fn := d.h.fn(uint8SliceTyp, true, true) - d.kSlice(&fn.i, reflect.ValueOf(&v).Elem()) - return v, true -} - -var fastpathAV fastpathA -var fastpathTV fastpathT - -// ---- -type TestMammoth2Wrapper struct{} // to allow testMammoth work in notfastpath mode diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-array.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-array.go.tmpl deleted file mode 100644 index 790e914e13cb3..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-array.go.tmpl +++ /dev/null @@ -1,78 +0,0 @@ -{{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }} -{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}{{if not isArray}} -var {{var "c"}} bool {{/* // changed */}} -_ = {{var "c"}}{{end}} -if {{var "l"}} == 0 { - {{if isSlice }}if {{var "v"}} == nil { - {{var "v"}} = []{{ .Typ }}{} - {{var "c"}} = true - } else if len({{var "v"}}) != 0 { - {{var "v"}} = {{var "v"}}[:0] - {{var "c"}} = true - } {{else if isChan }}if {{var "v"}} == nil { - {{var "v"}} = make({{ .CTyp }}, 0) - {{var "c"}} = true - } {{end}} -} else { - {{var "hl"}} := {{var "l"}} > 0 - var {{var "rl"}} int - _ = {{var "rl"}} - {{if isSlice }} if {{var "hl"}} { - if {{var "l"}} > cap({{var "v"}}) { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - if {{var "rl"}} <= cap({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "rl"}}] - } else { - {{var "v"}} = make([]{{ .Typ }}, {{var "rl"}}) - } - {{var "c"}} = true - } else if {{var "l"}} != len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "l"}}] - {{var "c"}} = true - } - } {{end}} - var {{var "j"}} int - // var {{var "dn"}} bool - for {{var "j"}} = 0; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { // bounds-check-elimination - {{if not isArray}} if {{var "j"}} == 0 && {{var "v"}} == nil { - if {{var "hl"}} { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - } else { - {{var "rl"}} = {{if isSlice}}8{{else if isChan}}64{{end}} - } - {{var "v"}} = make({{if isSlice}}[]{{ .Typ }}{{else if isChan}}{{.CTyp}}{{end}}, {{var "rl"}}) - {{var "c"}} = true - }{{end}} - {{var "h"}}.ElemContainerState({{var "j"}}) - {{/* {{var "dn"}} = r.TryDecodeAsNil() */}}{{/* commented out, as decLineVar handles this already each time */}} - {{if isChan}}{{ $x := printf "%[1]vvcx%[2]v" .TempVar .Rand }}var {{$x}} {{ .Typ }} - {{ decLineVar $x }} - {{var "v"}} <- {{ $x }} - // println(">>>> sending ", {{ $x }}, " into ", {{var "v"}}) // TODO: remove this - {{else}}{{/* // if indefinite, etc, then expand the slice if necessary */}} - var {{var "db"}} bool - if {{var "j"}} >= len({{var "v"}}) { - {{if isSlice }} {{var "v"}} = append({{var "v"}}, {{ zero }}) - {{var "c"}} = true - {{else}} z.DecArrayCannotExpand(len(v), {{var "j"}}+1); {{var "db"}} = true - {{end}} - } - if {{var "db"}} { - z.DecSwallow() - } else { - {{ $x := printf "%[1]vv%[2]v[%[1]vj%[2]v]" .TempVar .Rand }}{{ decLineVar $x }} - } - {{end}} - } - {{if isSlice}} if {{var "j"}} < len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "j"}}] - {{var "c"}} = true - } else if {{var "j"}} == 0 && {{var "v"}} == nil { - {{var "v"}} = make([]{{ .Typ }}, 0) - {{var "c"}} = true - } {{end}} -} -{{var "h"}}.End() -{{if not isArray }}if {{var "c"}} { - *{{ .Varname }} = {{var "v"}} -}{{end}} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-map.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-map.go.tmpl deleted file mode 100644 index 8323b54940d04..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen-dec-map.go.tmpl +++ /dev/null @@ -1,42 +0,0 @@ -{{var "v"}} := *{{ .Varname }} -{{var "l"}} := r.ReadMapStart() -{{var "bh"}} := z.DecBasicHandle() -if {{var "v"}} == nil { - {{var "rl"}} := z.DecInferLen({{var "l"}}, {{var "bh"}}.MaxInitLen, {{ .Size }}) - {{var "v"}} = make(map[{{ .KTyp }}]{{ .Typ }}, {{var "rl"}}) - *{{ .Varname }} = {{var "v"}} -} -var {{var "mk"}} {{ .KTyp }} -var {{var "mv"}} {{ .Typ }} -var {{var "mg"}}, {{var "mdn"}} {{if decElemKindPtr}}, {{var "ms"}}, {{var "mok"}}{{end}} bool -if {{var "bh"}}.MapValueReset { - {{if decElemKindPtr}}{{var "mg"}} = true - {{else if decElemKindIntf}}if !{{var "bh"}}.InterfaceReset { {{var "mg"}} = true } - {{else if not decElemKindImmutable}}{{var "mg"}} = true - {{end}} } -if {{var "l"}} != 0 { -{{var "hl"}} := {{var "l"}} > 0 - for {{var "j"}} := 0; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { - r.ReadMapElemKey() {{/* z.DecSendContainerState(codecSelfer_containerMapKey{{ .Sfx }}) */}} - {{ $x := printf "%vmk%v" .TempVar .Rand }}{{ decLineVarK $x }} -{{ if eq .KTyp "interface{}" }}{{/* // special case if a byte array. */}}if {{var "bv"}}, {{var "bok"}} := {{var "mk"}}.([]byte); {{var "bok"}} { - {{var "mk"}} = string({{var "bv"}}) - }{{ end }}{{if decElemKindPtr}} - {{var "ms"}} = true{{end}} - if {{var "mg"}} { - {{if decElemKindPtr}}{{var "mv"}}, {{var "mok"}} = {{var "v"}}[{{var "mk"}}] - if {{var "mok"}} { - {{var "ms"}} = false - } {{else}}{{var "mv"}} = {{var "v"}}[{{var "mk"}}] {{end}} - } {{if not decElemKindImmutable}}else { {{var "mv"}} = {{decElemZero}} }{{end}} - r.ReadMapElemValue() {{/* z.DecSendContainerState(codecSelfer_containerMapValue{{ .Sfx }}) */}} - {{var "mdn"}} = false - {{ $x := printf "%vmv%v" .TempVar .Rand }}{{ $y := printf "%vmdn%v" .TempVar .Rand }}{{ decLineVar $x $y }} - if {{var "mdn"}} { - if {{ var "bh" }}.DeleteOnNilMapValue { delete({{var "v"}}, {{var "mk"}}) } else { {{var "v"}}[{{var "mk"}}] = {{decElemZero}} } - } else if {{if decElemKindPtr}} {{var "ms"}} && {{end}} {{var "v"}} != nil { - {{var "v"}}[{{var "mk"}}] = {{var "mv"}} - } -} -} // else len==0: TODO: Should we clear map entries? -r.ReadMapEnd() {{/* z.DecSendContainerState(codecSelfer_containerMapEnd{{ .Sfx }}) */}} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen-enc-chan.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/gen-enc-chan.go.tmpl deleted file mode 100644 index 4249588a3cf8d..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen-enc-chan.go.tmpl +++ /dev/null @@ -1,27 +0,0 @@ -{{.Label}}: -switch timeout{{.Sfx}} := z.EncBasicHandle().ChanRecvTimeout; { -case timeout{{.Sfx}} == 0: // only consume available - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{ .Slice }} = append({{.Slice}}, b{{.Sfx}}) - default: - break {{.Label}} - } - } -case timeout{{.Sfx}} > 0: // consume until timeout - tt{{.Sfx}} := time.NewTimer(timeout{{.Sfx}}) - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - case <-tt{{.Sfx}}.C: - // close(tt.C) - break {{.Label}} - } - } -default: // consume until close - for b{{.Sfx}} := range {{.Chan}} { - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - } -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.generated.go b/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.generated.go deleted file mode 100644 index 2a7d1aab70b3a..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.generated.go +++ /dev/null @@ -1,343 +0,0 @@ -// comment this out // + build ignore - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from gen-helper.go.tmpl - DO NOT EDIT. - -package codec - -import ( - "encoding" - "reflect" -) - -// GenVersion is the current version of codecgen. -const GenVersion = 10 - -// This file is used to generate helper code for codecgen. -// The values here i.e. genHelper(En|De)coder are not to be used directly by -// library users. They WILL change continuously and without notice. -// -// To help enforce this, we create an unexported type with exported members. -// The only way to get the type is via the one exported type that we control (somewhat). -// -// When static codecs are created for types, they will use this value -// to perform encoding or decoding of primitives or known slice or map types. - -// GenHelperEncoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperEncoder(e *Encoder) (ge genHelperEncoder, ee genHelperEncDriver) { - ge = genHelperEncoder{e: e} - ee = genHelperEncDriver{encDriver: e.e} - return -} - -// GenHelperDecoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperDecoder(d *Decoder) (gd genHelperDecoder, dd genHelperDecDriver) { - gd = genHelperDecoder{d: d} - dd = genHelperDecDriver{decDriver: d.d} - return -} - -type genHelperEncDriver struct { - encDriver -} - -func (x genHelperEncDriver) EncodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperEncDriver) EncStructFieldKey(keyType valueType, s string) { - encStructFieldKey(s, x.encDriver, nil, keyType, false, false) -} -func (x genHelperEncDriver) EncodeSymbol(s string) { - x.encDriver.EncodeStringEnc(cUTF8, s) -} - -type genHelperDecDriver struct { - decDriver - C checkOverflow -} - -func (x genHelperDecDriver) DecodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperDecDriver) DecStructFieldKey(keyType valueType, buf *[decScratchByteArrayLen]byte) []byte { - return decStructFieldKey(x.decDriver, keyType, buf) -} -func (x genHelperDecDriver) DecodeInt(bitsize uint8) (i int64) { - return x.C.IntV(x.decDriver.DecodeInt64(), bitsize) -} -func (x genHelperDecDriver) DecodeUint(bitsize uint8) (ui uint64) { - return x.C.UintV(x.decDriver.DecodeUint64(), bitsize) -} -func (x genHelperDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { - f = x.DecodeFloat64() - if chkOverflow32 && chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} -func (x genHelperDecDriver) DecodeFloat32As64() (f float64) { - f = x.DecodeFloat64() - if chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperEncoder struct { - M must - e *Encoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperDecoder struct { - C checkOverflow - d *Decoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBasicHandle() *BasicHandle { - return f.e.h -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinary() bool { - return f.e.be // f.e.hh.isBinaryEncoding() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) IsJSONHandle() bool { - return f.e.js -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncFallback(iv interface{}) { - // println(">>>>>>>>> EncFallback") - // f.e.encodeI(iv, false, false) - f.e.encodeValue(reflect.ValueOf(iv), nil, false) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) { - bs, fnerr := iv.MarshalText() - f.e.marshalUtf8(bs, fnerr) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) { - bs, fnerr := iv.MarshalJSON() - f.e.marshalAsis(bs, fnerr) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) { - bs, fnerr := iv.MarshalBinary() - f.e.marshalRaw(bs, fnerr) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncRaw(iv Raw) { f.e.rawBytes(iv) } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) TimeRtidIfBinc() (v uintptr) { return } - -// func (f genHelperEncoder) TimeRtidIfBinc() uintptr { -// if _, ok := f.e.hh.(*BincHandle); ok { -// return timeTypId -// } -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.e.h.getExt(rtid) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncExtension(v interface{}, xfFn *extTypeTagFn) { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) WriteStr(s string) { - f.e.w.writestr(s) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) BytesView(v string) []byte { return bytesView(v) } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) HasExtensions() bool { - return len(f.e.h.extHandle) != 0 -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) EncExt(v interface{}) (r bool) { - if xfFn := f.e.h.getExt(i2rtid(v)); xfFn != nil { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) - return true - } - return false -} - -// ---------------- DECODER FOLLOWS ----------------- - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBasicHandle() *BasicHandle { - return f.d.h -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinary() bool { - return f.d.be // f.d.hh.isBinaryEncoding() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSwallow() { f.d.swallow() } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchBuffer() []byte { - return f.d.b[:] -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchArrayBuffer() *[decScratchByteArrayLen]byte { - return &f.d.b -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) { - // println(">>>>>>>>> DecFallback") - rv := reflect.ValueOf(iv) - if chkPtr { - rv = f.d.ensureDecodeable(rv) - } - f.d.decodeValue(rv, nil, false) - // f.d.decodeValueFallback(rv) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSliceHelperStart() (decSliceHelper, int) { - return f.d.decSliceHelperStart() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) { - f.d.structFieldNotFound(index, name) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) { - f.d.arrayCannotExpand(sliceLen, streamLen) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) { - fnerr := tm.UnmarshalText(f.d.d.DecodeStringAsBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) { - // bs := f.dd.DecodeStringAsBytes() - // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - fnerr := tm.UnmarshalJSON(f.d.nextValueBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) { - fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, true)) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecRaw() []byte { return f.d.rawBytes() } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) TimeRtidIfBinc() (v uintptr) { return } - -// func (f genHelperDecoder) TimeRtidIfBinc() uintptr { -// // Note: builtin is no longer supported - so make this a no-op -// if _, ok := f.d.hh.(*BincHandle); ok { -// return timeTypId -// } -// return 0 -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) IsJSONHandle() bool { - return f.d.js -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.d.h.getExt(rtid) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecExtension(v interface{}, xfFn *extTypeTagFn) { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) HasExtensions() bool { - return len(f.d.h.extHandle) != 0 -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) DecExt(v interface{}) (r bool) { - if xfFn := f.d.h.getExt(i2rtid(v)); xfFn != nil { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) - return true - } - return false -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecInferLen(clen, maxlen, unit int) (rvlen int) { - return decInferLen(clen, maxlen, unit) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: no longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) StringView(v []byte) string { return stringView(v) } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.go.tmpl deleted file mode 100644 index f5d0634e6a1c4..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen-helper.go.tmpl +++ /dev/null @@ -1,308 +0,0 @@ -// comment this out // + build ignore - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from gen-helper.go.tmpl - DO NOT EDIT. - -package codec - -import ( - "encoding" - "reflect" -) - -// GenVersion is the current version of codecgen. -const GenVersion = {{ .Version }} - -// This file is used to generate helper code for codecgen. -// The values here i.e. genHelper(En|De)coder are not to be used directly by -// library users. They WILL change continuously and without notice. -// -// To help enforce this, we create an unexported type with exported members. -// The only way to get the type is via the one exported type that we control (somewhat). -// -// When static codecs are created for types, they will use this value -// to perform encoding or decoding of primitives or known slice or map types. - -// GenHelperEncoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperEncoder(e *Encoder) (ge genHelperEncoder, ee genHelperEncDriver) { - ge = genHelperEncoder{e: e} - ee = genHelperEncDriver{encDriver: e.e} - return -} - -// GenHelperDecoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperDecoder(d *Decoder) (gd genHelperDecoder, dd genHelperDecDriver) { - gd = genHelperDecoder{d: d} - dd = genHelperDecDriver{decDriver: d.d} - return -} - -type genHelperEncDriver struct { - encDriver -} - -func (x genHelperEncDriver) EncodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperEncDriver) EncStructFieldKey(keyType valueType, s string) { - encStructFieldKey(s, x.encDriver, nil, keyType, false, false) -} -func (x genHelperEncDriver) EncodeSymbol(s string) { - x.encDriver.EncodeStringEnc(cUTF8, s) -} - -type genHelperDecDriver struct { - decDriver - C checkOverflow -} - -func (x genHelperDecDriver) DecodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperDecDriver) DecStructFieldKey(keyType valueType, buf *[decScratchByteArrayLen]byte) []byte { - return decStructFieldKey(x.decDriver, keyType, buf) -} -func (x genHelperDecDriver) DecodeInt(bitsize uint8) (i int64) { - return x.C.IntV(x.decDriver.DecodeInt64(), bitsize) -} -func (x genHelperDecDriver) DecodeUint(bitsize uint8) (ui uint64) { - return x.C.UintV(x.decDriver.DecodeUint64(), bitsize) -} -func (x genHelperDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { - f = x.DecodeFloat64() - if chkOverflow32 && chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} -func (x genHelperDecDriver) DecodeFloat32As64() (f float64) { - f = x.DecodeFloat64() - if chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperEncoder struct { - M must - e *Encoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperDecoder struct { - C checkOverflow - d *Decoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBasicHandle() *BasicHandle { - return f.e.h -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinary() bool { - return f.e.be // f.e.hh.isBinaryEncoding() -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) IsJSONHandle() bool { - return f.e.js -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncFallback(iv interface{}) { - // println(">>>>>>>>> EncFallback") - // f.e.encodeI(iv, false, false) - f.e.encodeValue(reflect.ValueOf(iv), nil, false) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) { - bs, fnerr := iv.MarshalText() - f.e.marshalUtf8(bs, fnerr) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) { - bs, fnerr := iv.MarshalJSON() - f.e.marshalAsis(bs, fnerr) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) { - bs, fnerr := iv.MarshalBinary() - f.e.marshalRaw(bs, fnerr) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncRaw(iv Raw) { f.e.rawBytes(iv) } -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) TimeRtidIfBinc() (v uintptr) { return } -// func (f genHelperEncoder) TimeRtidIfBinc() uintptr { -// if _, ok := f.e.hh.(*BincHandle); ok { -// return timeTypId -// } -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.e.h.getExt(rtid) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncExtension(v interface{}, xfFn *extTypeTagFn) { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) WriteStr(s string) { - f.e.w.writestr(s) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) BytesView(v string) []byte { return bytesView(v) } -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) HasExtensions() bool { - return len(f.e.h.extHandle) != 0 -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) EncExt(v interface{}) (r bool) { - if xfFn := f.e.h.getExt(i2rtid(v)); xfFn != nil { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) - return true - } - return false -} - -// ---------------- DECODER FOLLOWS ----------------- - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBasicHandle() *BasicHandle { - return f.d.h -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinary() bool { - return f.d.be // f.d.hh.isBinaryEncoding() -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSwallow() { f.d.swallow() } -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchBuffer() []byte { - return f.d.b[:] -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchArrayBuffer() *[decScratchByteArrayLen]byte { - return &f.d.b -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) { - // println(">>>>>>>>> DecFallback") - rv := reflect.ValueOf(iv) - if chkPtr { - rv = f.d.ensureDecodeable(rv) - } - f.d.decodeValue(rv, nil, false) - // f.d.decodeValueFallback(rv) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSliceHelperStart() (decSliceHelper, int) { - return f.d.decSliceHelperStart() -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) { - f.d.structFieldNotFound(index, name) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) { - f.d.arrayCannotExpand(sliceLen, streamLen) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) { - fnerr := tm.UnmarshalText(f.d.d.DecodeStringAsBytes()) - if fnerr != nil { - panic(fnerr) - } -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) { - // bs := f.dd.DecodeStringAsBytes() - // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - fnerr := tm.UnmarshalJSON(f.d.nextValueBytes()) - if fnerr != nil { - panic(fnerr) - } -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) { - fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, true)) - if fnerr != nil { - panic(fnerr) - } -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecRaw() []byte { return f.d.rawBytes() } -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) TimeRtidIfBinc() (v uintptr) { return } -// func (f genHelperDecoder) TimeRtidIfBinc() uintptr { -// // Note: builtin is no longer supported - so make this a no-op -// if _, ok := f.d.hh.(*BincHandle); ok { -// return timeTypId -// } -// return 0 -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) IsJSONHandle() bool { - return f.d.js -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.d.h.getExt(rtid) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecExtension(v interface{}, xfFn *extTypeTagFn) { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) HasExtensions() bool { - return len(f.d.h.extHandle) != 0 -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) DecExt(v interface{}) (r bool) { - if xfFn := f.d.h.getExt(i2rtid(v)); xfFn != nil { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) - return true - } - return false -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecInferLen(clen, maxlen, unit int) (rvlen int) { - return decInferLen(clen, maxlen, unit) -} -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: no longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) StringView(v []byte) string { return stringView(v) } - diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen.generated.go b/vendor/github.com/hashicorp/go-msgpack/codec/gen.generated.go deleted file mode 100644 index 8b00090a8ff4c..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen.generated.go +++ /dev/null @@ -1,164 +0,0 @@ -// +build codecgen.exec - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// DO NOT EDIT. THIS FILE IS AUTO-GENERATED FROM gen-dec-(map|array).go.tmpl - -const genDecMapTmpl = ` -{{var "v"}} := *{{ .Varname }} -{{var "l"}} := r.ReadMapStart() -{{var "bh"}} := z.DecBasicHandle() -if {{var "v"}} == nil { - {{var "rl"}} := z.DecInferLen({{var "l"}}, {{var "bh"}}.MaxInitLen, {{ .Size }}) - {{var "v"}} = make(map[{{ .KTyp }}]{{ .Typ }}, {{var "rl"}}) - *{{ .Varname }} = {{var "v"}} -} -var {{var "mk"}} {{ .KTyp }} -var {{var "mv"}} {{ .Typ }} -var {{var "mg"}}, {{var "mdn"}} {{if decElemKindPtr}}, {{var "ms"}}, {{var "mok"}}{{end}} bool -if {{var "bh"}}.MapValueReset { - {{if decElemKindPtr}}{{var "mg"}} = true - {{else if decElemKindIntf}}if !{{var "bh"}}.InterfaceReset { {{var "mg"}} = true } - {{else if not decElemKindImmutable}}{{var "mg"}} = true - {{end}} } -if {{var "l"}} != 0 { -{{var "hl"}} := {{var "l"}} > 0 - for {{var "j"}} := 0; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { - r.ReadMapElemKey() {{/* z.DecSendContainerState(codecSelfer_containerMapKey{{ .Sfx }}) */}} - {{ $x := printf "%vmk%v" .TempVar .Rand }}{{ decLineVarK $x }} -{{ if eq .KTyp "interface{}" }}{{/* // special case if a byte array. */}}if {{var "bv"}}, {{var "bok"}} := {{var "mk"}}.([]byte); {{var "bok"}} { - {{var "mk"}} = string({{var "bv"}}) - }{{ end }}{{if decElemKindPtr}} - {{var "ms"}} = true{{end}} - if {{var "mg"}} { - {{if decElemKindPtr}}{{var "mv"}}, {{var "mok"}} = {{var "v"}}[{{var "mk"}}] - if {{var "mok"}} { - {{var "ms"}} = false - } {{else}}{{var "mv"}} = {{var "v"}}[{{var "mk"}}] {{end}} - } {{if not decElemKindImmutable}}else { {{var "mv"}} = {{decElemZero}} }{{end}} - r.ReadMapElemValue() {{/* z.DecSendContainerState(codecSelfer_containerMapValue{{ .Sfx }}) */}} - {{var "mdn"}} = false - {{ $x := printf "%vmv%v" .TempVar .Rand }}{{ $y := printf "%vmdn%v" .TempVar .Rand }}{{ decLineVar $x $y }} - if {{var "mdn"}} { - if {{ var "bh" }}.DeleteOnNilMapValue { delete({{var "v"}}, {{var "mk"}}) } else { {{var "v"}}[{{var "mk"}}] = {{decElemZero}} } - } else if {{if decElemKindPtr}} {{var "ms"}} && {{end}} {{var "v"}} != nil { - {{var "v"}}[{{var "mk"}}] = {{var "mv"}} - } -} -} // else len==0: TODO: Should we clear map entries? -r.ReadMapEnd() {{/* z.DecSendContainerState(codecSelfer_containerMapEnd{{ .Sfx }}) */}} -` - -const genDecListTmpl = ` -{{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }} -{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}{{if not isArray}} -var {{var "c"}} bool {{/* // changed */}} -_ = {{var "c"}}{{end}} -if {{var "l"}} == 0 { - {{if isSlice }}if {{var "v"}} == nil { - {{var "v"}} = []{{ .Typ }}{} - {{var "c"}} = true - } else if len({{var "v"}}) != 0 { - {{var "v"}} = {{var "v"}}[:0] - {{var "c"}} = true - } {{else if isChan }}if {{var "v"}} == nil { - {{var "v"}} = make({{ .CTyp }}, 0) - {{var "c"}} = true - } {{end}} -} else { - {{var "hl"}} := {{var "l"}} > 0 - var {{var "rl"}} int - _ = {{var "rl"}} - {{if isSlice }} if {{var "hl"}} { - if {{var "l"}} > cap({{var "v"}}) { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - if {{var "rl"}} <= cap({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "rl"}}] - } else { - {{var "v"}} = make([]{{ .Typ }}, {{var "rl"}}) - } - {{var "c"}} = true - } else if {{var "l"}} != len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "l"}}] - {{var "c"}} = true - } - } {{end}} - var {{var "j"}} int - // var {{var "dn"}} bool - for {{var "j"}} = 0; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { // bounds-check-elimination - {{if not isArray}} if {{var "j"}} == 0 && {{var "v"}} == nil { - if {{var "hl"}} { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - } else { - {{var "rl"}} = {{if isSlice}}8{{else if isChan}}64{{end}} - } - {{var "v"}} = make({{if isSlice}}[]{{ .Typ }}{{else if isChan}}{{.CTyp}}{{end}}, {{var "rl"}}) - {{var "c"}} = true - }{{end}} - {{var "h"}}.ElemContainerState({{var "j"}}) - {{/* {{var "dn"}} = r.TryDecodeAsNil() */}}{{/* commented out, as decLineVar handles this already each time */}} - {{if isChan}}{{ $x := printf "%[1]vvcx%[2]v" .TempVar .Rand }}var {{$x}} {{ .Typ }} - {{ decLineVar $x }} - {{var "v"}} <- {{ $x }} - // println(">>>> sending ", {{ $x }}, " into ", {{var "v"}}) // TODO: remove this - {{else}}{{/* // if indefinite, etc, then expand the slice if necessary */}} - var {{var "db"}} bool - if {{var "j"}} >= len({{var "v"}}) { - {{if isSlice }} {{var "v"}} = append({{var "v"}}, {{ zero }}) - {{var "c"}} = true - {{else}} z.DecArrayCannotExpand(len(v), {{var "j"}}+1); {{var "db"}} = true - {{end}} - } - if {{var "db"}} { - z.DecSwallow() - } else { - {{ $x := printf "%[1]vv%[2]v[%[1]vj%[2]v]" .TempVar .Rand }}{{ decLineVar $x }} - } - {{end}} - } - {{if isSlice}} if {{var "j"}} < len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "j"}}] - {{var "c"}} = true - } else if {{var "j"}} == 0 && {{var "v"}} == nil { - {{var "v"}} = make([]{{ .Typ }}, 0) - {{var "c"}} = true - } {{end}} -} -{{var "h"}}.End() -{{if not isArray }}if {{var "c"}} { - *{{ .Varname }} = {{var "v"}} -}{{end}} -` - -const genEncChanTmpl = ` -{{.Label}}: -switch timeout{{.Sfx}} := z.EncBasicHandle().ChanRecvTimeout; { -case timeout{{.Sfx}} == 0: // only consume available - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{ .Slice }} = append({{.Slice}}, b{{.Sfx}}) - default: - break {{.Label}} - } - } -case timeout{{.Sfx}} > 0: // consume until timeout - tt{{.Sfx}} := time.NewTimer(timeout{{.Sfx}}) - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - case <-tt{{.Sfx}}.C: - // close(tt.C) - break {{.Label}} - } - } -default: // consume until close - for b{{.Sfx}} := range {{.Chan}} { - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - } -} -` diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/gen.go b/vendor/github.com/hashicorp/go-msgpack/codec/gen.go deleted file mode 100644 index 74c4aa86af73a..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/gen.go +++ /dev/null @@ -1,2149 +0,0 @@ -// +build codecgen.exec - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "go/format" - "io" - "io/ioutil" - "math/rand" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "text/template" - "time" - "unicode" - "unicode/utf8" -) - -// --------------------------------------------------- -// codecgen supports the full cycle of reflection-based codec: -// - RawExt -// - Raw -// - Extensions -// - (Binary|Text|JSON)(Unm|M)arshal -// - generic by-kind -// -// This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type. -// In those areas, we try to only do reflection or interface-conversion when NECESSARY: -// - Extensions, only if Extensions are configured. -// -// However, codecgen doesn't support the following: -// - Canonical option. (codecgen IGNORES it currently) -// This is just because it has not been implemented. -// - MissingFielder implementation. -// If a type implements MissingFielder, it is completely ignored by codecgen. -// -// During encode/decode, Selfer takes precedence. -// A type implementing Selfer will know how to encode/decode itself statically. -// -// The following field types are supported: -// array: [n]T -// slice: []T -// map: map[K]V -// primitive: [u]int[n], float(32|64), bool, string -// struct -// -// --------------------------------------------------- -// Note that a Selfer cannot call (e|d).(En|De)code on itself, -// as this will cause a circular reference, as (En|De)code will call Selfer methods. -// Any type that implements Selfer must implement completely and not fallback to (En|De)code. -// -// In addition, code in this file manages the generation of fast-path implementations of -// encode/decode of slices/maps of primitive keys/values. -// -// Users MUST re-generate their implementations whenever the code shape changes. -// The generated code will panic if it was generated with a version older than the supporting library. -// --------------------------------------------------- -// -// codec framework is very feature rich. -// When encoding or decoding into an interface, it depends on the runtime type of the interface. -// The type of the interface may be a named type, an extension, etc. -// Consequently, we fallback to runtime codec for encoding/decoding interfaces. -// In addition, we fallback for any value which cannot be guaranteed at runtime. -// This allows us support ANY value, including any named types, specifically those which -// do not implement our interfaces (e.g. Selfer). -// -// This explains some slowness compared to other code generation codecs (e.g. msgp). -// This reduction in speed is only seen when your refers to interfaces, -// e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} } -// -// codecgen will panic if the file was generated with an old version of the library in use. -// -// Note: -// It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil. -// This way, there isn't a function call overhead just to see that we should not enter a block of code. -// -// Note: -// codecgen-generated code depends on the variables defined by fast-path.generated.go. -// consequently, you cannot run with tags "codecgen notfastpath". - -// GenVersion is the current version of codecgen. -// -// NOTE: Increment this value each time codecgen changes fundamentally. -// Fundamental changes are: -// - helper methods change (signature change, new ones added, some removed, etc) -// - codecgen command line changes -// -// v1: Initial Version -// v2: -// v3: Changes for Kubernetes: -// changes in signature of some unpublished helper methods and codecgen cmdline arguments. -// v4: Removed separator support from (en|de)cDriver, and refactored codec(gen) -// v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections. -// v6: removed unsafe from gen, and now uses codecgen.exec tag -// v7: -// v8: current - we now maintain compatibility with old generated code. -// v9: skipped -// v10: modified encDriver and decDriver interfaces. Remove deprecated methods after Jan 1, 2019 -const genVersion = 10 - -const ( - genCodecPkg = "codec1978" - genTempVarPfx = "yy" - genTopLevelVarName = "x" - - // ignore canBeNil parameter, and always set to true. - // This is because nil can appear anywhere, so we should always check. - genAnythingCanBeNil = true - - // if genUseOneFunctionForDecStructMap, make a single codecDecodeSelferFromMap function; - // else make codecDecodeSelferFromMap{LenPrefix,CheckBreak} so that conditionals - // are not executed a lot. - // - // From testing, it didn't make much difference in runtime, so keep as true (one function only) - genUseOneFunctionForDecStructMap = true -) - -type genStructMapStyle uint8 - -const ( - genStructMapStyleConsolidated genStructMapStyle = iota - genStructMapStyleLenPrefix - genStructMapStyleCheckBreak -) - -var ( - errGenAllTypesSamePkg = errors.New("All types must be in the same package") - errGenExpectArrayOrMap = errors.New("unexpected type. Expecting array/map/slice") - - genBase64enc = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789__") - genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`) -) - -type genBuf struct { - buf []byte -} - -func (x *genBuf) s(s string) *genBuf { x.buf = append(x.buf, s...); return x } -func (x *genBuf) b(s []byte) *genBuf { x.buf = append(x.buf, s...); return x } -func (x *genBuf) v() string { return string(x.buf) } -func (x *genBuf) f(s string, args ...interface{}) { x.s(fmt.Sprintf(s, args...)) } -func (x *genBuf) reset() { - if x.buf != nil { - x.buf = x.buf[:0] - } -} - -// genRunner holds some state used during a Gen run. -type genRunner struct { - w io.Writer // output - c uint64 // counter used for generating varsfx - t []reflect.Type // list of types to run selfer on - - tc reflect.Type // currently running selfer on this type - te map[uintptr]bool // types for which the encoder has been created - td map[uintptr]bool // types for which the decoder has been created - cp string // codec import path - - im map[string]reflect.Type // imports to add - imn map[string]string // package names of imports to add - imc uint64 // counter for import numbers - - is map[reflect.Type]struct{} // types seen during import search - bp string // base PkgPath, for which we are generating for - - cpfx string // codec package prefix - - tm map[reflect.Type]struct{} // types for which enc/dec must be generated - ts []reflect.Type // types for which enc/dec must be generated - - xs string // top level variable/constant suffix - hn string // fn helper type name - - ti *TypeInfos - // rr *rand.Rand // random generator for file-specific types - - nx bool // no extensions -} - -// Gen will write a complete go file containing Selfer implementations for each -// type passed. All the types must be in the same package. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINUOUSLY WITHOUT NOTICE. -func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool, - ti *TypeInfos, typ ...reflect.Type) { - // All types passed to this method do not have a codec.Selfer method implemented directly. - // codecgen already checks the AST and skips any types that define the codec.Selfer methods. - // Consequently, there's no need to check and trim them if they implement codec.Selfer - - if len(typ) == 0 { - return - } - x := genRunner{ - w: w, - t: typ, - te: make(map[uintptr]bool), - td: make(map[uintptr]bool), - im: make(map[string]reflect.Type), - imn: make(map[string]string), - is: make(map[reflect.Type]struct{}), - tm: make(map[reflect.Type]struct{}), - ts: []reflect.Type{}, - bp: genImportPath(typ[0]), - xs: uid, - ti: ti, - nx: noExtensions, - } - if x.ti == nil { - x.ti = defTypeInfos - } - if x.xs == "" { - rr := rand.New(rand.NewSource(time.Now().UnixNano())) - x.xs = strconv.FormatInt(rr.Int63n(9999), 10) - } - - // gather imports first: - x.cp = genImportPath(reflect.TypeOf(x)) - x.imn[x.cp] = genCodecPkg - for _, t := range typ { - // fmt.Printf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name()) - if genImportPath(t) != x.bp { - panic(errGenAllTypesSamePkg) - } - x.genRefPkgs(t) - } - if buildTags != "" { - x.line("// +build " + buildTags) - x.line("") - } - x.line(` - -// Code generated by codecgen - DO NOT EDIT. - -`) - x.line("package " + pkgName) - x.line("") - x.line("import (") - if x.cp != x.bp { - x.cpfx = genCodecPkg + "." - x.linef("%s \"%s\"", genCodecPkg, x.cp) - } - // use a sorted set of im keys, so that we can get consistent output - imKeys := make([]string, 0, len(x.im)) - for k := range x.im { - imKeys = append(imKeys, k) - } - sort.Strings(imKeys) - for _, k := range imKeys { // for k, _ := range x.im { - if k == x.imn[k] { - x.linef("\"%s\"", k) - } else { - x.linef("%s \"%s\"", x.imn[k], k) - } - } - // add required packages - for _, k := range [...]string{"runtime", "errors", "strconv"} { // "reflect", "fmt" - if _, ok := x.im[k]; !ok { - x.line("\"" + k + "\"") - } - } - x.line(")") - x.line("") - - x.line("const (") - x.linef("// ----- content types ----") - x.linef("codecSelferCcUTF8%s = %v", x.xs, int64(cUTF8)) - x.linef("codecSelferCcRAW%s = %v", x.xs, int64(cRAW)) - x.linef("// ----- value types used ----") - for _, vt := range [...]valueType{ - valueTypeArray, valueTypeMap, valueTypeString, - valueTypeInt, valueTypeUint, valueTypeFloat} { - x.linef("codecSelferValueType%s%s = %v", vt.String(), x.xs, int64(vt)) - } - - x.linef("codecSelferBitsize%s = uint8(32 << (^uint(0) >> 63))", x.xs) - x.line(")") - x.line("var (") - x.line("errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + " = errors.New(`only encoded map or array can be decoded into a struct`)") - x.line(")") - x.line("") - - x.hn = "codecSelfer" + x.xs - x.line("type " + x.hn + " struct{}") - x.line("") - - x.varsfxreset() - x.line("func init() {") - x.linef("if %sGenVersion != %v {", x.cpfx, genVersion) - x.line("_, file, _, _ := runtime.Caller(0)") - x.outf(`panic("codecgen version mismatch: current: %v, need " + strconv.FormatInt(int64(%sGenVersion), 10) + ". Re-generate file: " + file)`, genVersion, x.cpfx) - // x.out(`panic(fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", `) - // x.linef(`%v, %sGenVersion, file))`, genVersion, x.cpfx) - x.linef("}") - x.line("if false { var _ byte = 0; // reference the types, but skip this branch at build/run time") - // x.line("_ = strconv.ParseInt") - var n int - // for k, t := range x.im { - for _, k := range imKeys { - t := x.im[k] - x.linef("var v%v %s.%s", n, x.imn[k], t.Name()) - n++ - } - if n > 0 { - x.out("_") - for i := 1; i < n; i++ { - x.out(", _") - } - x.out(" = v0") - for i := 1; i < n; i++ { - x.outf(", v%v", i) - } - } - x.line("} ") // close if false - x.line("}") // close init - x.line("") - - // generate rest of type info - for _, t := range typ { - x.tc = t - x.selfer(true) - x.selfer(false) - } - - for _, t := range x.ts { - rtid := rt2id(t) - // generate enc functions for all these slice/map types. - x.varsfxreset() - x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx) - x.genRequiredMethodVars(true) - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - x.encListFallback("v", t) - case reflect.Map: - x.encMapFallback("v", t) - default: - panic(errGenExpectArrayOrMap) - } - x.line("}") - x.line("") - - // generate dec functions for all these slice/map types. - x.varsfxreset() - x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx) - x.genRequiredMethodVars(false) - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - x.decListFallback("v", rtid, t) - case reflect.Map: - x.decMapFallback("v", rtid, t) - default: - panic(errGenExpectArrayOrMap) - } - x.line("}") - x.line("") - } - - x.line("") -} - -func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool { - // return varname != genTopLevelVarName && t != x.tc - // the only time we checkForSelfer is if we are not at the TOP of the generated code. - return varname != genTopLevelVarName -} - -func (x *genRunner) arr2str(t reflect.Type, s string) string { - if t.Kind() == reflect.Array { - return s - } - return "" -} - -func (x *genRunner) genRequiredMethodVars(encode bool) { - x.line("var h " + x.hn) - if encode { - x.line("z, r := " + x.cpfx + "GenHelperEncoder(e)") - } else { - x.line("z, r := " + x.cpfx + "GenHelperDecoder(d)") - } - x.line("_, _, _ = h, z, r") -} - -func (x *genRunner) genRefPkgs(t reflect.Type) { - if _, ok := x.is[t]; ok { - return - } - x.is[t] = struct{}{} - tpkg, tname := genImportPath(t), t.Name() - if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' { - if _, ok := x.im[tpkg]; !ok { - x.im[tpkg] = t - if idx := strings.LastIndex(tpkg, "/"); idx < 0 { - x.imn[tpkg] = tpkg - } else { - x.imc++ - x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false) - } - } - } - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan: - x.genRefPkgs(t.Elem()) - case reflect.Map: - x.genRefPkgs(t.Elem()) - x.genRefPkgs(t.Key()) - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' { - x.genRefPkgs(t.Field(i).Type) - } - } - } -} - -func (x *genRunner) varsfx() string { - x.c++ - return strconv.FormatUint(x.c, 10) -} - -func (x *genRunner) varsfxreset() { - x.c = 0 -} - -func (x *genRunner) out(s string) { - _, err := io.WriteString(x.w, s) - if err != nil { - panic(err) - } -} - -func (x *genRunner) outf(s string, params ...interface{}) { - _, err := fmt.Fprintf(x.w, s, params...) - if err != nil { - panic(err) - } -} - -func (x *genRunner) line(s string) { - x.out(s) - if len(s) == 0 || s[len(s)-1] != '\n' { - x.out("\n") - } -} - -func (x *genRunner) linef(s string, params ...interface{}) { - x.outf(s, params...) - if len(s) == 0 || s[len(s)-1] != '\n' { - x.out("\n") - } -} - -func (x *genRunner) genTypeName(t reflect.Type) (n string) { - // defer func() { fmt.Printf(">>>> ####: genTypeName: t: %v, name: '%s'\n", t, n) }() - - // if the type has a PkgPath, which doesn't match the current package, - // then include it. - // We cannot depend on t.String() because it includes current package, - // or t.PkgPath because it includes full import path, - // - var ptrPfx string - for t.Kind() == reflect.Ptr { - ptrPfx += "*" - t = t.Elem() - } - if tn := t.Name(); tn != "" { - return ptrPfx + x.genTypeNamePrim(t) - } - switch t.Kind() { - case reflect.Map: - return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem()) - case reflect.Slice: - return ptrPfx + "[]" + x.genTypeName(t.Elem()) - case reflect.Array: - return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem()) - case reflect.Chan: - return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem()) - default: - if t == intfTyp { - return ptrPfx + "interface{}" - } else { - return ptrPfx + x.genTypeNamePrim(t) - } - } -} - -func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) { - if t.Name() == "" { - return t.String() - } else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) { - return t.Name() - } else { - return x.imn[genImportPath(t)] + "." + t.Name() - // return t.String() // best way to get the package name inclusive - } -} - -func (x *genRunner) genZeroValueR(t reflect.Type) string { - // if t is a named type, w - switch t.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func, - reflect.Slice, reflect.Map, reflect.Invalid: - return "nil" - case reflect.Bool: - return "false" - case reflect.String: - return `""` - case reflect.Struct, reflect.Array: - return x.genTypeName(t) + "{}" - default: // all numbers - return "0" - } -} - -func (x *genRunner) genMethodNameT(t reflect.Type) (s string) { - return genMethodNameT(t, x.tc) -} - -func (x *genRunner) selfer(encode bool) { - t := x.tc - t0 := t - // always make decode use a pointer receiver, - // and structs/arrays always use a ptr receiver (encode|decode) - isptr := !encode || t.Kind() == reflect.Array || (t.Kind() == reflect.Struct && t != timeTyp) - x.varsfxreset() - - fnSigPfx := "func (" + genTopLevelVarName + " " - if isptr { - fnSigPfx += "*" - } - fnSigPfx += x.genTypeName(t) - x.out(fnSigPfx) - - if isptr { - t = reflect.PtrTo(t) - } - if encode { - x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {") - x.genRequiredMethodVars(true) - x.encVar(genTopLevelVarName, t) - } else { - x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - // do not use decVar, as there is no need to check TryDecodeAsNil - // or way to elegantly handle that, and also setting it to a - // non-nil value doesn't affect the pointer passed. - // x.decVar(genTopLevelVarName, t, false) - x.dec(genTopLevelVarName, t0, true) - } - x.line("}") - x.line("") - - if encode || t0.Kind() != reflect.Struct { - return - } - - // write is containerMap - if genUseOneFunctionForDecStructMap { - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleConsolidated) - x.line("}") - x.line("") - } else { - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMapLenPrefix(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleLenPrefix) - x.line("}") - x.line("") - - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMapCheckBreak(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleCheckBreak) - x.line("}") - x.line("") - } - - // write containerArray - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0) - x.line("}") - x.line("") - -} - -// used for chan, array, slice, map -func (x *genRunner) xtraSM(varname string, t reflect.Type, encode, isptr bool) { - var ptrPfx, addrPfx string - if isptr { - ptrPfx = "*" - } else { - addrPfx = "&" - } - if encode { - x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname) - } else { - x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname) - } - x.registerXtraT(t) -} - -func (x *genRunner) registerXtraT(t reflect.Type) { - // recursively register the types - if _, ok := x.tm[t]; ok { - return - } - var tkey reflect.Type - switch t.Kind() { - case reflect.Chan, reflect.Slice, reflect.Array: - case reflect.Map: - tkey = t.Key() - default: - return - } - x.tm[t] = struct{}{} - x.ts = append(x.ts, t) - // check if this refers to any xtra types eg. a slice of array: add the array - x.registerXtraT(t.Elem()) - if tkey != nil { - x.registerXtraT(tkey) - } -} - -// encVar will encode a variable. -// The parameter, t, is the reflect.Type of the variable itself -func (x *genRunner) encVar(varname string, t reflect.Type) { - // fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t) - var checkNil bool - switch t.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan: - checkNil = true - } - if checkNil { - x.linef("if %s == nil { r.EncodeNil() } else { ", varname) - } - - switch t.Kind() { - case reflect.Ptr: - telem := t.Elem() - tek := telem.Kind() - if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) { - x.enc(varname, genNonPtr(t)) - break - } - i := x.varsfx() - x.line(genTempVarPfx + i + " := *" + varname) - x.enc(genTempVarPfx+i, genNonPtr(t)) - case reflect.Struct, reflect.Array: - if t == timeTyp { - x.enc(varname, t) - break - } - i := x.varsfx() - x.line(genTempVarPfx + i + " := &" + varname) - x.enc(genTempVarPfx+i, t) - default: - x.enc(varname, t) - } - - if checkNil { - x.line("}") - } - -} - -// enc will encode a variable (varname) of type t, where t represents T. -// if t is !time.Time and t is of kind reflect.Struct or reflect.Array, varname is of type *T -// (to prevent copying), -// else t is of type T -func (x *genRunner) enc(varname string, t reflect.Type) { - rtid := rt2id(t) - ti2 := x.ti.get(rtid, t) - // We call CodecEncodeSelf if one of the following are honored: - // - the type already implements Selfer, call that - // - the type has a Selfer implementation just created, use that - // - the type is in the list of the ones we will generate for, but it is not currently being generated - - mi := x.varsfx() - // tptr := reflect.PtrTo(t) - tk := t.Kind() - if x.checkForSelfer(t, varname) { - if tk == reflect.Array || (tk == reflect.Struct && rtid != timeTypId) { // varname is of type *T - // if tptr.Implements(selferTyp) || t.Implements(selferTyp) { - if ti2.isFlag(typeInfoFlagIsZeroerPtr) || ti2.isFlag(typeInfoFlagIsZeroer) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - } else { // varname is of type T - if ti2.cs { // t.Implements(selferTyp) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } else if ti2.csp { // tptr.Implements(selferTyp) { - x.linef("%ssf%s := &%s", genTempVarPfx, mi, varname) - x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi) - return - } - } - - if _, ok := x.te[rtid]; ok { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - } - - inlist := false - for _, t0 := range x.t { - if t == t0 { - inlist = true - if x.checkForSelfer(t, varname) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - break - } - } - - var rtidAdded bool - if t == x.tc { - x.te[rtid] = true - rtidAdded = true - } - - // check if - // - type is time.Time, RawExt, Raw - // - the type implements (Text|JSON|Binary)(Unm|M)arshal - - x.line("if false {") //start if block - defer func() { x.line("}") }() //end if block - - if t == timeTyp { - x.linef("} else if !z.EncBasicHandle().TimeNotBuiltin { r.EncodeTime(%s)", varname) - // return - } - if t == rawTyp { - x.linef("} else { z.EncRaw(%s)", varname) - return - } - if t == rawExtTyp { - x.linef("} else { r.EncodeRawExt(%s, e)", varname) - return - } - // only check for extensions if the type is named, and has a packagePath. - var arrayOrStruct = tk == reflect.Array || tk == reflect.Struct // meaning varname if of type *T - if !x.nx && genImportPath(t) != "" && t.Name() != "" { - yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi) - x.linef("} else if %s := z.Extension(z.I2Rtid(%s)); %s != nil { z.EncExtension(%s, %s) ", yy, varname, yy, varname, yy) - } - if arrayOrStruct { // varname is of type *T - if ti2.bm || ti2.bmp { // t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(%v) ", varname) - } - if ti2.jm || ti2.jmp { // t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", varname) - } else if ti2.tm || ti2.tmp { // t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(%v) ", varname) - } - } else { // varname is of type T - if ti2.bm { // t.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(%v) ", varname) - } else if ti2.bmp { // tptr.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(&%v) ", varname) - } - if ti2.jm { // t.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", varname) - } else if ti2.jmp { // tptr.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(&%v) ", varname) - } else if ti2.tm { // t.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(%v) ", varname) - } else if ti2.tmp { // tptr.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(&%v) ", varname) - } - } - x.line("} else {") - - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x.line("r.EncodeInt(int64(" + varname + "))") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - x.line("r.EncodeUint(uint64(" + varname + "))") - case reflect.Float32: - x.line("r.EncodeFloat32(float32(" + varname + "))") - case reflect.Float64: - x.line("r.EncodeFloat64(float64(" + varname + "))") - case reflect.Bool: - x.line("r.EncodeBool(bool(" + varname + "))") - case reflect.String: - x.linef("if z.EncBasicHandle().StringToRaw { r.EncodeStringBytesRaw(z.BytesView(string(%s))) } else { r.EncodeStringEnc(codecSelferCcUTF8%s, string(%s)) }", varname, x.xs, varname) - case reflect.Chan: - x.xtraSM(varname, t, true, false) - // x.encListFallback(varname, rtid, t) - case reflect.Array: - x.xtraSM(varname, t, true, true) - case reflect.Slice: - // if nil, call dedicated function - // if a []uint8, call dedicated function - // if a known fastpath slice, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if rtid == uint8SliceTypId { - x.line("r.EncodeStringBytesRaw([]byte(" + varname + "))") - } else if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)") - } else { - x.xtraSM(varname, t, true, false) - // x.encListFallback(varname, rtid, t) - } - case reflect.Map: - // if nil, call dedicated function - // if a known fastpath map, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - // x.line("if " + varname + " == nil { \nr.EncodeNil()\n } else { ") - if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)") - } else { - x.xtraSM(varname, t, true, false) - // x.encMapFallback(varname, rtid, t) - } - case reflect.Struct: - if !inlist { - delete(x.te, rtid) - x.line("z.EncFallback(" + varname + ")") - break - } - x.encStruct(varname, rtid, t) - default: - if rtidAdded { - delete(x.te, rtid) - } - x.line("z.EncFallback(" + varname + ")") - } -} - -func (x *genRunner) encZero(t reflect.Type) { - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x.line("r.EncodeInt(0)") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - x.line("r.EncodeUint(0)") - case reflect.Float32: - x.line("r.EncodeFloat32(0)") - case reflect.Float64: - x.line("r.EncodeFloat64(0)") - case reflect.Bool: - x.line("r.EncodeBool(false)") - case reflect.String: - x.linef(`if z.EncBasicHandle().StringToRaw { r.EncodeStringBytesRaw([]byte{}) } else { r.EncodeStringEnc(codecSelferCcUTF8%s, "") }`, x.xs) - default: - x.line("r.EncodeNil()") - } -} - -func (x *genRunner) encOmitEmptyLine(t2 reflect.StructField, varname string, buf *genBuf) { - // smartly check omitEmpty on a struct type, as it may contain uncomparable map/slice/etc. - // also, for maps/slices/arrays, check if len ! 0 (not if == zero value) - varname2 := varname + "." + t2.Name - switch t2.Type.Kind() { - case reflect.Struct: - rtid2 := rt2id(t2.Type) - ti2 := x.ti.get(rtid2, t2.Type) - // fmt.Printf(">>>> structfield: omitempty: type: %s, field: %s\n", t2.Type.Name(), t2.Name) - if ti2.rtid == timeTypId { - buf.s("!(").s(varname2).s(".IsZero())") - break - } - if ti2.isFlag(typeInfoFlagIsZeroerPtr) || ti2.isFlag(typeInfoFlagIsZeroer) { - buf.s("!(").s(varname2).s(".IsZero())") - break - } - if ti2.isFlag(typeInfoFlagComparable) { - buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type)) - break - } - // buf.s("(") - buf.s("false") - for i, n := 0, t2.Type.NumField(); i < n; i++ { - f := t2.Type.Field(i) - if f.PkgPath != "" { // unexported - continue - } - buf.s(" || ") - x.encOmitEmptyLine(f, varname2, buf) - } - //buf.s(")") - case reflect.Bool: - buf.s(varname2) - case reflect.Map, reflect.Slice, reflect.Array, reflect.Chan: - buf.s("len(").s(varname2).s(") != 0") - default: - buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type)) - } -} - -func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { - // Use knowledge from structfieldinfo (mbs, encodable fields. Ignore omitempty. ) - // replicate code in kStruct i.e. for each field, deref type to non-pointer, and call x.enc on it - - // if t === type currently running selfer on, do for all - ti := x.ti.get(rtid, t) - i := x.varsfx() - sepVarname := genTempVarPfx + "sep" + i - numfieldsvar := genTempVarPfx + "q" + i - ti2arrayvar := genTempVarPfx + "r" + i - struct2arrvar := genTempVarPfx + "2arr" + i - - x.line(sepVarname + " := !z.EncBinary()") - x.linef("%s := z.EncBasicHandle().StructToArray", struct2arrvar) - x.linef("_, _ = %s, %s", sepVarname, struct2arrvar) - x.linef("const %s bool = %v // struct tag has 'toArray'", ti2arrayvar, ti.toArray) - - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - - // var nn int - // due to omitEmpty, we need to calculate the - // number of non-empty things we write out first. - // This is required as we need to pre-determine the size of the container, - // to support length-prefixing. - if ti.anyOmitEmpty { - x.linef("var %s = [%v]bool{ // should field at this index be written?", numfieldsvar, len(tisfi)) - - for j, si := range tisfi { - _ = j - if !si.omitEmpty() { - // x.linef("%s[%v] = true // %s", numfieldsvar, j, si.fieldName) - x.linef("true, // %s", si.fieldName) - // nn++ - continue - } - var t2 reflect.StructField - var omitline genBuf - { - t2typ := t - varname3 := varname - // go through the loop, record the t2 field explicitly, - // and gather the omit line if embedded in pointers. - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - // do not include actual field in the omit line. - // that is done subsequently (right after - below). - if uint8(ij+1) < si.nis && t2typ.Kind() == reflect.Ptr { - omitline.s(varname3).s(" != nil && ") - } - } - } - x.encOmitEmptyLine(t2, varname, &omitline) - x.linef("%s, // %s", omitline.v(), si.fieldName) - } - x.line("}") - x.linef("_ = %s", numfieldsvar) - } - // x.linef("var %snn%s int", genTempVarPfx, i) - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray { - x.linef("r.WriteArrayStart(%d)", len(tisfi)) - x.linef("} else {") // if not ti.toArray - if ti.anyOmitEmpty { - // nn = 0 - // x.linef("var %snn%s = %v", genTempVarPfx, i, nn) - x.linef("var %snn%s int", genTempVarPfx, i) - x.linef("for _, b := range %s { if b { %snn%s++ } }", numfieldsvar, genTempVarPfx, i) - x.linef("r.WriteMapStart(%snn%s)", genTempVarPfx, i) - x.linef("%snn%s = %v", genTempVarPfx, i, 0) - } else { - x.linef("r.WriteMapStart(%d)", len(tisfi)) - } - x.line("}") // close if not StructToArray - - for j, si := range tisfi { - i := x.varsfx() - isNilVarName := genTempVarPfx + "n" + i - var labelUsed bool - var t2 reflect.StructField - { - t2typ := t - varname3 := varname - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - if t2typ.Kind() == reflect.Ptr { - if !labelUsed { - x.line("var " + isNilVarName + " bool") - } - x.line("if " + varname3 + " == nil { " + isNilVarName + " = true ") - x.line("goto LABEL" + i) - x.line("}") - labelUsed = true - // "varname3 = new(" + x.genTypeName(t3.Elem()) + ") }") - } - } - // t2 = t.FieldByIndex(si.is) - } - if labelUsed { - x.line("LABEL" + i + ":") - } - // if the type of the field is a Selfer, or one of the ones - - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray - if labelUsed { - x.linef("if %s { r.WriteArrayElem(); r.EncodeNil() } else { ", isNilVarName) - } - x.line("r.WriteArrayElem()") - if si.omitEmpty() { - x.linef("if %s[%v] {", numfieldsvar, j) - } - x.encVar(varname+"."+t2.Name, t2.Type) - if si.omitEmpty() { - x.linef("} else {") - x.encZero(t2.Type) - x.linef("}") - } - if labelUsed { - x.line("}") - } - - x.linef("} else {") // if not ti.toArray - - if si.omitEmpty() { - x.linef("if %s[%v] {", numfieldsvar, j) - } - x.line("r.WriteMapElemKey()") - - // emulate EncStructFieldKey - switch ti.keyType { - case valueTypeInt: - x.linef("r.EncodeInt(z.M.Int(strconv.ParseInt(`%s`, 10, 64)))", si.encName) - case valueTypeUint: - x.linef("r.EncodeUint(z.M.Uint(strconv.ParseUint(`%s`, 10, 64)))", si.encName) - case valueTypeFloat: - x.linef("r.EncodeFloat64(z.M.Float(strconv.ParseFloat(`%s`, 64)))", si.encName) - default: // string - if si.encNameAsciiAlphaNum { - x.linef(`if z.IsJSONHandle() { z.WriteStr("\"%s\"") } else { `, si.encName) - } - x.linef("r.EncodeStringEnc(codecSelferCcUTF8%s, `%s`)", x.xs, si.encName) - if si.encNameAsciiAlphaNum { - x.linef("}") - } - } - // x.linef("r.EncStructFieldKey(codecSelferValueType%s%s, `%s`)", ti.keyType.String(), x.xs, si.encName) - x.line("r.WriteMapElemValue()") - if labelUsed { - x.line("if " + isNilVarName + " { r.EncodeNil() } else { ") - x.encVar(varname+"."+t2.Name, t2.Type) - x.line("}") - } else { - x.encVar(varname+"."+t2.Name, t2.Type) - } - if si.omitEmpty() { - x.line("}") - } - x.linef("} ") // end if/else ti.toArray - } - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray { - x.line("r.WriteArrayEnd()") - x.line("} else {") - x.line("r.WriteMapEnd()") - x.line("}") - -} - -func (x *genRunner) encListFallback(varname string, t reflect.Type) { - elemBytes := t.Elem().Kind() == reflect.Uint8 - if t.AssignableTo(uint8SliceTyp) { - x.linef("r.EncodeStringBytesRaw([]byte(%s))", varname) - return - } - if t.Kind() == reflect.Array && elemBytes { - x.linef("r.EncodeStringBytesRaw(((*[%d]byte)(%s))[:])", t.Len(), varname) - return - } - i := x.varsfx() - if t.Kind() == reflect.Chan { - type ts struct { - Label, Chan, Slice, Sfx string - } - tm, err := template.New("").Parse(genEncChanTmpl) - if err != nil { - panic(err) - } - x.linef("if %s == nil { r.EncodeNil() } else { ", varname) - x.linef("var sch%s []%s", i, x.genTypeName(t.Elem())) - err = tm.Execute(x.w, &ts{"Lsch" + i, varname, "sch" + i, i}) - if err != nil { - panic(err) - } - // x.linef("%s = sch%s", varname, i) - if elemBytes { - x.linef("r.EncodeStringBytesRaw([]byte(%s))", "sch"+i) - x.line("}") - return - } - varname = "sch" + i - } - - x.line("r.WriteArrayStart(len(" + varname + "))") - x.linef("for _, %sv%s := range %s {", genTempVarPfx, i, varname) - x.line("r.WriteArrayElem()") - - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line("}") - x.line("r.WriteArrayEnd()") - if t.Kind() == reflect.Chan { - x.line("}") - } -} - -func (x *genRunner) encMapFallback(varname string, t reflect.Type) { - // TODO: expand this to handle canonical. - i := x.varsfx() - x.line("r.WriteMapStart(len(" + varname + "))") - x.linef("for %sk%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname) - x.line("r.WriteMapElemKey()") - x.encVar(genTempVarPfx+"k"+i, t.Key()) - x.line("r.WriteMapElemValue()") - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line("}") - x.line("r.WriteMapEnd()") -} - -func (x *genRunner) decVarInitPtr(varname, nilvar string, t reflect.Type, si *structFieldInfo, - newbuf, nilbuf *genBuf) (t2 reflect.StructField) { - //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value. - // t2 = t.FieldByIndex(si.is) - t2typ := t - varname3 := varname - t2kind := t2typ.Kind() - var nilbufed bool - if si != nil { - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - t2kind = t2typ.Kind() - if t2kind != reflect.Ptr { - continue - } - if newbuf != nil { - newbuf.f("if %s == nil { %s = new(%s) }\n", varname3, varname3, x.genTypeName(t2typ.Elem())) - } - if nilbuf != nil { - if !nilbufed { - nilbuf.s("if true") - nilbufed = true - } - nilbuf.s(" && ").s(varname3).s(" != nil") - } - } - } - // if t2typ.Kind() == reflect.Ptr { - // varname3 = varname3 + t2.Name - // } - if nilbuf != nil { - if nilbufed { - nilbuf.s(" { ") - } - if nilvar != "" { - nilbuf.s(nilvar).s(" = true") - } else if tk := t2typ.Kind(); tk == reflect.Ptr { - if strings.IndexByte(varname3, '.') != -1 || strings.IndexByte(varname3, '[') != -1 { - nilbuf.s(varname3).s(" = nil") - } else { - nilbuf.s("*").s(varname3).s(" = ").s(x.genZeroValueR(t2typ.Elem())) - } - } else { - nilbuf.s(varname3).s(" = ").s(x.genZeroValueR(t2typ)) - } - if nilbufed { - nilbuf.s("}") - } - } - return t2 -} - -// decVar takes a variable called varname, of type t -func (x *genRunner) decVarMain(varname, rand string, t reflect.Type, checkNotNil bool) { - // We only encode as nil if a nillable value. - // This removes some of the wasted checks for TryDecodeAsNil. - // We need to think about this more, to see what happens if omitempty, etc - // cause a nil value to be stored when something is expected. - // This could happen when decoding from a struct encoded as an array. - // For that, decVar should be called with canNil=true, to force true as its value. - var varname2 string - if t.Kind() != reflect.Ptr { - if t.PkgPath() != "" || !x.decTryAssignPrimitive(varname, t, false) { - x.dec(varname, t, false) - } - } else { - if checkNotNil { - x.linef("if %s == nil { %s = new(%s) }", varname, varname, x.genTypeName(t.Elem())) - } - // Ensure we set underlying ptr to a non-nil value (so we can deref to it later). - // There's a chance of a **T in here which is nil. - var ptrPfx string - for t = t.Elem(); t.Kind() == reflect.Ptr; t = t.Elem() { - ptrPfx += "*" - if checkNotNil { - x.linef("if %s%s == nil { %s%s = new(%s)}", - ptrPfx, varname, ptrPfx, varname, x.genTypeName(t)) - } - } - // Should we create temp var if a slice/map indexing? No. dec(...) can now handle it. - - if ptrPfx == "" { - x.dec(varname, t, true) - } else { - varname2 = genTempVarPfx + "z" + rand - x.line(varname2 + " := " + ptrPfx + varname) - x.dec(varname2, t, true) - } - } -} - -// decVar takes a variable called varname, of type t -func (x *genRunner) decVar(varname, nilvar string, t reflect.Type, canBeNil, checkNotNil bool) { - i := x.varsfx() - - // We only encode as nil if a nillable value. - // This removes some of the wasted checks for TryDecodeAsNil. - // We need to think about this more, to see what happens if omitempty, etc - // cause a nil value to be stored when something is expected. - // This could happen when decoding from a struct encoded as an array. - // For that, decVar should be called with canNil=true, to force true as its value. - - if !canBeNil { - canBeNil = genAnythingCanBeNil || !genIsImmutable(t) - } - - if canBeNil { - var buf genBuf - x.decVarInitPtr(varname, nilvar, t, nil, nil, &buf) - x.linef("if r.TryDecodeAsNil() { %s } else {", buf.buf) - } else { - x.line("// cannot be nil") - } - - x.decVarMain(varname, i, t, checkNotNil) - - if canBeNil { - x.line("} ") - } -} - -// dec will decode a variable (varname) of type t or ptrTo(t) if isptr==true. -// t is always a basetype (i.e. not of kind reflect.Ptr). -func (x *genRunner) dec(varname string, t reflect.Type, isptr bool) { - // assumptions: - // - the varname is to a pointer already. No need to take address of it - // - t is always a baseType T (not a *T, etc). - rtid := rt2id(t) - ti2 := x.ti.get(rtid, t) - // tptr := reflect.PtrTo(t) - if x.checkForSelfer(t, varname) { - if ti2.cs || ti2.csp { // t.Implements(selferTyp) || tptr.Implements(selferTyp) { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - if _, ok := x.td[rtid]; ok { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - } - - inlist := false - for _, t0 := range x.t { - if t == t0 { - inlist = true - if x.checkForSelfer(t, varname) { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - break - } - } - - var rtidAdded bool - if t == x.tc { - x.td[rtid] = true - rtidAdded = true - } - - // check if - // - type is time.Time, Raw, RawExt - // - the type implements (Text|JSON|Binary)(Unm|M)arshal - - mi := x.varsfx() - // x.linef("%sm%s := z.DecBinary()", genTempVarPfx, mi) - // x.linef("_ = %sm%s", genTempVarPfx, mi) - x.line("if false {") //start if block - defer func() { x.line("}") }() //end if block - - var ptrPfx, addrPfx string - if isptr { - ptrPfx = "*" - } else { - addrPfx = "&" - } - if t == timeTyp { - x.linef("} else if !z.DecBasicHandle().TimeNotBuiltin { %s%v = r.DecodeTime()", ptrPfx, varname) - // return - } - if t == rawTyp { - x.linef("} else { %s%v = z.DecRaw()", ptrPfx, varname) - return - } - - if t == rawExtTyp { - x.linef("} else { r.DecodeExt(%s%v, 0, nil)", addrPfx, varname) - return - } - - // only check for extensions if the type is named, and has a packagePath. - if !x.nx && genImportPath(t) != "" && t.Name() != "" { - // first check if extensions are configued, before doing the interface conversion - // x.linef("} else if z.HasExtensions() && z.DecExt(%s) {", varname) - yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi) - x.linef("} else if %s := z.Extension(z.I2Rtid(%s)); %s != nil { z.DecExtension(%s, %s) ", yy, varname, yy, varname, yy) - } - - if ti2.bu || ti2.bup { // t.Implements(binaryUnmarshalerTyp) || tptr.Implements(binaryUnmarshalerTyp) { - x.linef("} else if z.DecBinary() { z.DecBinaryUnmarshal(%s%v) ", addrPfx, varname) - } - if ti2.ju || ti2.jup { // t.Implements(jsonUnmarshalerTyp) || tptr.Implements(jsonUnmarshalerTyp) { - x.linef("} else if !z.DecBinary() && z.IsJSONHandle() { z.DecJSONUnmarshal(%s%v)", addrPfx, varname) - } else if ti2.tu || ti2.tup { // t.Implements(textUnmarshalerTyp) || tptr.Implements(textUnmarshalerTyp) { - x.linef("} else if !z.DecBinary() { z.DecTextUnmarshal(%s%v)", addrPfx, varname) - } - - x.line("} else {") - - if x.decTryAssignPrimitive(varname, t, isptr) { - return - } - - switch t.Kind() { - case reflect.Array, reflect.Chan: - x.xtraSM(varname, t, false, isptr) - case reflect.Slice: - // if a []uint8, call dedicated function - // if a known fastpath slice, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if rtid == uint8SliceTypId { - x.linef("%s%s = r.DecodeBytes(%s(%s[]byte)(%s), false)", - ptrPfx, varname, ptrPfx, ptrPfx, varname) - } else if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname) - } else { - x.xtraSM(varname, t, false, isptr) - // x.decListFallback(varname, rtid, false, t) - } - case reflect.Map: - // if a known fastpath map, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname) - } else { - x.xtraSM(varname, t, false, isptr) - // x.decMapFallback(varname, rtid, t) - } - case reflect.Struct: - if inlist { - // no need to create temp variable if isptr, or x.F or x[F] - if isptr || strings.IndexByte(varname, '.') != -1 || strings.IndexByte(varname, '[') != -1 { - x.decStruct(varname, rtid, t) - } else { - varname2 := genTempVarPfx + "j" + mi - x.line(varname2 + " := &" + varname) - x.decStruct(varname2, rtid, t) - } - } else { - // delete(x.td, rtid) - x.line("z.DecFallback(" + addrPfx + varname + ", false)") - } - default: - if rtidAdded { - delete(x.te, rtid) - } - x.line("z.DecFallback(" + addrPfx + varname + ", true)") - } -} - -func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type, isptr bool) (done bool) { - // This should only be used for exact primitives (ie un-named types). - // Named types may be implementations of Selfer, Unmarshaler, etc. - // They should be handled by dec(...) - - var ptr string - if isptr { - ptr = "*" - } - switch t.Kind() { - case reflect.Int: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - case reflect.Int8: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 8))", ptr, varname, x.genTypeName(t)) - case reflect.Int16: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 16))", ptr, varname, x.genTypeName(t)) - case reflect.Int32: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 32))", ptr, varname, x.genTypeName(t)) - case reflect.Int64: - x.linef("%s%s = (%s)(r.DecodeInt64())", ptr, varname, x.genTypeName(t)) - - case reflect.Uint: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - case reflect.Uint8: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 8))", ptr, varname, x.genTypeName(t)) - case reflect.Uint16: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 16))", ptr, varname, x.genTypeName(t)) - case reflect.Uint32: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 32))", ptr, varname, x.genTypeName(t)) - case reflect.Uint64: - x.linef("%s%s = (%s)(r.DecodeUint64())", ptr, varname, x.genTypeName(t)) - case reflect.Uintptr: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - - case reflect.Float32: - x.linef("%s%s = (%s)(r.DecodeFloat32As64())", ptr, varname, x.genTypeName(t)) - case reflect.Float64: - x.linef("%s%s = (%s)(r.DecodeFloat64())", ptr, varname, x.genTypeName(t)) - - case reflect.Bool: - x.linef("%s%s = (%s)(r.DecodeBool())", ptr, varname, x.genTypeName(t)) - case reflect.String: - x.linef("%s%s = (%s)(r.DecodeString())", ptr, varname, x.genTypeName(t)) - default: - return false - } - return true -} - -func (x *genRunner) decListFallback(varname string, rtid uintptr, t reflect.Type) { - if t.AssignableTo(uint8SliceTyp) { - x.line("*" + varname + " = r.DecodeBytes(*((*[]byte)(" + varname + ")), false)") - return - } - if t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 { - x.linef("r.DecodeBytes( ((*[%d]byte)(%s))[:], true)", t.Len(), varname) - return - } - type tstruc struct { - TempVar string - Rand string - Varname string - CTyp string - Typ string - Immutable bool - Size int - } - telem := t.Elem() - ts := tstruc{genTempVarPfx, x.varsfx(), varname, x.genTypeName(t), x.genTypeName(telem), genIsImmutable(telem), int(telem.Size())} - - funcs := make(template.FuncMap) - - funcs["decLineVar"] = func(varname string) string { - x.decVar(varname, "", telem, false, true) - return "" - } - funcs["var"] = func(s string) string { - return ts.TempVar + s + ts.Rand - } - funcs["zero"] = func() string { - return x.genZeroValueR(telem) - } - funcs["isArray"] = func() bool { - return t.Kind() == reflect.Array - } - funcs["isSlice"] = func() bool { - return t.Kind() == reflect.Slice - } - funcs["isChan"] = func() bool { - return t.Kind() == reflect.Chan - } - tm, err := template.New("").Funcs(funcs).Parse(genDecListTmpl) - if err != nil { - panic(err) - } - if err = tm.Execute(x.w, &ts); err != nil { - panic(err) - } -} - -func (x *genRunner) decMapFallback(varname string, rtid uintptr, t reflect.Type) { - type tstruc struct { - TempVar string - Sfx string - Rand string - Varname string - KTyp string - Typ string - Size int - } - telem := t.Elem() - tkey := t.Key() - ts := tstruc{ - genTempVarPfx, x.xs, x.varsfx(), varname, x.genTypeName(tkey), - x.genTypeName(telem), int(telem.Size() + tkey.Size()), - } - - funcs := make(template.FuncMap) - funcs["decElemZero"] = func() string { - return x.genZeroValueR(telem) - } - funcs["decElemKindImmutable"] = func() bool { - return genIsImmutable(telem) - } - funcs["decElemKindPtr"] = func() bool { - return telem.Kind() == reflect.Ptr - } - funcs["decElemKindIntf"] = func() bool { - return telem.Kind() == reflect.Interface - } - funcs["decLineVarK"] = func(varname string) string { - x.decVar(varname, "", tkey, false, true) - return "" - } - funcs["decLineVar"] = func(varname, decodedNilVarname string) string { - x.decVar(varname, decodedNilVarname, telem, false, true) - return "" - } - funcs["var"] = func(s string) string { - return ts.TempVar + s + ts.Rand - } - - tm, err := template.New("").Funcs(funcs).Parse(genDecMapTmpl) - if err != nil { - panic(err) - } - if err = tm.Execute(x.w, &ts); err != nil { - panic(err) - } -} - -func (x *genRunner) decStructMapSwitch(kName string, varname string, rtid uintptr, t reflect.Type) { - ti := x.ti.get(rtid, t) - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - x.line("switch (" + kName + ") {") - var newbuf, nilbuf genBuf - for _, si := range tisfi { - x.line("case \"" + si.encName + "\":") - newbuf.reset() - nilbuf.reset() - t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf) - x.linef("if r.TryDecodeAsNil() { %s } else { %s", nilbuf.buf, newbuf.buf) - x.decVarMain(varname+"."+t2.Name, x.varsfx(), t2.Type, false) - x.line("}") - } - x.line("default:") - // pass the slice here, so that the string will not escape, and maybe save allocation - x.line("z.DecStructFieldNotFound(-1, " + kName + ")") - x.line("} // end switch " + kName) -} - -func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t reflect.Type, style genStructMapStyle) { - tpfx := genTempVarPfx - ti := x.ti.get(rtid, t) - i := x.varsfx() - kName := tpfx + "s" + i - - switch style { - case genStructMapStyleLenPrefix: - x.linef("for %sj%s := 0; %sj%s < %s; %sj%s++ {", tpfx, i, tpfx, i, lenvarname, tpfx, i) - case genStructMapStyleCheckBreak: - x.linef("for %sj%s := 0; !r.CheckBreak(); %sj%s++ {", tpfx, i, tpfx, i) - default: // 0, otherwise. - x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length - x.linef("for %sj%s := 0; ; %sj%s++ {", tpfx, i, tpfx, i) - x.linef("if %shl%s { if %sj%s >= %s { break }", tpfx, i, tpfx, i, lenvarname) - x.line("} else { if r.CheckBreak() { break }; }") - } - x.line("r.ReadMapElemKey()") - - // emulate decstructfieldkey - switch ti.keyType { - case valueTypeInt: - x.linef("%s := z.StringView(strconv.AppendInt(z.DecScratchArrayBuffer()[:0], r.DecodeInt64(), 10))", kName) - case valueTypeUint: - x.linef("%s := z.StringView(strconv.AppendUint(z.DecScratchArrayBuffer()[:0], r.DecodeUint64(), 10))", kName) - case valueTypeFloat: - x.linef("%s := z.StringView(strconv.AppendFloat(z.DecScratchArrayBuffer()[:0], r.DecodeFloat64(), 'f', -1, 64))", kName) - default: // string - x.linef("%s := z.StringView(r.DecodeStringAsBytes())", kName) - } - // x.linef("%s := z.StringView(r.DecStructFieldKey(codecSelferValueType%s%s, z.DecScratchArrayBuffer()))", kName, ti.keyType.String(), x.xs) - - x.line("r.ReadMapElemValue()") - x.decStructMapSwitch(kName, varname, rtid, t) - - x.line("} // end for " + tpfx + "j" + i) - x.line("r.ReadMapEnd()") -} - -func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid uintptr, t reflect.Type) { - tpfx := genTempVarPfx - i := x.varsfx() - ti := x.ti.get(rtid, t) - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - x.linef("var %sj%s int", tpfx, i) - x.linef("var %sb%s bool", tpfx, i) // break - x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length - var newbuf, nilbuf genBuf - for _, si := range tisfi { - x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }", - tpfx, i, tpfx, i, tpfx, i, - tpfx, i, lenvarname, tpfx, i) - x.linef("if %sb%s { r.ReadArrayEnd(); %s }", tpfx, i, breakString) - x.line("r.ReadArrayElem()") - newbuf.reset() - nilbuf.reset() - t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf) - x.linef("if r.TryDecodeAsNil() { %s } else { %s", nilbuf.buf, newbuf.buf) - x.decVarMain(varname+"."+t2.Name, x.varsfx(), t2.Type, false) - x.line("}") - } - // read remaining values and throw away. - x.line("for {") - x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }", - tpfx, i, tpfx, i, tpfx, i, - tpfx, i, lenvarname, tpfx, i) - x.linef("if %sb%s { break }", tpfx, i) - x.line("r.ReadArrayElem()") - x.linef(`z.DecStructFieldNotFound(%sj%s - 1, "")`, tpfx, i) - x.line("}") - x.line("r.ReadArrayEnd()") -} - -func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) { - // varname MUST be a ptr, or a struct field or a slice element. - i := x.varsfx() - x.linef("%sct%s := r.ContainerType()", genTempVarPfx, i) - x.linef("if %sct%s == codecSelferValueTypeMap%s {", genTempVarPfx, i, x.xs) - x.line(genTempVarPfx + "l" + i + " := r.ReadMapStart()") - x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadMapEnd()") - if genUseOneFunctionForDecStructMap { - x.line("} else { ") - x.linef("%s.codecDecodeSelfFromMap(%sl%s, d)", varname, genTempVarPfx, i) - } else { - x.line("} else if " + genTempVarPfx + "l" + i + " > 0 { ") - x.line(varname + ".codecDecodeSelfFromMapLenPrefix(" + genTempVarPfx + "l" + i + ", d)") - x.line("} else {") - x.line(varname + ".codecDecodeSelfFromMapCheckBreak(" + genTempVarPfx + "l" + i + ", d)") - } - x.line("}") - - // else if container is array - x.linef("} else if %sct%s == codecSelferValueTypeArray%s {", genTempVarPfx, i, x.xs) - x.line(genTempVarPfx + "l" + i + " := r.ReadArrayStart()") - x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadArrayEnd()") - x.line("} else { ") - x.linef("%s.codecDecodeSelfFromArray(%sl%s, d)", varname, genTempVarPfx, i) - x.line("}") - // else panic - x.line("} else { ") - x.line("panic(errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + ")") - x.line("} ") -} - -// -------- - -type genV struct { - // genV is either a primitive (Primitive != "") or a map (MapKey != "") or a slice - MapKey string - Elem string - Primitive string - Size int -} - -func (x *genRunner) newGenV(t reflect.Type) (v genV) { - switch t.Kind() { - case reflect.Slice, reflect.Array: - te := t.Elem() - v.Elem = x.genTypeName(te) - v.Size = int(te.Size()) - case reflect.Map: - te, tk := t.Elem(), t.Key() - v.Elem = x.genTypeName(te) - v.MapKey = x.genTypeName(tk) - v.Size = int(te.Size() + tk.Size()) - default: - panic("unexpected type for newGenV. Requires map or slice type") - } - return -} - -func (x *genV) MethodNamePfx(prefix string, prim bool) string { - var name []byte - if prefix != "" { - name = append(name, prefix...) - } - if prim { - name = append(name, genTitleCaseName(x.Primitive)...) - } else { - if x.MapKey == "" { - name = append(name, "Slice"...) - } else { - name = append(name, "Map"...) - name = append(name, genTitleCaseName(x.MapKey)...) - } - name = append(name, genTitleCaseName(x.Elem)...) - } - return string(name) - -} - -// genImportPath returns import path of a non-predeclared named typed, or an empty string otherwise. -// -// This handles the misbehaviour that occurs when 1.5-style vendoring is enabled, -// where PkgPath returns the full path, including the vendoring pre-fix that should have been stripped. -// We strip it here. -func genImportPath(t reflect.Type) (s string) { - s = t.PkgPath() - if genCheckVendor { - // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7 - s = genStripVendor(s) - } - return -} - -// A go identifier is (letter|_)[letter|number|_]* -func genGoIdentifier(s string, checkFirstChar bool) string { - b := make([]byte, 0, len(s)) - t := make([]byte, 4) - var n int - for i, r := range s { - if checkFirstChar && i == 0 && !unicode.IsLetter(r) { - b = append(b, '_') - } - // r must be unicode_letter, unicode_digit or _ - if unicode.IsLetter(r) || unicode.IsDigit(r) { - n = utf8.EncodeRune(t, r) - b = append(b, t[:n]...) - } else { - b = append(b, '_') - } - } - return string(b) -} - -func genNonPtr(t reflect.Type) reflect.Type { - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t -} - -func genTitleCaseName(s string) string { - switch s { - case "interface{}", "interface {}": - return "Intf" - default: - return strings.ToUpper(s[0:1]) + s[1:] - } -} - -func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) { - var ptrPfx string - for t.Kind() == reflect.Ptr { - ptrPfx += "Ptrto" - t = t.Elem() - } - tstr := t.String() - if tn := t.Name(); tn != "" { - if tRef != nil && genImportPath(t) == genImportPath(tRef) { - return ptrPfx + tn - } else { - if genQNameRegex.MatchString(tstr) { - return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } - } - switch t.Kind() { - case reflect.Map: - return ptrPfx + "Map" + genMethodNameT(t.Key(), tRef) + genMethodNameT(t.Elem(), tRef) - case reflect.Slice: - return ptrPfx + "Slice" + genMethodNameT(t.Elem(), tRef) - case reflect.Array: - return ptrPfx + "Array" + strconv.FormatInt(int64(t.Len()), 10) + genMethodNameT(t.Elem(), tRef) - case reflect.Chan: - var cx string - switch t.ChanDir() { - case reflect.SendDir: - cx = "ChanSend" - case reflect.RecvDir: - cx = "ChanRecv" - default: - cx = "Chan" - } - return ptrPfx + cx + genMethodNameT(t.Elem(), tRef) - default: - if t == intfTyp { - return ptrPfx + "Interface" - } else { - if tRef != nil && genImportPath(t) == genImportPath(tRef) { - if t.Name() != "" { - return ptrPfx + t.Name() - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } else { - // best way to get the package name inclusive - // return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - // return ptrPfx + genBase64enc.EncodeToString([]byte(tstr)) - if t.Name() != "" && genQNameRegex.MatchString(tstr) { - return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } - } - } -} - -// genCustomNameForType base64encodes the t.String() value in such a way -// that it can be used within a function name. -func genCustomTypeName(tstr string) string { - len2 := genBase64enc.EncodedLen(len(tstr)) - bufx := make([]byte, len2) - genBase64enc.Encode(bufx, []byte(tstr)) - for i := len2 - 1; i >= 0; i-- { - if bufx[i] == '=' { - len2-- - } else { - break - } - } - return string(bufx[:len2]) -} - -func genIsImmutable(t reflect.Type) (v bool) { - return isImmutableKind(t.Kind()) -} - -type genInternal struct { - Version int - Values []genV -} - -func (x genInternal) FastpathLen() (l int) { - for _, v := range x.Values { - if v.Primitive == "" && !(v.MapKey == "" && v.Elem == "uint8") { - l++ - } - } - return -} - -func genInternalZeroValue(s string) string { - switch s { - case "interface{}", "interface {}": - return "nil" - case "bool": - return "false" - case "string": - return `""` - default: - return "0" - } -} - -var genInternalNonZeroValueIdx [5]uint64 -var genInternalNonZeroValueStrs = [2][5]string{ - {`"string-is-an-interface"`, "true", `"some-string"`, "11.1", "33"}, - {`"string-is-an-interface-2"`, "true", `"some-string-2"`, "22.2", "44"}, -} - -func genInternalNonZeroValue(s string) string { - switch s { - case "interface{}", "interface {}": - genInternalNonZeroValueIdx[0]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[0]%2][0] // return string, to remove ambiguity - case "bool": - genInternalNonZeroValueIdx[1]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[1]%2][1] - case "string": - genInternalNonZeroValueIdx[2]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[2]%2][2] - case "float32", "float64", "float", "double": - genInternalNonZeroValueIdx[3]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[3]%2][3] - default: - genInternalNonZeroValueIdx[4]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[4]%2][4] - } -} - -func genInternalEncCommandAsString(s string, vname string) string { - switch s { - case "uint", "uint8", "uint16", "uint32", "uint64": - return "ee.EncodeUint(uint64(" + vname + "))" - case "int", "int8", "int16", "int32", "int64": - return "ee.EncodeInt(int64(" + vname + "))" - case "string": - return "if e.h.StringToRaw { ee.EncodeStringBytesRaw(bytesView(" + vname + ")) " + - "} else { ee.EncodeStringEnc(cUTF8, " + vname + ") }" - case "float32": - return "ee.EncodeFloat32(" + vname + ")" - case "float64": - return "ee.EncodeFloat64(" + vname + ")" - case "bool": - return "ee.EncodeBool(" + vname + ")" - // case "symbol": - // return "ee.EncodeSymbol(" + vname + ")" - default: - return "e.encode(" + vname + ")" - } -} - -func genInternalDecCommandAsString(s string) string { - switch s { - case "uint": - return "uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize))" - case "uint8": - return "uint8(chkOvf.UintV(dd.DecodeUint64(), 8))" - case "uint16": - return "uint16(chkOvf.UintV(dd.DecodeUint64(), 16))" - case "uint32": - return "uint32(chkOvf.UintV(dd.DecodeUint64(), 32))" - case "uint64": - return "dd.DecodeUint64()" - case "uintptr": - return "uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize))" - case "int": - return "int(chkOvf.IntV(dd.DecodeInt64(), intBitsize))" - case "int8": - return "int8(chkOvf.IntV(dd.DecodeInt64(), 8))" - case "int16": - return "int16(chkOvf.IntV(dd.DecodeInt64(), 16))" - case "int32": - return "int32(chkOvf.IntV(dd.DecodeInt64(), 32))" - case "int64": - return "dd.DecodeInt64()" - - case "string": - return "dd.DecodeString()" - case "float32": - return "float32(chkOvf.Float32V(dd.DecodeFloat64()))" - case "float64": - return "dd.DecodeFloat64()" - case "bool": - return "dd.DecodeBool()" - default: - panic(errors.New("gen internal: unknown type for decode: " + s)) - } -} - -func genInternalSortType(s string, elem bool) string { - for _, v := range [...]string{"int", "uint", "float", "bool", "string"} { - if strings.HasPrefix(s, v) { - if elem { - if v == "int" || v == "uint" || v == "float" { - return v + "64" - } else { - return v - } - } - return v + "Slice" - } - } - panic("sorttype: unexpected type: " + s) -} - -func genStripVendor(s string) string { - // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later. - // if s contains /vendor/ OR startsWith vendor/, then return everything after it. - const vendorStart = "vendor/" - const vendorInline = "/vendor/" - if i := strings.LastIndex(s, vendorInline); i >= 0 { - s = s[i+len(vendorInline):] - } else if strings.HasPrefix(s, vendorStart) { - s = s[len(vendorStart):] - } - return s -} - -// var genInternalMu sync.Mutex -var genInternalV = genInternal{Version: genVersion} -var genInternalTmplFuncs template.FuncMap -var genInternalOnce sync.Once - -func genInternalInit() { - types := [...]string{ - "interface{}", - "string", - "float32", - "float64", - "uint", - "uint8", - "uint16", - "uint32", - "uint64", - "uintptr", - "int", - "int8", - "int16", - "int32", - "int64", - "bool", - } - // keep as slice, so it is in specific iteration order. - // Initial order was uint64, string, interface{}, int, int64 - mapvaltypes := [...]string{ - "interface{}", - "string", - "uint", - "uint8", - "uint16", - "uint32", - "uint64", - "uintptr", - "int", - "int8", - "int16", - "int32", - "int64", - "float32", - "float64", - "bool", - } - wordSizeBytes := int(intBitsize) / 8 - - mapvaltypes2 := map[string]int{ - "interface{}": 2 * wordSizeBytes, - "string": 2 * wordSizeBytes, - "uint": 1 * wordSizeBytes, - "uint8": 1, - "uint16": 2, - "uint32": 4, - "uint64": 8, - "uintptr": 1 * wordSizeBytes, - "int": 1 * wordSizeBytes, - "int8": 1, - "int16": 2, - "int32": 4, - "int64": 8, - "float32": 4, - "float64": 8, - "bool": 1, - } - var gt = genInternal{Version: genVersion} - - // For each slice or map type, there must be a (symmetrical) Encode and Decode fast-path function - for _, s := range types { - gt.Values = append(gt.Values, genV{Primitive: s, Size: mapvaltypes2[s]}) - // if s != "uint8" { // do not generate fast path for slice of bytes. Treat specially already. - // gt.Values = append(gt.Values, genV{Elem: s, Size: mapvaltypes2[s]}) - // } - gt.Values = append(gt.Values, genV{Elem: s, Size: mapvaltypes2[s]}) - if _, ok := mapvaltypes2[s]; !ok { - gt.Values = append(gt.Values, genV{MapKey: s, Elem: s, Size: 2 * mapvaltypes2[s]}) - } - for _, ms := range mapvaltypes { - gt.Values = append(gt.Values, genV{MapKey: s, Elem: ms, Size: mapvaltypes2[s] + mapvaltypes2[ms]}) - } - } - - funcs := make(template.FuncMap) - // funcs["haspfx"] = strings.HasPrefix - funcs["encmd"] = genInternalEncCommandAsString - funcs["decmd"] = genInternalDecCommandAsString - funcs["zerocmd"] = genInternalZeroValue - funcs["nonzerocmd"] = genInternalNonZeroValue - funcs["hasprefix"] = strings.HasPrefix - funcs["sorttype"] = genInternalSortType - - genInternalV = gt - genInternalTmplFuncs = funcs -} - -// genInternalGoFile is used to generate source files from templates. -// It is run by the program author alone. -// Unfortunately, it has to be exported so that it can be called from a command line tool. -// *** DO NOT USE *** -func genInternalGoFile(r io.Reader, w io.Writer) (err error) { - genInternalOnce.Do(genInternalInit) - - gt := genInternalV - - t := template.New("").Funcs(genInternalTmplFuncs) - - tmplstr, err := ioutil.ReadAll(r) - if err != nil { - return - } - - if t, err = t.Parse(string(tmplstr)); err != nil { - return - } - - var out bytes.Buffer - err = t.Execute(&out, gt) - if err != nil { - return - } - - bout, err := format.Source(out.Bytes()) - if err != nil { - w.Write(out.Bytes()) // write out if error, so we can still see. - // w.Write(bout) // write out if error, as much as possible, so we can still see. - return - } - w.Write(bout) - return -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_gte_go15.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_gte_go15.go deleted file mode 100644 index 9ddbe2059336f..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_gte_go15.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.5 - -package codec - -import "reflect" - -const reflectArrayOfSupported = true - -func reflectArrayOf(count int, elem reflect.Type) reflect.Type { - return reflect.ArrayOf(count, elem) -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_lt_go15.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_lt_go15.go deleted file mode 100644 index c5fcd6697ef6d..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_arrayof_lt_go15.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.5 - -package codec - -import "reflect" - -const reflectArrayOfSupported = false - -func reflectArrayOf(count int, elem reflect.Type) reflect.Type { - panic("codec: reflect.ArrayOf unsupported in this go version") -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_gte_go19.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_gte_go19.go deleted file mode 100644 index bc39d6b719f34..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_gte_go19.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.9 - -package codec - -import "reflect" - -func makeMapReflect(t reflect.Type, size int) reflect.Value { - if size < 0 { - return reflect.MakeMapWithSize(t, 4) - } - return reflect.MakeMapWithSize(t, size) -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_lt_go19.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_lt_go19.go deleted file mode 100644 index cde4cd372514d..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_makemap_lt_go19.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.9 - -package codec - -import "reflect" - -func makeMapReflect(t reflect.Type, size int) reflect.Value { - return reflect.MakeMap(t) -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_gte_go110.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_gte_go110.go deleted file mode 100644 index 794133a3cbb79..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_gte_go110.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.10 - -package codec - -const allowSetUnexportedEmbeddedPtr = false diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_lt_go110.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_lt_go110.go deleted file mode 100644 index fd92ede3558ec..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unexportedembeddedptr_lt_go110.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.10 - -package codec - -const allowSetUnexportedEmbeddedPtr = true diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unsupported_lt_go14.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unsupported_lt_go14.go deleted file mode 100644 index 8debfa6137131..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_unsupported_lt_go14.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.4 - -package codec - -// This codec package will only work for go1.4 and above. -// This is for the following reasons: -// - go 1.4 was released in 2014 -// - go runtime is written fully in go -// - interface only holds pointers -// - reflect.Value is stabilized as 3 words - -func init() { - panic("codec: go 1.3 and below are not supported") -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go15.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go15.go deleted file mode 100644 index 0f1bb01e5a134..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go15.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.5,!go1.6 - -package codec - -import "os" - -var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") == "1" diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go16.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go16.go deleted file mode 100644 index 2fb4b057ddc0b..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_eq_go16.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.6,!go1.7 - -package codec - -import "os" - -var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") != "0" diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_gte_go17.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_gte_go17.go deleted file mode 100644 index c5b8155053948..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_gte_go17.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.7 - -package codec - -const genCheckVendor = true diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_lt_go15.go b/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_lt_go15.go deleted file mode 100644 index 837cf240bae3a..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/goversion_vendor_lt_go15.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.5 - -package codec - -var genCheckVendor = false diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go index 228ad93d1594f..7da3955edc99f 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/helper.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go @@ -1,200 +1,68 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec // Contains code shared by both encode and decode. -// Some shared ideas around encoding/decoding -// ------------------------------------------ -// -// If an interface{} is passed, we first do a type assertion to see if it is -// a primitive type or a map/slice of primitive types, and use a fastpath to handle it. -// -// If we start with a reflect.Value, we are already in reflect.Value land and -// will try to grab the function for the underlying Type and directly call that function. -// This is more performant than calling reflect.Value.Interface(). -// -// This still helps us bypass many layers of reflection, and give best performance. -// -// Containers -// ------------ -// Containers in the stream are either associative arrays (key-value pairs) or -// regular arrays (indexed by incrementing integers). -// -// Some streams support indefinite-length containers, and use a breaking -// byte-sequence to denote that the container has come to an end. -// -// Some streams also are text-based, and use explicit separators to denote the -// end/beginning of different values. -// -// During encode, we use a high-level condition to determine how to iterate through -// the container. That decision is based on whether the container is text-based (with -// separators) or binary (without separators). If binary, we do not even call the -// encoding of separators. -// -// During decode, we use a different high-level condition to determine how to iterate -// through the containers. That decision is based on whether the stream contained -// a length prefix, or if it used explicit breaks. If length-prefixed, we assume that -// it has to be binary, and we do not even try to read separators. -// -// Philosophy -// ------------ -// On decode, this codec will update containers appropriately: -// - If struct, update fields from stream into fields of struct. -// If field in stream not found in struct, handle appropriately (based on option). -// If a struct field has no corresponding value in the stream, leave it AS IS. -// If nil in stream, set value to nil/zero value. -// - If map, update map from stream. -// If the stream value is NIL, set the map to nil. -// - if slice, try to update up to length of array in stream. -// if container len is less than stream array length, -// and container cannot be expanded, handled (based on option). -// This means you can decode 4-element stream array into 1-element array. -// -// ------------------------------------ -// On encode, user can specify omitEmpty. This means that the value will be omitted -// if the zero value. The problem may occur during decode, where omitted values do not affect -// the value being decoded into. This means that if decoding into a struct with an -// int field with current value=5, and the field is omitted in the stream, then after -// decoding, the value will still be 5 (not 0). -// omitEmpty only works if you guarantee that you always decode into zero-values. -// -// ------------------------------------ -// We could have truncated a map to remove keys not available in the stream, -// or set values in the struct which are not in the stream to their zero values. -// We decided against it because there is no efficient way to do it. -// We may introduce it as an option later. -// However, that will require enabling it for both runtime and code generation modes. -// -// To support truncate, we need to do 2 passes over the container: -// map -// - first collect all keys (e.g. in k1) -// - for each key in stream, mark k1 that the key should not be removed -// - after updating map, do second pass and call delete for all keys in k1 which are not marked -// struct: -// - for each field, track the *typeInfo s1 -// - iterate through all s1, and for each one not marked, set value to zero -// - this involves checking the possible anonymous fields which are nil ptrs. -// too much work. -// -// ------------------------------------------ -// Error Handling is done within the library using panic. -// -// This way, the code doesn't have to keep checking if an error has happened, -// and we don't have to keep sending the error value along with each call -// or storing it in the En|Decoder and checking it constantly along the way. -// -// The disadvantage is that small functions which use panics cannot be inlined. -// The code accounts for that by only using panics behind an interface; -// since interface calls cannot be inlined, this is irrelevant. -// -// We considered storing the error is En|Decoder. -// - once it has its err field set, it cannot be used again. -// - panicing will be optional, controlled by const flag. -// - code should always check error first and return early. -// We eventually decided against it as it makes the code clumsier to always -// check for these error conditions. - import ( - "bytes" - "encoding" "encoding/binary" - "errors" "fmt" - "io" "math" "reflect" "sort" - "strconv" "strings" "sync" - "sync/atomic" "time" + "unicode" + "unicode/utf8" ) const ( - scratchByteArrayLen = 32 - // initCollectionCap = 16 // 32 is defensive. 16 is preferred. + structTagName = "codec" - // Support encoding.(Binary|Text)(Unm|M)arshaler. + // Support + // encoding.BinaryMarshaler: MarshalBinary() (data []byte, err error) + // encoding.BinaryUnmarshaler: UnmarshalBinary(data []byte) error // This constant flag will enable or disable it. - supportMarshalInterfaces = true + supportBinaryMarshal = true + + // Each Encoder or Decoder uses a cache of functions based on conditionals, + // so that the conditionals are not run every time. + // + // Either a map or a slice is used to keep track of the functions. + // The map is more natural, but has a higher cost than a slice/array. + // This flag (useMapForCodecCache) controls which is used. + useMapForCodecCache = false + + // For some common container types, we can short-circuit an elaborate + // reflection dance and call encode/decode directly. + // The currently supported types are: + // - slices of strings, or id's (int64,uint64) or interfaces. + // - maps of str->str, str->intf, id(int64,uint64)->intf, intf->intf + shortCircuitReflectToFastPath = true // for debugging, set this to false, to catch panic traces. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic. recoverPanicToErr = true - // arrayCacheLen is the length of the cache used in encoder or decoder for - // allowing zero-alloc initialization. - // arrayCacheLen = 8 - - // size of the cacheline: defaulting to value for archs: amd64, arm64, 386 - // should use "runtime/internal/sys".CacheLineSize, but that is not exposed. - cacheLineSize = 64 + // if checkStructForEmptyValue, check structs fields to see if an empty value. + // This could be an expensive call, so possibly disable it. + checkStructForEmptyValue = false - wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize - wordSize = wordSizeBits / 8 - - // so structFieldInfo fits into 8 bytes - maxLevelsEmbedding = 14 - - // useFinalizers=true configures finalizers to release pool'ed resources - // acquired by Encoder/Decoder during their GC. - // - // Note that calling SetFinalizer is always expensive, - // as code must be run on the systemstack even for SetFinalizer(t, nil). - // - // We document that folks SHOULD call Release() when done, or they can - // explicitly call SetFinalizer themselves e.g. - // runtime.SetFinalizer(e, (*Encoder).Release) - // runtime.SetFinalizer(d, (*Decoder).Release) - useFinalizers = false + // if derefForIsEmptyValue, deref pointers and interfaces when checking isEmptyValue + derefForIsEmptyValue = false ) -var oneByteArr [1]byte -var zeroByteSlice = oneByteArr[:0:0] - -var codecgen bool - -var refBitset bitset256 -var pool pooler -var panicv panicHdl - -func init() { - pool.init() - - refBitset.set(byte(reflect.Map)) - refBitset.set(byte(reflect.Ptr)) - refBitset.set(byte(reflect.Func)) - refBitset.set(byte(reflect.Chan)) -} - -type clsErr struct { - closed bool // is it closed? - errClosed error // error on closing -} - -// type entryType uint8 - -// const ( -// entryTypeBytes entryType = iota // make this 0, so a comparison is cheap -// entryTypeIo -// entryTypeBufio -// entryTypeUnset = 255 -// ) - type charEncoding uint8 const ( - _ charEncoding = iota // make 0 unset - cUTF8 - cUTF16LE - cUTF16BE - cUTF32LE - cUTF32BE - // Deprecated: not a true char encoding value - cRAW charEncoding = 255 + c_RAW charEncoding = iota + c_UTF8 + c_UTF16LE + c_UTF16BE + c_UTF32LE + c_UTF32BE ) // valueType is the stream type @@ -212,2508 +80,517 @@ const ( valueTypeBytes valueTypeMap valueTypeArray - valueTypeTime + valueTypeTimestamp valueTypeExt - // valueTypeInvalid = 0xff -) - -var valueTypeStrings = [...]string{ - "Unset", - "Nil", - "Int", - "Uint", - "Float", - "Bool", - "String", - "Symbol", - "Bytes", - "Map", - "Array", - "Timestamp", - "Ext", -} - -func (x valueType) String() string { - if int(x) < len(valueTypeStrings) { - return valueTypeStrings[x] - } - return strconv.FormatInt(int64(x), 10) -} - -type seqType uint8 - -const ( - _ seqType = iota - seqTypeArray - seqTypeSlice - seqTypeChan -) - -// note that containerMapStart and containerArraySend are not sent. -// This is because the ReadXXXStart and EncodeXXXStart already does these. -type containerState uint8 - -const ( - _ containerState = iota - - containerMapStart // slot left open, since Driver method already covers it - containerMapKey - containerMapValue - containerMapEnd - containerArrayStart // slot left open, since Driver methods already cover it - containerArrayElem - containerArrayEnd -) - -// // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo -// type sfiIdx struct { -// name string -// index int -// } - -// do not recurse if a containing type refers to an embedded type -// which refers back to its containing type (via a pointer). -// The second time this back-reference happens, break out, -// so as not to cause an infinite loop. -const rgetMaxRecursion = 2 - -// Anecdotally, we believe most types have <= 12 fields. -// - even Java's PMD rules set TooManyFields threshold to 15. -// However, go has embedded fields, which should be regarded as -// top level, allowing structs to possibly double or triple. -// In addition, we don't want to keep creating transient arrays, -// especially for the sfi index tracking, and the evtypes tracking. -// -// So - try to keep typeInfoLoadArray within 2K bytes -const ( - typeInfoLoadArraySfisLen = 16 - typeInfoLoadArraySfiidxLen = 8 * 112 - typeInfoLoadArrayEtypesLen = 12 - typeInfoLoadArrayBLen = 8 * 4 + valueTypeInvalid = 0xff ) -type typeInfoLoad struct { - // fNames []string - // encNames []string - etypes []uintptr - sfis []structFieldInfo -} - -type typeInfoLoadArray struct { - // fNames [typeInfoLoadArrayLen]string - // encNames [typeInfoLoadArrayLen]string - sfis [typeInfoLoadArraySfisLen]structFieldInfo - sfiidx [typeInfoLoadArraySfiidxLen]byte - etypes [typeInfoLoadArrayEtypesLen]uintptr - b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names -} - -// mirror json.Marshaler and json.Unmarshaler here, -// so we don't import the encoding/json package - -type jsonMarshaler interface { - MarshalJSON() ([]byte, error) -} -type jsonUnmarshaler interface { - UnmarshalJSON([]byte) error -} - -type isZeroer interface { - IsZero() bool -} - -type codecError struct { - name string - err interface{} -} - -func (e codecError) Cause() error { - switch xerr := e.err.(type) { - case nil: - return nil - case error: - return xerr - case string: - return errors.New(xerr) - case fmt.Stringer: - return errors.New(xerr.String()) - default: - return fmt.Errorf("%v", e.err) - } -} - -func (e codecError) Error() string { - return fmt.Sprintf("%s error: %v", e.name, e.err) -} - -// type byteAccepter func(byte) bool - var ( bigen = binary.BigEndian structInfoFieldName = "_struct" - mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil)) - mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil)) - intfSliceTyp = reflect.TypeOf([]interface{}(nil)) - intfTyp = intfSliceTyp.Elem() - - reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem() - - stringTyp = reflect.TypeOf("") - timeTyp = reflect.TypeOf(time.Time{}) - rawExtTyp = reflect.TypeOf(RawExt{}) - rawTyp = reflect.TypeOf(Raw{}) - uintptrTyp = reflect.TypeOf(uintptr(0)) - uint8Typ = reflect.TypeOf(uint8(0)) - uint8SliceTyp = reflect.TypeOf([]uint8(nil)) - uintTyp = reflect.TypeOf(uint(0)) - intTyp = reflect.TypeOf(int(0)) - - mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem() - - binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() - binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() - - textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - - jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem() - jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem() - - selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem() - missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem() - iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem() - - uint8TypId = rt2id(uint8Typ) - uint8SliceTypId = rt2id(uint8SliceTyp) - rawExtTypId = rt2id(rawExtTyp) - rawTypId = rt2id(rawTyp) - intfTypId = rt2id(intfTyp) - timeTypId = rt2id(timeTyp) - stringTypId = rt2id(stringTyp) - - mapStrIntfTypId = rt2id(mapStrIntfTyp) - mapIntfIntfTypId = rt2id(mapIntfIntfTyp) - intfSliceTypId = rt2id(intfSliceTyp) - // mapBySliceTypId = rt2id(mapBySliceTyp) + cachedTypeInfo = make(map[uintptr]*typeInfo, 4) + cachedTypeInfoMutex sync.RWMutex + + intfSliceTyp = reflect.TypeOf([]interface{}(nil)) + intfTyp = intfSliceTyp.Elem() + + strSliceTyp = reflect.TypeOf([]string(nil)) + boolSliceTyp = reflect.TypeOf([]bool(nil)) + uintSliceTyp = reflect.TypeOf([]uint(nil)) + uint8SliceTyp = reflect.TypeOf([]uint8(nil)) + uint16SliceTyp = reflect.TypeOf([]uint16(nil)) + uint32SliceTyp = reflect.TypeOf([]uint32(nil)) + uint64SliceTyp = reflect.TypeOf([]uint64(nil)) + intSliceTyp = reflect.TypeOf([]int(nil)) + int8SliceTyp = reflect.TypeOf([]int8(nil)) + int16SliceTyp = reflect.TypeOf([]int16(nil)) + int32SliceTyp = reflect.TypeOf([]int32(nil)) + int64SliceTyp = reflect.TypeOf([]int64(nil)) + float32SliceTyp = reflect.TypeOf([]float32(nil)) + float64SliceTyp = reflect.TypeOf([]float64(nil)) - intBitsize = uint8(intTyp.Bits()) - uintBitsize = uint8(uintTyp.Bits()) - - // bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0} + mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil)) + mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil)) + mapStrStrTyp = reflect.TypeOf(map[string]string(nil)) + + mapIntIntfTyp = reflect.TypeOf(map[int]interface{}(nil)) + mapInt64IntfTyp = reflect.TypeOf(map[int64]interface{}(nil)) + mapUintIntfTyp = reflect.TypeOf(map[uint]interface{}(nil)) + mapUint64IntfTyp = reflect.TypeOf(map[uint64]interface{}(nil)) + + stringTyp = reflect.TypeOf("") + timeTyp = reflect.TypeOf(time.Time{}) + rawExtTyp = reflect.TypeOf(RawExt{}) + + mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem() + binaryMarshalerTyp = reflect.TypeOf((*binaryMarshaler)(nil)).Elem() + binaryUnmarshalerTyp = reflect.TypeOf((*binaryUnmarshaler)(nil)).Elem() + + rawExtTypId = reflect.ValueOf(rawExtTyp).Pointer() + intfTypId = reflect.ValueOf(intfTyp).Pointer() + timeTypId = reflect.ValueOf(timeTyp).Pointer() + + intfSliceTypId = reflect.ValueOf(intfSliceTyp).Pointer() + strSliceTypId = reflect.ValueOf(strSliceTyp).Pointer() + + boolSliceTypId = reflect.ValueOf(boolSliceTyp).Pointer() + uintSliceTypId = reflect.ValueOf(uintSliceTyp).Pointer() + uint8SliceTypId = reflect.ValueOf(uint8SliceTyp).Pointer() + uint16SliceTypId = reflect.ValueOf(uint16SliceTyp).Pointer() + uint32SliceTypId = reflect.ValueOf(uint32SliceTyp).Pointer() + uint64SliceTypId = reflect.ValueOf(uint64SliceTyp).Pointer() + intSliceTypId = reflect.ValueOf(intSliceTyp).Pointer() + int8SliceTypId = reflect.ValueOf(int8SliceTyp).Pointer() + int16SliceTypId = reflect.ValueOf(int16SliceTyp).Pointer() + int32SliceTypId = reflect.ValueOf(int32SliceTyp).Pointer() + int64SliceTypId = reflect.ValueOf(int64SliceTyp).Pointer() + float32SliceTypId = reflect.ValueOf(float32SliceTyp).Pointer() + float64SliceTypId = reflect.ValueOf(float64SliceTyp).Pointer() + + mapStrStrTypId = reflect.ValueOf(mapStrStrTyp).Pointer() + mapIntfIntfTypId = reflect.ValueOf(mapIntfIntfTyp).Pointer() + mapStrIntfTypId = reflect.ValueOf(mapStrIntfTyp).Pointer() + mapIntIntfTypId = reflect.ValueOf(mapIntIntfTyp).Pointer() + mapInt64IntfTypId = reflect.ValueOf(mapInt64IntfTyp).Pointer() + mapUintIntfTypId = reflect.ValueOf(mapUintIntfTyp).Pointer() + mapUint64IntfTypId = reflect.ValueOf(mapUint64IntfTyp).Pointer() + // Id = reflect.ValueOf().Pointer() + // mapBySliceTypId = reflect.ValueOf(mapBySliceTyp).Pointer() + + binaryMarshalerTypId = reflect.ValueOf(binaryMarshalerTyp).Pointer() + binaryUnmarshalerTypId = reflect.ValueOf(binaryUnmarshalerTyp).Pointer() + + intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits()) + uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits()) + + bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0} bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} - - chkOvf checkOverflow - - errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo") ) -var defTypeInfos = NewTypeInfos([]string{"codec", "json"}) - -var immutableKindsSet = [32]bool{ - // reflect.Invalid: , - reflect.Bool: true, - reflect.Int: true, - reflect.Int8: true, - reflect.Int16: true, - reflect.Int32: true, - reflect.Int64: true, - reflect.Uint: true, - reflect.Uint8: true, - reflect.Uint16: true, - reflect.Uint32: true, - reflect.Uint64: true, - reflect.Uintptr: true, - reflect.Float32: true, - reflect.Float64: true, - reflect.Complex64: true, - reflect.Complex128: true, - // reflect.Array - // reflect.Chan - // reflect.Func: true, - // reflect.Interface - // reflect.Map - // reflect.Ptr - // reflect.Slice - reflect.String: true, - // reflect.Struct - // reflect.UnsafePointer -} - -// Selfer defines methods by which a value can encode or decode itself. -// -// Any type which implements Selfer will be able to encode or decode itself. -// Consequently, during (en|de)code, this takes precedence over -// (text|binary)(M|Unm)arshal or extension support. -// -// By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself. -// If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error. -// For example, the snippet below will cause such an error. -// type testSelferRecur struct{} -// func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) } -// func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) } -// -// Note: *the first set of bytes of any value MUST NOT represent nil in the format*. -// This is because, during each decode, we first check the the next set of bytes -// represent nil, and if so, we just set the value to nil. -type Selfer interface { - CodecEncodeSelf(*Encoder) - CodecDecodeSelf(*Decoder) +type binaryUnmarshaler interface { + UnmarshalBinary(data []byte) error } -// MissingFielder defines the interface allowing structs to internally decode or encode -// values which do not map to struct fields. -// -// We expect that this interface is bound to a pointer type (so the mutation function works). -// -// A use-case is if a version of a type unexports a field, but you want compatibility between -// both versions during encoding and decoding. -// -// Note that the interface is completely ignored during codecgen. -type MissingFielder interface { - // CodecMissingField is called to set a missing field and value pair. - // - // It returns true if the missing field was set on the struct. - CodecMissingField(field []byte, value interface{}) bool - - // CodecMissingFields returns the set of fields which are not struct fields - CodecMissingFields() map[string]interface{} +type binaryMarshaler interface { + MarshalBinary() (data []byte, err error) } -// MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream. +// MapBySlice represents a slice which should be encoded as a map in the stream. // The slice contains a sequence of key-value pairs. -// This affords storing a map in a specific sequence in the stream. -// -// Example usage: -// type T1 []string // or []int or []Point or any other "slice" type -// func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map -// type T2 struct { KeyValues T1 } -// -// var kvs = []string{"one", "1", "two", "2", "three", "3"} -// var v2 = T2{ KeyValues: T1(kvs) } -// // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} } -// -// The support of MapBySlice affords the following: -// - A slice type which implements MapBySlice will be encoded as a map -// - A slice can be decoded from a map in the stream -// - It MUST be a slice type (not a pointer receiver) that implements MapBySlice type MapBySlice interface { MapBySlice() } -// BasicHandle encapsulates the common options and extension functions. +// WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED. // -// Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED. +// BasicHandle encapsulates the common options and extension functions. type BasicHandle struct { - // BasicHandle is always a part of a different type. - // It doesn't have to fit into it own cache lines. - - // TypeInfos is used to get the type info for any type. - // - // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json - TypeInfos *TypeInfos - - // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls). - // If *[]T is used instead, this becomes comparable, at the cost of extra indirection. - // Thses slices are used all the time, so keep as slices (not pointers). - extHandle - - intf2impls - - inited uint32 - _ uint32 // padding - - // ---- cache line - - RPCOptions - - // TimeNotBuiltin configures whether time.Time should be treated as a builtin type. - // - // All Handlers should know how to encode/decode time.Time as part of the core - // format specification, or as a standard extension defined by the format. - // - // However, users can elect to handle time.Time as a custom extension, or via the - // standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface. - // To elect this behavior, users can set TimeNotBuiltin=true. - // Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior - // (for Cbor and Msgpack), where time.Time was not a builtin supported type. - TimeNotBuiltin bool - - // ExplicitRelease configures whether Release() is implicitly called after an encode or - // decode call. - // - // If you will hold onto an Encoder or Decoder for re-use, by calling Reset(...) - // on it or calling (Must)Encode repeatedly into a given []byte or io.Writer, - // then you do not want it to be implicitly closed after each Encode/Decode call. - // Doing so will unnecessarily return resources to the shared pool, only for you to - // grab them right after again to do another Encode/Decode call. - // - // Instead, you configure ExplicitRelease=true, and you explicitly call Release() when - // you are truly done. - // - // As an alternative, you can explicitly set a finalizer - so its resources - // are returned to the shared pool before it is garbage-collected. Do it as below: - // runtime.SetFinalizer(e, (*Encoder).Release) - // runtime.SetFinalizer(d, (*Decoder).Release) - ExplicitRelease bool - - be bool // is handle a binary encoding? - js bool // is handle javascript handler? - n byte // first letter of handle name - _ uint16 // padding - - // ---- cache line - + EncodeOptions DecodeOptions +} - // ---- cache line - - EncodeOptions +// Handle is the interface for a specific encoding format. +// +// Typically, a Handle is pre-configured before first time use, +// and not modified while in use. Such a pre-configured Handle +// is safe for concurrent access. +type Handle interface { + writeExt() bool + getBasicHandle() *BasicHandle + newEncDriver(w encWriter) encDriver + newDecDriver(r decReader) decDriver +} - // noBuiltInTypeChecker +// RawExt represents raw unprocessed extension data. +type RawExt struct { + Tag byte + Data []byte +} - rtidFns atomicRtidFnSlice - mu sync.Mutex - // r []uintptr // rtids mapped to s above +type extTypeTagFn struct { + rtid uintptr + rt reflect.Type + tag byte + encFn func(reflect.Value) ([]byte, error) + decFn func(reflect.Value, []byte) error } -// basicHandle returns an initialized BasicHandle from the Handle. -func basicHandle(hh Handle) (x *BasicHandle) { - x = hh.getBasicHandle() - // ** We need to simulate once.Do, to ensure no data race within the block. - // ** Consequently, below would not work. - // if atomic.CompareAndSwapUint32(&x.inited, 0, 1) { - // x.be = hh.isBinary() - // _, x.js = hh.(*JsonHandle) - // x.n = hh.Name()[0] +type extHandle []*extTypeTagFn + +// AddExt registers an encode and decode function for a reflect.Type. +// Note that the type must be a named type, and specifically not +// a pointer or Interface. An error is returned if that is not honored. +// +// To Deregister an ext, call AddExt with 0 tag, nil encfn and nil decfn. +func (o *extHandle) AddExt( + rt reflect.Type, + tag byte, + encfn func(reflect.Value) ([]byte, error), + decfn func(reflect.Value, []byte) error, +) (err error) { + // o is a pointer, because we may need to initialize it + if rt.PkgPath() == "" || rt.Kind() == reflect.Interface { + err = fmt.Errorf("codec.Handle.AddExt: Takes named type, especially not a pointer or interface: %T", + reflect.Zero(rt).Interface()) + return + } + + // o cannot be nil, since it is always embedded in a Handle. + // if nil, let it panic. + // if o == nil { + // err = errors.New("codec.Handle.AddExt: extHandle cannot be a nil pointer.") + // return // } - // simulate once.Do using our own stored flag and mutex as a CompareAndSwap - // is not sufficient, since a race condition can occur within init(Handle) function. - // init is made noinline, so that this function can be inlined by its caller. - if atomic.LoadUint32(&x.inited) == 0 { - x.init(hh) + rtid := reflect.ValueOf(rt).Pointer() + for _, v := range *o { + if v.rtid == rtid { + v.tag, v.encFn, v.decFn = tag, encfn, decfn + return + } } + + *o = append(*o, &extTypeTagFn{rtid, rt, tag, encfn, decfn}) return } -//go:noinline -func (x *BasicHandle) init(hh Handle) { - // make it uninlineable, as it is called at most once - x.mu.Lock() - if x.inited == 0 { - x.be = hh.isBinary() - _, x.js = hh.(*JsonHandle) - x.n = hh.Name()[0] - atomic.StoreUint32(&x.inited, 1) +func (o extHandle) getExt(rtid uintptr) *extTypeTagFn { + for _, v := range o { + if v.rtid == rtid { + return v + } } - x.mu.Unlock() + return nil } -func (x *BasicHandle) getBasicHandle() *BasicHandle { - return x +func (o extHandle) getExtForTag(tag byte) *extTypeTagFn { + for _, v := range o { + if v.tag == tag { + return v + } + } + return nil } -func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) { - if x.TypeInfos == nil { - return defTypeInfos.get(rtid, rt) +func (o extHandle) getDecodeExtForTag(tag byte) ( + rv reflect.Value, fn func(reflect.Value, []byte) error) { + if x := o.getExtForTag(tag); x != nil { + // ext is only registered for base + rv = reflect.New(x.rt).Elem() + fn = x.decFn } - return x.TypeInfos.get(rtid, rt) + return } -func findFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) { - // binary search. adapted from sort/search.go. - // Note: we use goto (instead of for loop) so this can be inlined. - - // h, i, j := 0, 0, len(s) - var h uint // var h, i uint - var j = uint(len(s)) -LOOP: - if i < j { - h = i + (j-i)/2 - if s[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - goto LOOP +func (o extHandle) getDecodeExt(rtid uintptr) (tag byte, fn func(reflect.Value, []byte) error) { + if x := o.getExt(rtid); x != nil { + tag = x.tag + fn = x.decFn } - if i < uint(len(s)) && s[i].rtid == rtid { - fn = s[i].fn + return +} + +func (o extHandle) getEncodeExt(rtid uintptr) (tag byte, fn func(reflect.Value) ([]byte, error)) { + if x := o.getExt(rtid); x != nil { + tag = x.tag + fn = x.encFn } return } -func (x *BasicHandle) fn(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) { - rtid := rt2id(rt) - sp := x.rtidFns.load() - if sp != nil { - if _, fn = findFn(sp, rtid); fn != nil { - // xdebugf("<<<< %c: found fn for %v in rtidfns of size: %v", c.n, rt, len(sp)) - return - } +type structFieldInfo struct { + encName string // encode name + + // only one of 'i' or 'is' can be set. If 'i' is -1, then 'is' has been set. + + is []int // (recursive/embedded) field index in struct + i int16 // field index in struct + omitEmpty bool + toArray bool // if field is _struct, is the toArray set? + + // tag string // tag + // name string // field name + // encNameBs []byte // encoded name as byte stream + // ikind int // kind of the field as an int i.e. int(reflect.Kind) +} + +func parseStructFieldInfo(fname string, stag string) *structFieldInfo { + if fname == "" { + panic("parseStructFieldInfo: No Field Name") } - c := x - // xdebugf("#### for %c: load fn for %v in rtidfns of size: %v", c.n, rt, len(sp)) - fn = new(codecFn) - fi := &(fn.i) - ti := c.getTypeInfo(rtid, rt) - fi.ti = ti - - rk := reflect.Kind(ti.kind) - - if checkCodecSelfer && (ti.cs || ti.csp) { - fn.fe = (*Encoder).selferMarshal - fn.fd = (*Decoder).selferUnmarshal - fi.addrF = true - fi.addrD = ti.csp - fi.addrE = ti.csp - } else if rtid == timeTypId && !c.TimeNotBuiltin { - fn.fe = (*Encoder).kTime - fn.fd = (*Decoder).kTime - } else if rtid == rawTypId { - fn.fe = (*Encoder).raw - fn.fd = (*Decoder).raw - } else if rtid == rawExtTypId { - fn.fe = (*Encoder).rawExt - fn.fd = (*Decoder).rawExt - fi.addrF = true - fi.addrD = true - fi.addrE = true - } else if xfFn := c.getExt(rtid); xfFn != nil { - fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext - fn.fe = (*Encoder).ext - fn.fd = (*Decoder).ext - fi.addrF = true - fi.addrD = true - if rk == reflect.Struct || rk == reflect.Array { - fi.addrE = true - } - } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) { - fn.fe = (*Encoder).binaryMarshal - fn.fd = (*Decoder).binaryUnmarshal - fi.addrF = true - fi.addrD = ti.bup - fi.addrE = ti.bmp - } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) { - //If JSON, we should check JSONMarshal before textMarshal - fn.fe = (*Encoder).jsonMarshal - fn.fd = (*Decoder).jsonUnmarshal - fi.addrF = true - fi.addrD = ti.jup - fi.addrE = ti.jmp - } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) { - fn.fe = (*Encoder).textMarshal - fn.fd = (*Decoder).textUnmarshal - fi.addrF = true - fi.addrD = ti.tup - fi.addrE = ti.tmp - } else { - if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { - if ti.pkgpath == "" { // un-named slice or map - if idx := fastpathAV.index(rtid); idx != -1 { - fn.fe = fastpathAV[idx].encfn - fn.fd = fastpathAV[idx].decfn - fi.addrD = true - fi.addrF = false + si := structFieldInfo{ + // name: fname, + encName: fname, + // tag: stag, + } + + if stag != "" { + for i, s := range strings.Split(stag, ",") { + if i == 0 { + if s != "" { + si.encName = s } } else { - // use mapping for underlying type if there - var rtu reflect.Type - if rk == reflect.Map { - rtu = reflect.MapOf(ti.key, ti.elem) - } else { - rtu = reflect.SliceOf(ti.elem) - } - rtuid := rt2id(rtu) - if idx := fastpathAV.index(rtuid); idx != -1 { - xfnf := fastpathAV[idx].encfn - xrt := fastpathAV[idx].rt - fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) { - xfnf(e, xf, xrv.Convert(xrt)) - } - fi.addrD = true - fi.addrF = false // meaning it can be an address(ptr) or a value - xfnf2 := fastpathAV[idx].decfn - fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) { - if xrv.Kind() == reflect.Ptr { - xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt))) - } else { - xfnf2(d, xf, xrv.Convert(xrt)) - } - } - } - } - } - if fn.fe == nil && fn.fd == nil { - switch rk { - case reflect.Bool: - fn.fe = (*Encoder).kBool - fn.fd = (*Decoder).kBool - case reflect.String: - fn.fe = (*Encoder).kString - fn.fd = (*Decoder).kString - case reflect.Int: - fn.fd = (*Decoder).kInt - fn.fe = (*Encoder).kInt - case reflect.Int8: - fn.fe = (*Encoder).kInt8 - fn.fd = (*Decoder).kInt8 - case reflect.Int16: - fn.fe = (*Encoder).kInt16 - fn.fd = (*Decoder).kInt16 - case reflect.Int32: - fn.fe = (*Encoder).kInt32 - fn.fd = (*Decoder).kInt32 - case reflect.Int64: - fn.fe = (*Encoder).kInt64 - fn.fd = (*Decoder).kInt64 - case reflect.Uint: - fn.fd = (*Decoder).kUint - fn.fe = (*Encoder).kUint - case reflect.Uint8: - fn.fe = (*Encoder).kUint8 - fn.fd = (*Decoder).kUint8 - case reflect.Uint16: - fn.fe = (*Encoder).kUint16 - fn.fd = (*Decoder).kUint16 - case reflect.Uint32: - fn.fe = (*Encoder).kUint32 - fn.fd = (*Decoder).kUint32 - case reflect.Uint64: - fn.fe = (*Encoder).kUint64 - fn.fd = (*Decoder).kUint64 - case reflect.Uintptr: - fn.fe = (*Encoder).kUintptr - fn.fd = (*Decoder).kUintptr - case reflect.Float32: - fn.fe = (*Encoder).kFloat32 - fn.fd = (*Decoder).kFloat32 - case reflect.Float64: - fn.fe = (*Encoder).kFloat64 - fn.fd = (*Decoder).kFloat64 - case reflect.Invalid: - fn.fe = (*Encoder).kInvalid - fn.fd = (*Decoder).kErr - case reflect.Chan: - fi.seq = seqTypeChan - fn.fe = (*Encoder).kSlice - fn.fd = (*Decoder).kSlice - case reflect.Slice: - fi.seq = seqTypeSlice - fn.fe = (*Encoder).kSlice - fn.fd = (*Decoder).kSlice - case reflect.Array: - fi.seq = seqTypeArray - fn.fe = (*Encoder).kSlice - fi.addrF = false - fi.addrD = false - rt2 := reflect.SliceOf(ti.elem) - fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) { - d.h.fn(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len())) - } - // fn.fd = (*Decoder).kArray - case reflect.Struct: - if ti.anyOmitEmpty || ti.mf || ti.mfp { - fn.fe = (*Encoder).kStruct - } else { - fn.fe = (*Encoder).kStructNoOmitempty + switch s { + case "omitempty": + si.omitEmpty = true + case "toarray": + si.toArray = true } - fn.fd = (*Decoder).kStruct - case reflect.Map: - fn.fe = (*Encoder).kMap - fn.fd = (*Decoder).kMap - case reflect.Interface: - // encode: reflect.Interface are handled already by preEncodeValue - fn.fd = (*Decoder).kInterface - fn.fe = (*Encoder).kErr - default: - // reflect.Ptr and reflect.Interface are handled already by preEncodeValue - fn.fe = (*Encoder).kErr - fn.fd = (*Decoder).kErr } } } + // si.encNameBs = []byte(si.encName) + return &si +} - c.mu.Lock() - var sp2 []codecRtidFn - sp = c.rtidFns.load() - if sp == nil { - sp2 = []codecRtidFn{{rtid, fn}} - c.rtidFns.store(sp2) - // xdebugf(">>>> adding rt: %v to rtidfns of size: %v", rt, len(sp2)) - // xdebugf(">>>> loading stored rtidfns of size: %v", len(c.rtidFns.load())) - } else { - idx, fn2 := findFn(sp, rtid) - if fn2 == nil { - sp2 = make([]codecRtidFn, len(sp)+1) - copy(sp2, sp[:idx]) - copy(sp2[idx+1:], sp[idx:]) - sp2[idx] = codecRtidFn{rtid, fn} - c.rtidFns.store(sp2) - // xdebugf(">>>> adding rt: %v to rtidfns of size: %v", rt, len(sp2)) +type sfiSortedByEncName []*structFieldInfo - } - } - c.mu.Unlock() - return +func (p sfiSortedByEncName) Len() int { + return len(p) } -// Handle defines a specific encoding format. It also stores any runtime state -// used during an Encoding or Decoding session e.g. stored state about Types, etc. -// -// Once a handle is configured, it can be shared across multiple Encoders and Decoders. -// -// Note that a Handle is NOT safe for concurrent modification. -// Consequently, do not modify it after it is configured if shared among -// multiple Encoders and Decoders in different goroutines. -// -// Consequently, the typical usage model is that a Handle is pre-configured -// before first time use, and not modified while in use. -// Such a pre-configured Handle is safe for concurrent access. -type Handle interface { - Name() string - // return the basic handle. It may not have been inited. - // Prefer to use basicHandle() helper function that ensures it has been inited. - getBasicHandle() *BasicHandle - recreateEncDriver(encDriver) bool - newEncDriver(w *Encoder) encDriver - newDecDriver(r *Decoder) decDriver - isBinary() bool - hasElemSeparators() bool - // IsBuiltinType(rtid uintptr) bool +func (p sfiSortedByEncName) Less(i, j int) bool { + return p[i].encName < p[j].encName } -// Raw represents raw formatted bytes. -// We "blindly" store it during encode and retrieve the raw bytes during decode. -// Note: it is dangerous during encode, so we may gate the behaviour -// behind an Encode flag which must be explicitly set. -type Raw []byte +func (p sfiSortedByEncName) Swap(i, j int) { + p[i], p[j] = p[j], p[i] +} -// RawExt represents raw unprocessed extension data. -// Some codecs will decode extension data as a *RawExt -// if there is no registered extension for the tag. +// typeInfo keeps information about each type referenced in the encode/decode sequence. // -// Only one of Data or Value is nil. -// If Data is nil, then the content of the RawExt is in the Value. -type RawExt struct { - Tag uint64 - // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value. - // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types - Data []byte - // Value represents the extension, if Data is nil. - // Value is used by codecs (e.g. cbor, json) which leverage the format to do - // custom serialization of the types. - Value interface{} -} +// During an encode/decode sequence, we work as below: +// - If base is a built in type, en/decode base value +// - If base is registered as an extension, en/decode base value +// - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method +// - Else decode appropriately based on the reflect.Kind +type typeInfo struct { + sfi []*structFieldInfo // sorted. Used when enc/dec struct to map. + sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array. -// BytesExt handles custom (de)serialization of types to/from []byte. -// It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types. -type BytesExt interface { - // WriteExt converts a value to a []byte. - // - // Note: v is a pointer iff the registered extension type is a struct or array kind. - WriteExt(v interface{}) []byte + rt reflect.Type + rtid uintptr - // ReadExt updates a value from a []byte. - // - // Note: dst is always a pointer kind to the registered extension type. - ReadExt(dst interface{}, src []byte) + // baseId gives pointer to the base reflect.Type, after deferencing + // the pointers. E.g. base type of ***time.Time is time.Time. + base reflect.Type + baseId uintptr + baseIndir int8 // number of indirections to get to base + + mbs bool // base type (T or *T) is a MapBySlice + + m bool // base type (T or *T) is a binaryMarshaler + unm bool // base type (T or *T) is a binaryUnmarshaler + mIndir int8 // number of indirections to get to binaryMarshaler type + unmIndir int8 // number of indirections to get to binaryUnmarshaler type + toArray bool // whether this (struct) type should be encoded as an array +} + +func (ti *typeInfo) indexForEncName(name string) int { + //tisfi := ti.sfi + const binarySearchThreshold = 16 + if sfilen := len(ti.sfi); sfilen < binarySearchThreshold { + // linear search. faster than binary search in my testing up to 16-field structs. + for i, si := range ti.sfi { + if si.encName == name { + return i + } + } + } else { + // binary search. adapted from sort/search.go. + h, i, j := 0, 0, sfilen + for i < j { + h = i + (j-i)/2 + if ti.sfi[h].encName < name { + i = h + 1 + } else { + j = h + } + } + if i < sfilen && ti.sfi[i].encName == name { + return i + } + } + return -1 } -// InterfaceExt handles custom (de)serialization of types to/from another interface{} value. -// The Encoder or Decoder will then handle the further (de)serialization of that known type. -// -// It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types. -type InterfaceExt interface { - // ConvertExt converts a value into a simpler interface for easy encoding - // e.g. convert time.Time to int64. - // - // Note: v is a pointer iff the registered extension type is a struct or array kind. - ConvertExt(v interface{}) interface{} +func getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) { + var ok bool + cachedTypeInfoMutex.RLock() + pti, ok = cachedTypeInfo[rtid] + cachedTypeInfoMutex.RUnlock() + if ok { + return + } - // UpdateExt updates a value from a simpler interface for easy decoding - // e.g. convert int64 to time.Time. - // - // Note: dst is always a pointer kind to the registered extension type. - UpdateExt(dst interface{}, src interface{}) -} + cachedTypeInfoMutex.Lock() + defer cachedTypeInfoMutex.Unlock() + if pti, ok = cachedTypeInfo[rtid]; ok { + return + } -// Ext handles custom (de)serialization of custom types / extensions. -type Ext interface { - BytesExt - InterfaceExt -} + ti := typeInfo{rt: rt, rtid: rtid} + pti = &ti -// addExtWrapper is a wrapper implementation to support former AddExt exported method. -type addExtWrapper struct { - encFn func(reflect.Value) ([]byte, error) - decFn func(reflect.Value, []byte) error -} + var indir int8 + if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok { + ti.m, ti.mIndir = true, indir + } + if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok { + ti.unm, ti.unmIndir = true, indir + } + if ok, _ = implementsIntf(rt, mapBySliceTyp); ok { + ti.mbs = true + } -func (x addExtWrapper) WriteExt(v interface{}) []byte { - bs, err := x.encFn(reflect.ValueOf(v)) - if err != nil { - panic(err) + pt := rt + var ptIndir int8 + // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { } + for pt.Kind() == reflect.Ptr { + pt = pt.Elem() + ptIndir++ + } + if ptIndir == 0 { + ti.base = rt + ti.baseId = rtid + } else { + ti.base = pt + ti.baseId = reflect.ValueOf(pt).Pointer() + ti.baseIndir = ptIndir } - return bs + + if rt.Kind() == reflect.Struct { + var siInfo *structFieldInfo + if f, ok := rt.FieldByName(structInfoFieldName); ok { + siInfo = parseStructFieldInfo(structInfoFieldName, f.Tag.Get(structTagName)) + ti.toArray = siInfo.toArray + } + sfip := make([]*structFieldInfo, 0, rt.NumField()) + rgetTypeInfo(rt, nil, make(map[string]bool), &sfip, siInfo) + + // // try to put all si close together + // const tryToPutAllStructFieldInfoTogether = true + // if tryToPutAllStructFieldInfoTogether { + // sfip2 := make([]structFieldInfo, len(sfip)) + // for i, si := range sfip { + // sfip2[i] = *si + // } + // for i := range sfip { + // sfip[i] = &sfip2[i] + // } + // } + + ti.sfip = make([]*structFieldInfo, len(sfip)) + ti.sfi = make([]*structFieldInfo, len(sfip)) + copy(ti.sfip, sfip) + sort.Sort(sfiSortedByEncName(sfip)) + copy(ti.sfi, sfip) + } + // sfi = sfip + cachedTypeInfo[rtid] = pti + return } -func (x addExtWrapper) ReadExt(v interface{}, bs []byte) { - if err := x.decFn(reflect.ValueOf(v), bs); err != nil { - panic(err) +func rgetTypeInfo(rt reflect.Type, indexstack []int, fnameToHastag map[string]bool, + sfi *[]*structFieldInfo, siInfo *structFieldInfo, +) { + // for rt.Kind() == reflect.Ptr { + // // indexstack = append(indexstack, 0) + // rt = rt.Elem() + // } + for j := 0; j < rt.NumField(); j++ { + f := rt.Field(j) + stag := f.Tag.Get(structTagName) + if stag == "-" { + continue + } + if r1, _ := utf8.DecodeRuneInString(f.Name); r1 == utf8.RuneError || !unicode.IsUpper(r1) { + continue + } + // if anonymous and there is no struct tag and its a struct (or pointer to struct), inline it. + if f.Anonymous && stag == "" { + ft := f.Type + for ft.Kind() == reflect.Ptr { + ft = ft.Elem() + } + if ft.Kind() == reflect.Struct { + indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) + rgetTypeInfo(ft, indexstack2, fnameToHastag, sfi, siInfo) + continue + } + } + // do not let fields with same name in embedded structs override field at higher level. + // this must be done after anonymous check, to allow anonymous field + // still include their child fields + if _, ok := fnameToHastag[f.Name]; ok { + continue + } + si := parseStructFieldInfo(f.Name, stag) + // si.ikind = int(f.Type.Kind()) + if len(indexstack) == 0 { + si.i = int16(j) + } else { + si.i = -1 + si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) + } + + if siInfo != nil { + if siInfo.omitEmpty { + si.omitEmpty = true + } + } + *sfi = append(*sfi, si) + fnameToHastag[f.Name] = stag != "" } } -func (x addExtWrapper) ConvertExt(v interface{}) interface{} { - return x.WriteExt(v) +func panicToErr(err *error) { + if recoverPanicToErr { + if x := recover(); x != nil { + //debug.PrintStack() + panicValToErr(x, err) + } + } } -func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) { - x.ReadExt(dest, v.([]byte)) +func doPanic(tag string, format string, params ...interface{}) { + params2 := make([]interface{}, len(params)+1) + params2[0] = tag + copy(params2[1:], params) + panic(fmt.Errorf("%s: "+format, params2...)) } -type extWrapper struct { - BytesExt - InterfaceExt +func checkOverflowFloat32(f float64, doCheck bool) { + if !doCheck { + return + } + // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat() + f2 := f + if f2 < 0 { + f2 = -f + } + if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 { + decErr("Overflow float32 value: %v", f2) + } } -type bytesExtFailer struct{} - -func (bytesExtFailer) WriteExt(v interface{}) []byte { - panicv.errorstr("BytesExt.WriteExt is not supported") - return nil -} -func (bytesExtFailer) ReadExt(v interface{}, bs []byte) { - panicv.errorstr("BytesExt.ReadExt is not supported") -} - -type interfaceExtFailer struct{} - -func (interfaceExtFailer) ConvertExt(v interface{}) interface{} { - panicv.errorstr("InterfaceExt.ConvertExt is not supported") - return nil -} -func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) { - panicv.errorstr("InterfaceExt.UpdateExt is not supported") -} - -type binaryEncodingType struct{} - -func (binaryEncodingType) isBinary() bool { return true } - -type textEncodingType struct{} - -func (textEncodingType) isBinary() bool { return false } - -// noBuiltInTypes is embedded into many types which do not support builtins -// e.g. msgpack, simple, cbor. - -// type noBuiltInTypeChecker struct{} -// func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false } -// type noBuiltInTypes struct{ noBuiltInTypeChecker } - -type noBuiltInTypes struct{} - -func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {} -func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {} - -// type noStreamingCodec struct{} -// func (noStreamingCodec) CheckBreak() bool { return false } -// func (noStreamingCodec) hasElemSeparators() bool { return false } - -type noElemSeparators struct{} - -func (noElemSeparators) hasElemSeparators() (v bool) { return } -func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return } - -// bigenHelper. -// Users must already slice the x completely, because we will not reslice. -type bigenHelper struct { - x []byte // must be correctly sliced to appropriate len. slicing is a cost. - w *encWriterSwitch -} - -func (z bigenHelper) writeUint16(v uint16) { - bigen.PutUint16(z.x, v) - z.w.writeb(z.x) -} - -func (z bigenHelper) writeUint32(v uint32) { - bigen.PutUint32(z.x, v) - z.w.writeb(z.x) -} - -func (z bigenHelper) writeUint64(v uint64) { - bigen.PutUint64(z.x, v) - z.w.writeb(z.x) -} - -type extTypeTagFn struct { - rtid uintptr - rtidptr uintptr - rt reflect.Type - tag uint64 - ext Ext - _ [1]uint64 // padding -} - -type extHandle []extTypeTagFn - -// AddExt registes an encode and decode function for a reflect.Type. -// To deregister an Ext, call AddExt with nil encfn and/or nil decfn. -// -// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead. -func (o *extHandle) AddExt(rt reflect.Type, tag byte, - encfn func(reflect.Value) ([]byte, error), - decfn func(reflect.Value, []byte) error) (err error) { - if encfn == nil || decfn == nil { - return o.SetExt(rt, uint64(tag), nil) - } - return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn}) -} - -// SetExt will set the extension for a tag and reflect.Type. -// Note that the type must be a named type, and specifically not a pointer or Interface. -// An error is returned if that is not honored. -// To Deregister an ext, call SetExt with nil Ext. -// -// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead. -func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) { - // o is a pointer, because we may need to initialize it - rk := rt.Kind() - for rk == reflect.Ptr { - rt = rt.Elem() - rk = rt.Kind() - } - - if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr { - return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt) - } - - rtid := rt2id(rt) - switch rtid { - case timeTypId, rawTypId, rawExtTypId: - // all natively supported type, so cannot have an extension - return // TODO: should we silently ignore, or return an error??? - } - // if o == nil { - // return errors.New("codec.Handle.SetExt: extHandle not initialized") - // } - o2 := *o - // if o2 == nil { - // return errors.New("codec.Handle.SetExt: extHandle not initialized") - // } - for i := range o2 { - v := &o2[i] - if v.rtid == rtid { - v.tag, v.ext = tag, ext - return - } - } - rtidptr := rt2id(reflect.PtrTo(rt)) - *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext, [1]uint64{}}) - return -} - -func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) { - for i := range o { - v = &o[i] - if v.rtid == rtid || v.rtidptr == rtid { - return - } - } - return nil -} - -func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) { - for i := range o { - v = &o[i] - if v.tag == tag { - return - } - } - return nil -} - -type intf2impl struct { - rtid uintptr // for intf - impl reflect.Type - // _ [1]uint64 // padding // not-needed, as *intf2impl is never returned. -} - -type intf2impls []intf2impl - -// Intf2Impl maps an interface to an implementing type. -// This allows us support infering the concrete type -// and populating it when passed an interface. -// e.g. var v io.Reader can be decoded as a bytes.Buffer, etc. -// -// Passing a nil impl will clear the mapping. -func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) { - if impl != nil && !impl.Implements(intf) { - return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf) - } - rtid := rt2id(intf) - o2 := *o - for i := range o2 { - v := &o2[i] - if v.rtid == rtid { - v.impl = impl - return - } - } - *o = append(o2, intf2impl{rtid, impl}) - return -} - -func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) { - for i := range o { - v := &o[i] - if v.rtid == rtid { - if v.impl == nil { - return - } - if v.impl.Kind() == reflect.Ptr { - return reflect.New(v.impl.Elem()) - } - return reflect.New(v.impl).Elem() - } - } - return -} - -type structFieldInfoFlag uint8 - -const ( - _ structFieldInfoFlag = 1 << iota - structFieldInfoFlagReady - structFieldInfoFlagOmitEmpty -) - -func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) { - *x = *x | f -} - -func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) { - *x = *x &^ f -} - -func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool { - return x&f != 0 -} - -func (x structFieldInfoFlag) omitEmpty() bool { - return x.flagGet(structFieldInfoFlagOmitEmpty) -} - -func (x structFieldInfoFlag) ready() bool { - return x.flagGet(structFieldInfoFlagReady) -} - -type structFieldInfo struct { - encName string // encode name - fieldName string // field name - - is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct - nis uint8 // num levels of embedding. if 1, then it's not embedded. - - encNameAsciiAlphaNum bool // the encName only contains ascii alphabet and numbers - structFieldInfoFlag - _ [1]byte // padding -} - -func (si *structFieldInfo) setToZeroValue(v reflect.Value) { - if v, valid := si.field(v, false); valid { - v.Set(reflect.Zero(v.Type())) - } -} - -// rv returns the field of the struct. -// If anonymous, it returns an Invalid -func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) { - // replicate FieldByIndex - for i, x := range si.is { - if uint8(i) == si.nis { - break - } - if v, valid = baseStructRv(v, update); !valid { - return - } - v = v.Field(int(x)) - } - - return v, true -} - -// func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value { -// v, _ = si.field(v, update) -// return v -// } - -func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) { - keytype = valueTypeString // default - if stag == "" { - return - } - for i, s := range strings.Split(stag, ",") { - if i == 0 { - } else { - switch s { - case "omitempty": - omitEmpty = true - case "toarray": - toArray = true - case "int": - keytype = valueTypeInt - case "uint": - keytype = valueTypeUint - case "float": - keytype = valueTypeFloat - // case "bool": - // keytype = valueTypeBool - case "string": - keytype = valueTypeString - } - } - } - return -} - -func (si *structFieldInfo) parseTag(stag string) { - // if fname == "" { - // panic(errNoFieldNameToStructFieldInfo) - // } - - if stag == "" { - return - } - for i, s := range strings.Split(stag, ",") { - if i == 0 { - if s != "" { - si.encName = s - } - } else { - switch s { - case "omitempty": - si.flagSet(structFieldInfoFlagOmitEmpty) - // si.omitEmpty = true - // case "toarray": - // si.toArray = true - } - } - } -} - -type sfiSortedByEncName []*structFieldInfo - -func (p sfiSortedByEncName) Len() int { return len(p) } -func (p sfiSortedByEncName) Less(i, j int) bool { return p[uint(i)].encName < p[uint(j)].encName } -func (p sfiSortedByEncName) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -const structFieldNodeNumToCache = 4 - -type structFieldNodeCache struct { - rv [structFieldNodeNumToCache]reflect.Value - idx [structFieldNodeNumToCache]uint32 - num uint8 -} - -func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) { - for i, k := range &x.idx { - if uint8(i) == x.num { - return // break - } - if key == k { - return x.rv[i], true - } - } - return -} - -func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) { - if x.num < structFieldNodeNumToCache { - x.rv[x.num] = fv - x.idx[x.num] = key - x.num++ - return - } -} - -type structFieldNode struct { - v reflect.Value - cache2 structFieldNodeCache - cache3 structFieldNodeCache - update bool -} - -func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) { - // return si.fieldval(x.v, x.update) - // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding - // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc. - var valid bool - switch si.nis { - case 1: - fv = x.v.Field(int(si.is[0])) - case 2: - if fv, valid = x.cache2.get(uint32(si.is[0])); valid { - fv = fv.Field(int(si.is[1])) - return - } - fv = x.v.Field(int(si.is[0])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - x.cache2.tryAdd(fv, uint32(si.is[0])) - fv = fv.Field(int(si.is[1])) - case 3: - var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1]) - if fv, valid = x.cache3.get(key); valid { - fv = fv.Field(int(si.is[2])) - return - } - fv = x.v.Field(int(si.is[0])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - fv = fv.Field(int(si.is[1])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - x.cache3.tryAdd(fv, key) - fv = fv.Field(int(si.is[2])) - default: - fv, _ = si.field(x.v, x.update) - } - return -} - -func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - if !update { - return - } - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - return v, true -} - -type typeInfoFlag uint8 - -const ( - typeInfoFlagComparable = 1 << iota - typeInfoFlagIsZeroer - typeInfoFlagIsZeroerPtr -) - -// typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence. -// -// During an encode/decode sequence, we work as below: -// - If base is a built in type, en/decode base value -// - If base is registered as an extension, en/decode base value -// - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method -// - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method -// - Else decode appropriately based on the reflect.Kind -type typeInfo struct { - rt reflect.Type - elem reflect.Type - pkgpath string - - rtid uintptr - // rv0 reflect.Value // saved zero value, used if immutableKind - - numMeth uint16 // number of methods - kind uint8 - chandir uint8 - - anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty" - toArray bool // whether this (struct) type should be encoded as an array - keyType valueType // if struct, how is the field name stored in a stream? default is string - mbs bool // base type (T or *T) is a MapBySlice - - // ---- cpu cache line boundary? - sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map. - sfiSrc []*structFieldInfo // unsorted. Used when enc/dec struct to array. - - key reflect.Type - - // ---- cpu cache line boundary? - // sfis []structFieldInfo // all sfi, in src order, as created. - sfiNamesSort []byte // all names, with indexes into the sfiSort - - // format of marshal type fields below: [btj][mu]p? OR csp? - - bm bool // T is a binaryMarshaler - bmp bool // *T is a binaryMarshaler - bu bool // T is a binaryUnmarshaler - bup bool // *T is a binaryUnmarshaler - tm bool // T is a textMarshaler - tmp bool // *T is a textMarshaler - tu bool // T is a textUnmarshaler - tup bool // *T is a textUnmarshaler - - jm bool // T is a jsonMarshaler - jmp bool // *T is a jsonMarshaler - ju bool // T is a jsonUnmarshaler - jup bool // *T is a jsonUnmarshaler - cs bool // T is a Selfer - csp bool // *T is a Selfer - mf bool // T is a MissingFielder - mfp bool // *T is a MissingFielder - - // other flags, with individual bits representing if set. - flags typeInfoFlag - infoFieldOmitempty bool - - _ [6]byte // padding - _ [2]uint64 // padding -} - -func (ti *typeInfo) isFlag(f typeInfoFlag) bool { - return ti.flags&f != 0 -} - -func (ti *typeInfo) indexForEncName(name []byte) (index int16) { - var sn []byte - if len(name)+2 <= 32 { - var buf [32]byte // should not escape to heap - sn = buf[:len(name)+2] - } else { - sn = make([]byte, len(name)+2) - } - copy(sn[1:], name) - sn[0], sn[len(sn)-1] = tiSep2(name), 0xff - j := bytes.Index(ti.sfiNamesSort, sn) - if j < 0 { - return -1 - } - index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8) - return -} - -type rtid2ti struct { - rtid uintptr - ti *typeInfo -} - -// TypeInfos caches typeInfo for each type on first inspection. -// -// It is configured with a set of tag keys, which are used to get -// configuration for the type. -type TypeInfos struct { - // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected - infos atomicTypeInfoSlice - mu sync.Mutex - tags []string - _ [2]uint64 // padding -} - -// NewTypeInfos creates a TypeInfos given a set of struct tags keys. -// -// This allows users customize the struct tag keys which contain configuration -// of their types. -func NewTypeInfos(tags []string) *TypeInfos { - return &TypeInfos{tags: tags} -} - -func (x *TypeInfos) structTag(t reflect.StructTag) (s string) { - // check for tags: codec, json, in that order. - // this allows seamless support for many configured structs. - for _, x := range x.tags { - s = t.Get(x) - if s != "" { - return s - } - } - return -} - -func findTypeInfo(s []rtid2ti, rtid uintptr) (i uint, ti *typeInfo) { - // binary search. adapted from sort/search.go. - // Note: we use goto (instead of for loop) so this can be inlined. - - // if sp == nil { - // return -1, nil - // } - // s := *sp - - // h, i, j := 0, 0, len(s) - var h uint // var h, i uint - var j = uint(len(s)) -LOOP: - if i < j { - h = i + (j-i)/2 - if s[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - goto LOOP - } - if i < uint(len(s)) && s[i].rtid == rtid { - ti = s[i].ti - } - return -} - -func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) { - sp := x.infos.load() - if sp != nil { - _, pti = findTypeInfo(sp, rtid) - if pti != nil { - return - } - } - - rk := rt.Kind() - - if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) { - panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt) - } - - // do not hold lock while computing this. - // it may lead to duplication, but that's ok. - ti := typeInfo{ - rt: rt, - rtid: rtid, - kind: uint8(rk), - pkgpath: rt.PkgPath(), - keyType: valueTypeString, // default it - so it's never 0 - } - // ti.rv0 = reflect.Zero(rt) - - // ti.comparable = rt.Comparable() - ti.numMeth = uint16(rt.NumMethod()) - - ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp) - ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp) - ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp) - ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp) - ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp) - ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp) - ti.cs, ti.csp = implIntf(rt, selferTyp) - ti.mf, ti.mfp = implIntf(rt, missingFielderTyp) - - b1, b2 := implIntf(rt, iszeroTyp) - if b1 { - ti.flags |= typeInfoFlagIsZeroer - } - if b2 { - ti.flags |= typeInfoFlagIsZeroerPtr - } - if rt.Comparable() { - ti.flags |= typeInfoFlagComparable - } - - switch rk { - case reflect.Struct: - var omitEmpty bool - if f, ok := rt.FieldByName(structInfoFieldName); ok { - ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag)) - ti.infoFieldOmitempty = omitEmpty - } else { - ti.keyType = valueTypeString - } - pp, pi := &pool.tiload, pool.tiload.Get() // pool.tiLoad() - pv := pi.(*typeInfoLoadArray) - pv.etypes[0] = ti.rtid - // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]} - vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]} - x.rget(rt, rtid, omitEmpty, nil, &vv) - // ti.sfis = vv.sfis - ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv) - pp.Put(pi) - case reflect.Map: - ti.elem = rt.Elem() - ti.key = rt.Key() - case reflect.Slice: - ti.mbs, _ = implIntf(rt, mapBySliceTyp) - ti.elem = rt.Elem() - case reflect.Chan: - ti.elem = rt.Elem() - ti.chandir = uint8(rt.ChanDir()) - case reflect.Array, reflect.Ptr: - ti.elem = rt.Elem() - } - // sfi = sfiSrc - - x.mu.Lock() - sp = x.infos.load() - var sp2 []rtid2ti - if sp == nil { - pti = &ti - sp2 = []rtid2ti{{rtid, pti}} - x.infos.store(sp2) - } else { - var idx uint - idx, pti = findTypeInfo(sp, rtid) - if pti == nil { - pti = &ti - sp2 = make([]rtid2ti, len(sp)+1) - copy(sp2, sp[:idx]) - copy(sp2[idx+1:], sp[idx:]) - sp2[idx] = rtid2ti{rtid, pti} - x.infos.store(sp2) - } - } - x.mu.Unlock() - return -} - -func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool, - indexstack []uint16, pv *typeInfoLoad) { - // Read up fields and store how to access the value. - // - // It uses go's rules for message selectors, - // which say that the field with the shallowest depth is selected. - // - // Note: we consciously use slices, not a map, to simulate a set. - // Typically, types have < 16 fields, - // and iteration using equals is faster than maps there - flen := rt.NumField() - if flen > (1<<maxLevelsEmbedding - 1) { - panicv.errorf("codec: types with > %v fields are not supported - has %v fields", - (1<<maxLevelsEmbedding - 1), flen) - } - // pv.sfis = make([]structFieldInfo, flen) -LOOP: - for j, jlen := uint16(0), uint16(flen); j < jlen; j++ { - f := rt.Field(int(j)) - fkind := f.Type.Kind() - // skip if a func type, or is unexported, or structTag value == "-" - switch fkind { - case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer: - continue LOOP - } - - isUnexported := f.PkgPath != "" - if isUnexported && !f.Anonymous { - continue - } - stag := x.structTag(f.Tag) - if stag == "-" { - continue - } - var si structFieldInfo - var parsed bool - // if anonymous and no struct tag (or it's blank), - // and a struct (or pointer to struct), inline it. - if f.Anonymous && fkind != reflect.Interface { - // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface - ft := f.Type - isPtr := ft.Kind() == reflect.Ptr - for ft.Kind() == reflect.Ptr { - ft = ft.Elem() - } - isStruct := ft.Kind() == reflect.Struct - - // Ignore embedded fields of unexported non-struct types. - // Also, from go1.10, ignore pointers to unexported struct types - // because unmarshal cannot assign a new struct to an unexported field. - // See https://golang.org/issue/21357 - if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) { - continue - } - doInline := stag == "" - if !doInline { - si.parseTag(stag) - parsed = true - doInline = si.encName == "" - // doInline = si.isZero() - } - if doInline && isStruct { - // if etypes contains this, don't call rget again (as fields are already seen here) - ftid := rt2id(ft) - // We cannot recurse forever, but we need to track other field depths. - // So - we break if we see a type twice (not the first time). - // This should be sufficient to handle an embedded type that refers to its - // owning type, which then refers to its embedded type. - processIt := true - numk := 0 - for _, k := range pv.etypes { - if k == ftid { - numk++ - if numk == rgetMaxRecursion { - processIt = false - break - } - } - } - if processIt { - pv.etypes = append(pv.etypes, ftid) - indexstack2 := make([]uint16, len(indexstack)+1) - copy(indexstack2, indexstack) - indexstack2[len(indexstack)] = j - // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) - x.rget(ft, ftid, omitEmpty, indexstack2, pv) - } - continue - } - } - - // after the anonymous dance: if an unexported field, skip - if isUnexported { - continue - } - - if f.Name == "" { - panic(errNoFieldNameToStructFieldInfo) - } - - // pv.fNames = append(pv.fNames, f.Name) - // if si.encName == "" { - - if !parsed { - si.encName = f.Name - si.parseTag(stag) - parsed = true - } else if si.encName == "" { - si.encName = f.Name - } - si.encNameAsciiAlphaNum = true - for i := len(si.encName) - 1; i >= 0; i-- { // bounds-check elimination - b := si.encName[i] - if (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') { - continue - } - si.encNameAsciiAlphaNum = false - break - } - si.fieldName = f.Name - si.flagSet(structFieldInfoFlagReady) - - // pv.encNames = append(pv.encNames, si.encName) - - // si.ikind = int(f.Type.Kind()) - if len(indexstack) > maxLevelsEmbedding-1 { - panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth", - maxLevelsEmbedding-1, len(indexstack)) - } - si.nis = uint8(len(indexstack)) + 1 - copy(si.is[:], indexstack) - si.is[len(indexstack)] = j - - if omitEmpty { - si.flagSet(structFieldInfoFlagOmitEmpty) - } - pv.sfis = append(pv.sfis, si) - } -} - -func tiSep(name string) uint8 { - // (xn[0]%64) // (between 192-255 - outside ascii BMP) - // return 0xfe - (name[0] & 63) - // return 0xfe - (name[0] & 63) - uint8(len(name)) - // return 0xfe - (name[0] & 63) - uint8(len(name)&63) - // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07)) - return 0xfe - (name[0] & 63) - uint8(len(name)&63) -} - -func tiSep2(name []byte) uint8 { - return 0xfe - (name[0] & 63) - uint8(len(name)&63) -} - -// resolves the struct field info got from a call to rget. -// Returns a trimmed, unsorted and sorted []*structFieldInfo. -func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) ( - y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) { - sa := pv.sfiidx[:0] - sn := pv.b[:] - n := len(x) - - var xn string - var ui uint16 - var sep byte - - for i := range x { - ui = uint16(i) - xn = x[i].encName // fieldName or encName? use encName for now. - if len(xn)+2 > cap(pv.b) { - sn = make([]byte, len(xn)+2) - } else { - sn = sn[:len(xn)+2] - } - // use a custom sep, so that misses are less frequent, - // since the sep (first char in search) is as unique as first char in field name. - sep = tiSep(xn) - sn[0], sn[len(sn)-1] = sep, 0xff - copy(sn[1:], xn) - j := bytes.Index(sa, sn) - if j == -1 { - sa = append(sa, sep) - sa = append(sa, xn...) - sa = append(sa, 0xff, byte(ui>>8), byte(ui)) - } else { - index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8 - // one of them must be reset to nil, - // and the index updated appropriately to the other one - if x[i].nis == x[index].nis { - } else if x[i].nis < x[index].nis { - sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui) - if x[index].ready() { - x[index].flagClr(structFieldInfoFlagReady) - n-- - } - } else { - if x[i].ready() { - x[i].flagClr(structFieldInfoFlagReady) - n-- - } - } - } - - } - var w []structFieldInfo - sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray - if sharingArray { - w = make([]structFieldInfo, n) - } - - // remove all the nils (non-ready) - y = make([]*structFieldInfo, n) - n = 0 - var sslen int - for i := range x { - if !x[i].ready() { - continue - } - if !anyOmitEmpty && x[i].omitEmpty() { - anyOmitEmpty = true - } - if sharingArray { - w[n] = x[i] - y[n] = &w[n] - } else { - y[n] = &x[i] - } - sslen = sslen + len(x[i].encName) + 4 - n++ - } - if n != len(y) { - panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d", - rt, len(y), len(x), n) - } - - z = make([]*structFieldInfo, len(y)) - copy(z, y) - sort.Sort(sfiSortedByEncName(z)) - - sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen - if sharingArray { - ss = make([]byte, 0, sslen) - } else { - ss = sa[:0] // reuse the newly made sa array if necessary - } - for i := range z { - xn = z[i].encName - sep = tiSep(xn) - ui = uint16(i) - ss = append(ss, sep) - ss = append(ss, xn...) - ss = append(ss, 0xff, byte(ui>>8), byte(ui)) - } - return -} - -func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) { - return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp) -} - -// isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty: -// - does it implement IsZero() bool -// - is it comparable, and can i compare directly using == -// - if checkStruct, then walk through the encodable fields -// and check if they are empty or not. -func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - // v is a struct kind - no need to check again. - // We only check isZero on a struct kind, to reduce the amount of times - // that we lookup the rtid and typeInfo for each type as we walk the tree. - - vt := v.Type() - rtid := rt2id(vt) - if tinfos == nil { - tinfos = defTypeInfos - } - ti := tinfos.get(rtid, vt) - if ti.rtid == timeTypId { - return rv2i(v).(time.Time).IsZero() - } - if ti.isFlag(typeInfoFlagIsZeroerPtr) && v.CanAddr() { - return rv2i(v.Addr()).(isZeroer).IsZero() - } - if ti.isFlag(typeInfoFlagIsZeroer) { - return rv2i(v).(isZeroer).IsZero() - } - if ti.isFlag(typeInfoFlagComparable) { - return rv2i(v) == rv2i(reflect.Zero(vt)) - } - if !checkStruct { - return false - } - // We only care about what we can encode/decode, - // so that is what we use to check omitEmpty. - for _, si := range ti.sfiSrc { - sfv, valid := si.field(v, false) - if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) { - return false - } - } - return true -} - -// func roundFloat(x float64) float64 { -// t := math.Trunc(x) -// if math.Abs(x-t) >= 0.5 { -// return t + math.Copysign(1, x) -// } -// return t -// } - -func panicToErr(h errDecorator, err *error) { - // Note: This method MUST be called directly from defer i.e. defer panicToErr ... - // else it seems the recover is not fully handled - if recoverPanicToErr { - if x := recover(); x != nil { - // fmt.Printf("panic'ing with: %v\n", x) - // debug.PrintStack() - panicValToErr(h, x, err) - } - } -} - -func panicValToErr(h errDecorator, v interface{}, err *error) { - switch xerr := v.(type) { - case nil: - case error: - switch xerr { - case nil: - case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized: - // treat as special (bubble up) - *err = xerr - default: - h.wrapErr(xerr, err) - } - case string: - if xerr != "" { - h.wrapErr(xerr, err) - } - case fmt.Stringer: - if xerr != nil { - h.wrapErr(xerr, err) - } - default: - h.wrapErr(v, err) - } -} - -func isImmutableKind(k reflect.Kind) (v bool) { - // return immutableKindsSet[k] - // since we know reflect.Kind is in range 0..31, then use the k%32 == k constraint - return immutableKindsSet[k%reflect.Kind(len(immutableKindsSet))] // bounds-check-elimination -} - -// ---- - -type codecFnInfo struct { - ti *typeInfo - xfFn Ext - xfTag uint64 - seq seqType - addrD bool - addrF bool // if addrD, this says whether decode function can take a value or a ptr - addrE bool -} - -// codecFn encapsulates the captured variables and the encode function. -// This way, we only do some calculations one times, and pass to the -// code block that should be called (encapsulated in a function) -// instead of executing the checks every time. -type codecFn struct { - i codecFnInfo - fe func(*Encoder, *codecFnInfo, reflect.Value) - fd func(*Decoder, *codecFnInfo, reflect.Value) - _ [1]uint64 // padding -} - -type codecRtidFn struct { - rtid uintptr - fn *codecFn -} - -// ---- - -// these "checkOverflow" functions must be inlinable, and not call anybody. -// Overflow means that the value cannot be represented without wrapping/overflow. -// Overflow=false does not mean that the value can be represented without losing precision -// (especially for floating point). - -type checkOverflow struct{} - -// func (checkOverflow) Float16(f float64) (overflow bool) { -// panicv.errorf("unimplemented") -// if f < 0 { -// f = -f -// } -// return math.MaxFloat32 < f && f <= math.MaxFloat64 -// } - -func (checkOverflow) Float32(v float64) (overflow bool) { - if v < 0 { - v = -v - } - return math.MaxFloat32 < v && v <= math.MaxFloat64 -} -func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) { - if bitsize == 0 || bitsize >= 64 || v == 0 { - return - } - if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc { - overflow = true - } - return -} -func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) { - if bitsize == 0 || bitsize >= 64 || v == 0 { - return - } - if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc { - overflow = true - } - return -} -func (checkOverflow) SignedInt(v uint64) (overflow bool) { - //e.g. -127 to 128 for int8 - pos := (v >> 63) == 0 - ui2 := v & 0x7fffffffffffffff - if pos { - if ui2 > math.MaxInt64 { - overflow = true - } - } else { - if ui2 > math.MaxInt64-1 { - overflow = true - } - } - return -} - -func (x checkOverflow) Float32V(v float64) float64 { - if x.Float32(v) { - panicv.errorf("float32 overflow: %v", v) - } - return v -} -func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 { - if x.Uint(v, bitsize) { - panicv.errorf("uint64 overflow: %v", v) - } - return v -} -func (x checkOverflow) IntV(v int64, bitsize uint8) int64 { - if x.Int(v, bitsize) { - panicv.errorf("int64 overflow: %v", v) - } - return v -} -func (x checkOverflow) SignedIntV(v uint64) int64 { - if x.SignedInt(v) { - panicv.errorf("uint64 to int64 overflow: %v", v) - } - return int64(v) -} - -// ------------------ SORT ----------------- - -func isNaN(f float64) bool { return f != f } - -// ----------------------- - -type ioFlusher interface { - Flush() error -} - -type ioPeeker interface { - Peek(int) ([]byte, error) -} - -type ioBuffered interface { - Buffered() int -} - -// ----------------------- - -type intSlice []int64 -type uintSlice []uint64 - -// type uintptrSlice []uintptr -type floatSlice []float64 -type boolSlice []bool -type stringSlice []string - -// type bytesSlice [][]byte - -func (p intSlice) Len() int { return len(p) } -func (p intSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] } -func (p intSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p uintSlice) Len() int { return len(p) } -func (p uintSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] } -func (p uintSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -// func (p uintptrSlice) Len() int { return len(p) } -// func (p uintptrSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] } -// func (p uintptrSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p floatSlice) Len() int { return len(p) } -func (p floatSlice) Less(i, j int) bool { - return p[uint(i)] < p[uint(j)] || isNaN(p[uint(i)]) && !isNaN(p[uint(j)]) -} -func (p floatSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p stringSlice) Len() int { return len(p) } -func (p stringSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] } -func (p stringSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -// func (p bytesSlice) Len() int { return len(p) } -// func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[uint(i)], p[uint(j)]) == -1 } -// func (p bytesSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p boolSlice) Len() int { return len(p) } -func (p boolSlice) Less(i, j int) bool { return !p[uint(i)] && p[uint(j)] } -func (p boolSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -// --------------------- - -type sfiRv struct { - v *structFieldInfo - r reflect.Value -} - -type intRv struct { - v int64 - r reflect.Value -} -type intRvSlice []intRv -type uintRv struct { - v uint64 - r reflect.Value -} -type uintRvSlice []uintRv -type floatRv struct { - v float64 - r reflect.Value -} -type floatRvSlice []floatRv -type boolRv struct { - v bool - r reflect.Value -} -type boolRvSlice []boolRv -type stringRv struct { - v string - r reflect.Value -} -type stringRvSlice []stringRv -type bytesRv struct { - v []byte - r reflect.Value -} -type bytesRvSlice []bytesRv -type timeRv struct { - v time.Time - r reflect.Value -} -type timeRvSlice []timeRv - -func (p intRvSlice) Len() int { return len(p) } -func (p intRvSlice) Less(i, j int) bool { return p[uint(i)].v < p[uint(j)].v } -func (p intRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p uintRvSlice) Len() int { return len(p) } -func (p uintRvSlice) Less(i, j int) bool { return p[uint(i)].v < p[uint(j)].v } -func (p uintRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p floatRvSlice) Len() int { return len(p) } -func (p floatRvSlice) Less(i, j int) bool { - return p[uint(i)].v < p[uint(j)].v || isNaN(p[uint(i)].v) && !isNaN(p[uint(j)].v) -} -func (p floatRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p stringRvSlice) Len() int { return len(p) } -func (p stringRvSlice) Less(i, j int) bool { return p[uint(i)].v < p[uint(j)].v } -func (p stringRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p bytesRvSlice) Len() int { return len(p) } -func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[uint(i)].v, p[uint(j)].v) == -1 } -func (p bytesRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p boolRvSlice) Len() int { return len(p) } -func (p boolRvSlice) Less(i, j int) bool { return !p[uint(i)].v && p[uint(j)].v } -func (p boolRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -func (p timeRvSlice) Len() int { return len(p) } -func (p timeRvSlice) Less(i, j int) bool { return p[uint(i)].v.Before(p[uint(j)].v) } -func (p timeRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -// ----------------- - -type bytesI struct { - v []byte - i interface{} -} - -type bytesISlice []bytesI - -func (p bytesISlice) Len() int { return len(p) } -func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[uint(i)].v, p[uint(j)].v) == -1 } -func (p bytesISlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } - -// ----------------- - -type set []uintptr - -func (s *set) add(v uintptr) (exists bool) { - // e.ci is always nil, or len >= 1 - x := *s - if x == nil { - x = make([]uintptr, 1, 8) - x[0] = v - *s = x - return - } - // typically, length will be 1. make this perform. - if len(x) == 1 { - if j := x[0]; j == 0 { - x[0] = v - } else if j == v { - exists = true - } else { - x = append(x, v) - *s = x - } - return - } - // check if it exists - for _, j := range x { - if j == v { - exists = true - return - } - } - // try to replace a "deleted" slot - for i, j := range x { - if j == 0 { - x[i] = v - return - } - } - // if unable to replace deleted slot, just append it. - x = append(x, v) - *s = x - return -} - -func (s *set) remove(v uintptr) (exists bool) { - x := *s - if len(x) == 0 { +func checkOverflow(ui uint64, i int64, bitsize uint8) { + // check overflow (logic adapted from std pkg reflect/value.go OverflowUint() + if bitsize == 0 { return } - if len(x) == 1 { - if x[0] == v { - x[0] = 0 + if i != 0 { + if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc { + decErr("Overflow int value: %v", i) } - return } - for i, j := range x { - if j == v { - exists = true - x[i] = 0 // set it to 0, as way to delete it. - // copy(x[i:], x[i+1:]) - // x = x[:len(x)-1] - return + if ui != 0 { + if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc { + decErr("Overflow uint value: %v", ui) } } - return -} - -// ------ - -// bitset types are better than [256]bool, because they permit the whole -// bitset array being on a single cache line and use less memory. -// -// Also, since pos is a byte (0-255), there's no bounds checks on indexing (cheap). -// -// We previously had bitset128 [16]byte, and bitset32 [4]byte, but those introduces -// bounds checking, so we discarded them, and everyone uses bitset256. -// -// given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1). -// consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7 - -type bitset256 [32]byte - -func (x *bitset256) isset(pos byte) bool { - return x[pos>>3]&(1<<(pos&7)) != 0 -} - -// func (x *bitset256) issetv(pos byte) byte { -// return x[pos>>3] & (1 << (pos & 7)) -// } - -func (x *bitset256) set(pos byte) { - x[pos>>3] |= (1 << (pos & 7)) -} - -// func (x *bitset256) unset(pos byte) { -// x[pos>>3] &^= (1 << (pos & 7)) -// } - -// type bit2set256 [64]byte - -// func (x *bit2set256) set(pos byte, v1, v2 bool) { -// var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6 -// if v1 { -// x[pos>>2] |= 1 << (pos2 + 1) -// } -// if v2 { -// x[pos>>2] |= 1 << pos2 -// } -// } -// func (x *bit2set256) get(pos byte) uint8 { -// var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6 -// return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011 -// } - -// ------------ - -type pooler struct { - // function-scoped pooled resources - tiload sync.Pool // for type info loading - sfiRv8, sfiRv16, sfiRv32, sfiRv64, sfiRv128 sync.Pool // for struct encoding - - // lifetime-scoped pooled resources - // dn sync.Pool // for decNaked - buf1k, buf2k, buf4k, buf8k, buf16k, buf32k, buf64k sync.Pool // for [N]byte -} - -func (p *pooler) init() { - p.tiload.New = func() interface{} { return new(typeInfoLoadArray) } - - p.sfiRv8.New = func() interface{} { return new([8]sfiRv) } - p.sfiRv16.New = func() interface{} { return new([16]sfiRv) } - p.sfiRv32.New = func() interface{} { return new([32]sfiRv) } - p.sfiRv64.New = func() interface{} { return new([64]sfiRv) } - p.sfiRv128.New = func() interface{} { return new([128]sfiRv) } - - // p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x } - - p.buf1k.New = func() interface{} { return new([1 * 1024]byte) } - p.buf2k.New = func() interface{} { return new([2 * 1024]byte) } - p.buf4k.New = func() interface{} { return new([4 * 1024]byte) } - p.buf8k.New = func() interface{} { return new([8 * 1024]byte) } - p.buf16k.New = func() interface{} { return new([16 * 1024]byte) } - p.buf32k.New = func() interface{} { return new([32 * 1024]byte) } - p.buf64k.New = func() interface{} { return new([64 * 1024]byte) } - -} - -// func (p *pooler) sfiRv8() (sp *sync.Pool, v interface{}) { -// return &p.strRv8, p.strRv8.Get() -// } -// func (p *pooler) sfiRv16() (sp *sync.Pool, v interface{}) { -// return &p.strRv16, p.strRv16.Get() -// } -// func (p *pooler) sfiRv32() (sp *sync.Pool, v interface{}) { -// return &p.strRv32, p.strRv32.Get() -// } -// func (p *pooler) sfiRv64() (sp *sync.Pool, v interface{}) { -// return &p.strRv64, p.strRv64.Get() -// } -// func (p *pooler) sfiRv128() (sp *sync.Pool, v interface{}) { -// return &p.strRv128, p.strRv128.Get() -// } - -// func (p *pooler) bytes1k() (sp *sync.Pool, v interface{}) { -// return &p.buf1k, p.buf1k.Get() -// } -// func (p *pooler) bytes2k() (sp *sync.Pool, v interface{}) { -// return &p.buf2k, p.buf2k.Get() -// } -// func (p *pooler) bytes4k() (sp *sync.Pool, v interface{}) { -// return &p.buf4k, p.buf4k.Get() -// } -// func (p *pooler) bytes8k() (sp *sync.Pool, v interface{}) { -// return &p.buf8k, p.buf8k.Get() -// } -// func (p *pooler) bytes16k() (sp *sync.Pool, v interface{}) { -// return &p.buf16k, p.buf16k.Get() -// } -// func (p *pooler) bytes32k() (sp *sync.Pool, v interface{}) { -// return &p.buf32k, p.buf32k.Get() -// } -// func (p *pooler) bytes64k() (sp *sync.Pool, v interface{}) { -// return &p.buf64k, p.buf64k.Get() -// } - -// func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) { -// return &p.tiload, p.tiload.Get() -// } - -// func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) { -// return &p.dn, p.dn.Get() -// } - -// func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) { -// sp := &(p.dn) -// vv := sp.Get() -// return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) } -// } -// func (p *pooler) decNakedGet() (v interface{}) { -// return p.dn.Get() -// } -// func (p *pooler) tiLoadGet() (v interface{}) { -// return p.tiload.Get() -// } -// func (p *pooler) decNakedPut(v interface{}) { -// p.dn.Put(v) -// } -// func (p *pooler) tiLoadPut(v interface{}) { -// p.tiload.Put(v) -// } - -// ---------------------------------------------------- - -type panicHdl struct{} - -func (panicHdl) errorv(err error) { - if err != nil { - panic(err) - } -} - -func (panicHdl) errorstr(message string) { - if message != "" { - panic(message) - } -} - -func (panicHdl) errorf(format string, params ...interface{}) { - if format == "" { - } else if len(params) == 0 { - panic(format) - } else { - panic(fmt.Sprintf(format, params...)) - } -} - -// ---------------------------------------------------- - -type errDecorator interface { - wrapErr(in interface{}, out *error) -} - -type errDecoratorDef struct{} - -func (errDecoratorDef) wrapErr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) } - -// ---------------------------------------------------- - -type must struct{} - -func (must) String(s string, err error) string { - if err != nil { - panicv.errorv(err) - } - return s -} -func (must) Int(s int64, err error) int64 { - if err != nil { - panicv.errorv(err) - } - return s -} -func (must) Uint(s uint64, err error) uint64 { - if err != nil { - panicv.errorv(err) - } - return s } -func (must) Float(s float64, err error) float64 { - if err != nil { - panicv.errorv(err) - } - return s -} - -// ------------------- - -type bytesBufPooler struct { - pool *sync.Pool - poolbuf interface{} -} - -func (z *bytesBufPooler) end() { - if z.pool != nil { - z.pool.Put(z.poolbuf) - z.pool, z.poolbuf = nil, nil - } -} - -func (z *bytesBufPooler) get(bufsize int) (buf []byte) { - // ensure an end is called first (if necessary) - if z.pool != nil { - z.pool.Put(z.poolbuf) - z.pool, z.poolbuf = nil, nil - } - - // // Try to use binary search. - // // This is not optimal, as most folks select 1k or 2k buffers - // // so a linear search is better (sequence of if/else blocks) - // if bufsize < 1 { - // bufsize = 0 - // } else { - // bufsize-- - // bufsize /= 1024 - // } - // switch bufsize { - // case 0: - // z.pool, z.poolbuf = pool.bytes1k() - // buf = z.poolbuf.(*[1 * 1024]byte)[:] - // case 1: - // z.pool, z.poolbuf = pool.bytes2k() - // buf = z.poolbuf.(*[2 * 1024]byte)[:] - // case 2, 3: - // z.pool, z.poolbuf = pool.bytes4k() - // buf = z.poolbuf.(*[4 * 1024]byte)[:] - // case 4, 5, 6, 7: - // z.pool, z.poolbuf = pool.bytes8k() - // buf = z.poolbuf.(*[8 * 1024]byte)[:] - // case 8, 9, 10, 11, 12, 13, 14, 15: - // z.pool, z.poolbuf = pool.bytes16k() - // buf = z.poolbuf.(*[16 * 1024]byte)[:] - // case 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31: - // z.pool, z.poolbuf = pool.bytes32k() - // buf = z.poolbuf.(*[32 * 1024]byte)[:] - // default: - // z.pool, z.poolbuf = pool.bytes64k() - // buf = z.poolbuf.(*[64 * 1024]byte)[:] - // } - // return - - if bufsize <= 1*1024 { - z.pool, z.poolbuf = &pool.buf1k, pool.buf1k.Get() // pool.bytes1k() - buf = z.poolbuf.(*[1 * 1024]byte)[:] - } else if bufsize <= 2*1024 { - z.pool, z.poolbuf = &pool.buf2k, pool.buf2k.Get() // pool.bytes2k() - buf = z.poolbuf.(*[2 * 1024]byte)[:] - } else if bufsize <= 4*1024 { - z.pool, z.poolbuf = &pool.buf4k, pool.buf4k.Get() // pool.bytes4k() - buf = z.poolbuf.(*[4 * 1024]byte)[:] - } else if bufsize <= 8*1024 { - z.pool, z.poolbuf = &pool.buf8k, pool.buf8k.Get() // pool.bytes8k() - buf = z.poolbuf.(*[8 * 1024]byte)[:] - } else if bufsize <= 16*1024 { - z.pool, z.poolbuf = &pool.buf16k, pool.buf16k.Get() // pool.bytes16k() - buf = z.poolbuf.(*[16 * 1024]byte)[:] - } else if bufsize <= 32*1024 { - z.pool, z.poolbuf = &pool.buf32k, pool.buf32k.Get() // pool.bytes32k() - buf = z.poolbuf.(*[32 * 1024]byte)[:] - } else { - z.pool, z.poolbuf = &pool.buf64k, pool.buf64k.Get() // pool.bytes64k() - buf = z.poolbuf.(*[64 * 1024]byte)[:] - } - return -} - -// ---------------- - -type sfiRvPooler struct { - pool *sync.Pool - poolv interface{} -} - -func (z *sfiRvPooler) end() { - if z.pool != nil { - z.pool.Put(z.poolv) - z.pool, z.poolv = nil, nil - } -} - -func (z *sfiRvPooler) get(newlen int) (fkvs []sfiRv) { - if newlen < 0 { // bounds-check-elimination - // cannot happen // here for bounds-check-elimination - } else if newlen <= 8 { - z.pool, z.poolv = &pool.sfiRv8, pool.sfiRv8.Get() // pool.sfiRv8() - fkvs = z.poolv.(*[8]sfiRv)[:newlen] - } else if newlen <= 16 { - z.pool, z.poolv = &pool.sfiRv16, pool.sfiRv16.Get() // pool.sfiRv16() - fkvs = z.poolv.(*[16]sfiRv)[:newlen] - } else if newlen <= 32 { - z.pool, z.poolv = &pool.sfiRv32, pool.sfiRv32.Get() // pool.sfiRv32() - fkvs = z.poolv.(*[32]sfiRv)[:newlen] - } else if newlen <= 64 { - z.pool, z.poolv = &pool.sfiRv64, pool.sfiRv64.Get() // pool.sfiRv64() - fkvs = z.poolv.(*[64]sfiRv)[:newlen] - } else if newlen <= 128 { - z.pool, z.poolv = &pool.sfiRv128, pool.sfiRv128.Get() // pool.sfiRv128() - fkvs = z.poolv.(*[128]sfiRv)[:newlen] - } else { - fkvs = make([]sfiRv, newlen) - } - return -} - -// xdebugf printf. the message in red on the terminal. -// Use it in place of fmt.Printf (which it calls internally) -func xdebugf(pattern string, args ...interface{}) { - var delim string - if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' { - delim = "\n" - } - fmt.Printf("\033[1;31m"+pattern+delim+"\033[0m", args...) -} - -// func isImmutableKind(k reflect.Kind) (v bool) { -// return false || -// k == reflect.Int || -// k == reflect.Int8 || -// k == reflect.Int16 || -// k == reflect.Int32 || -// k == reflect.Int64 || -// k == reflect.Uint || -// k == reflect.Uint8 || -// k == reflect.Uint16 || -// k == reflect.Uint32 || -// k == reflect.Uint64 || -// k == reflect.Uintptr || -// k == reflect.Float32 || -// k == reflect.Float64 || -// k == reflect.Bool || -// k == reflect.String -// } - -// func timeLocUTCName(tzint int16) string { -// if tzint == 0 { -// return "UTC" -// } -// var tzname = []byte("UTC+00:00") -// //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf.. inline below. -// //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first -// var tzhr, tzmin int16 -// if tzint < 0 { -// tzname[3] = '-' // (TODO: verify. this works here) -// tzhr, tzmin = -tzint/60, (-tzint)%60 -// } else { -// tzhr, tzmin = tzint/60, tzint%60 -// } -// tzname[4] = timeDigits[tzhr/10] -// tzname[5] = timeDigits[tzhr%10] -// tzname[7] = timeDigits[tzmin/10] -// tzname[8] = timeDigits[tzmin%10] -// return string(tzname) -// //return time.FixedZone(string(tzname), int(tzint)*60) -// } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go index 0cbd665e257f0..93f12854f21ae 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go @@ -1,121 +1,132 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec // All non-std package dependencies live in this file, // so porting to different environment is easy (just update functions). -func pruneSignExt(v []byte, pos bool) (n int) { - if len(v) < 2 { - } else if pos && v[0] == 0 { - for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ { - } - } else if !pos && v[0] == 0xff { - for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ { - } +import ( + "errors" + "fmt" + "math" + "reflect" +) + +var ( + raisePanicAfterRecover = false + debugging = true +) + +func panicValToErr(panicVal interface{}, err *error) { + switch xerr := panicVal.(type) { + case error: + *err = xerr + case string: + *err = errors.New(xerr) + default: + *err = fmt.Errorf("%v", panicVal) + } + if raisePanicAfterRecover { + panic(panicVal) } return } -// validate that this function is correct ... -// culled from OGRE (Object-Oriented Graphics Rendering Engine) -// function: halfToFloatI (http://stderr.org/doc/ogre-doc/api/OgreBitwise_8h-source.html) -func halfFloatToFloatBits(yy uint16) (d uint32) { - y := uint32(yy) - s := (y >> 15) & 0x01 - e := (y >> 10) & 0x1f - m := y & 0x03ff - - if e == 0 { - if m == 0 { // plu or minus 0 - return s << 31 +func hIsEmptyValue(v reflect.Value, deref, checkStruct bool) bool { + switch v.Kind() { + case reflect.Invalid: + return true + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + if deref { + if v.IsNil() { + return true + } + return hIsEmptyValue(v.Elem(), deref, checkStruct) + } else { + return v.IsNil() } - // Denormalized number -- renormalize it - for (m & 0x00000400) == 0 { - m <<= 1 - e -= 1 + case reflect.Struct: + if !checkStruct { + return false } - e += 1 - const zz uint32 = 0x0400 - m &= ^zz - } else if e == 31 { - if m == 0 { // Inf - return (s << 31) | 0x7f800000 + // return true if all fields are empty. else return false. + + // we cannot use equality check, because some fields may be maps/slices/etc + // and consequently the structs are not comparable. + // return v.Interface() == reflect.Zero(v.Type()).Interface() + for i, n := 0, v.NumField(); i < n; i++ { + if !hIsEmptyValue(v.Field(i), deref, checkStruct) { + return false + } } - return (s << 31) | 0x7f800000 | (m << 13) // NaN + return true } - e = e + (127 - 15) - m = m << 13 - return (s << 31) | (e << 23) | m + return false } -// GrowCap will return a new capacity for a slice, given the following: -// - oldCap: current capacity -// - unit: in-memory size of an element -// - num: number of elements to add -func growCap(oldCap, unit, num int) (newCap int) { - // appendslice logic (if cap < 1024, *2, else *1.25): - // leads to many copy calls, especially when copying bytes. - // bytes.Buffer model (2*cap + n): much better for bytes. - // smarter way is to take the byte-size of the appended element(type) into account - - // maintain 3 thresholds: - // t1: if cap <= t1, newcap = 2x - // t2: if cap <= t2, newcap = 1.75x - // t3: if cap <= t3, newcap = 1.5x - // else newcap = 1.25x - // - // t1, t2, t3 >= 1024 always. - // i.e. if unit size >= 16, then always do 2x or 1.25x (ie t1, t2, t3 are all same) - // - // With this, appending for bytes increase by: - // 100% up to 4K - // 75% up to 8K - // 50% up to 16K - // 25% beyond that +func isEmptyValue(v reflect.Value) bool { + return hIsEmptyValue(v, derefForIsEmptyValue, checkStructForEmptyValue) +} - // unit can be 0 e.g. for struct{}{}; handle that appropriately - var t1, t2, t3 int // thresholds - if unit <= 1 { - t1, t2, t3 = 4*1024, 8*1024, 16*1024 - } else if unit < 16 { - t3 = 16 / unit * 1024 - t1 = t3 * 1 / 4 - t2 = t3 * 2 / 4 - } else { - t1, t2, t3 = 1024, 1024, 1024 +func debugf(format string, args ...interface{}) { + if debugging { + if len(format) == 0 || format[len(format)-1] != '\n' { + format = format + "\n" + } + fmt.Printf(format, args...) } +} - var x int // temporary variable - - // x is multiplier here: one of 5, 6, 7 or 8; incr of 25%, 50%, 75% or 100% respectively - if oldCap <= t1 { // [0,t1] - x = 8 - } else if oldCap > t3 { // (t3,infinity] - x = 5 - } else if oldCap <= t2 { // (t1,t2] - x = 7 - } else { // (t2,t3] - x = 6 +func pruneSignExt(v []byte, pos bool) (n int) { + if len(v) < 2 { + } else if pos && v[0] == 0 { + for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ { + } + } else if !pos && v[0] == 0xff { + for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ { + } } - newCap = x * oldCap / 4 + return +} - if num > 0 { - newCap += num +func implementsIntf(typ, iTyp reflect.Type) (success bool, indir int8) { + if typ == nil { + return } - - // ensure newCap is a multiple of 64 (if it is > 64) or 16. - if newCap > 64 { - if x = newCap % 64; x != 0 { - x = newCap / 64 - newCap = 64 * (x + 1) + rt := typ + // The type might be a pointer and we need to keep + // dereferencing to the base type until we find an implementation. + for { + if rt.Implements(iTyp) { + return true, indir } - } else { - if x = newCap % 16; x != 0 { - x = newCap / 16 - newCap = 16 * (x + 1) + if p := rt; p.Kind() == reflect.Ptr { + indir++ + if indir >= math.MaxInt8 { // insane number of indirections + return false, 0 + } + rt = p.Elem() + continue } + break } - return + // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy. + if typ.Kind() != reflect.Ptr { + // Not a pointer, but does the pointer work? + if reflect.PtrTo(typ).Implements(iTyp) { + return true, -1 + } + } + return false, 0 } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper_not_unsafe.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper_not_unsafe.go deleted file mode 100644 index 74987f9f7f74a..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/helper_not_unsafe.go +++ /dev/null @@ -1,331 +0,0 @@ -// +build !go1.7 safe appengine - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "reflect" - "sync/atomic" - "time" -) - -const safeMode = true - -// stringView returns a view of the []byte as a string. -// In unsafe mode, it doesn't incur allocation and copying caused by conversion. -// In regular safe mode, it is an allocation and copy. -// -// Usage: Always maintain a reference to v while result of this call is in use, -// and call keepAlive4BytesView(v) at point where done with view. -func stringView(v []byte) string { - return string(v) -} - -// bytesView returns a view of the string as a []byte. -// In unsafe mode, it doesn't incur allocation and copying caused by conversion. -// In regular safe mode, it is an allocation and copy. -// -// Usage: Always maintain a reference to v while result of this call is in use, -// and call keepAlive4BytesView(v) at point where done with view. -func bytesView(v string) []byte { - return []byte(v) -} - -func definitelyNil(v interface{}) bool { - // this is a best-effort option. - // We just return false, so we don't unnecessarily incur the cost of reflection this early. - return false -} - -func rv2i(rv reflect.Value) interface{} { - return rv.Interface() -} - -func rt2id(rt reflect.Type) uintptr { - return reflect.ValueOf(rt).Pointer() -} - -// func rv2rtid(rv reflect.Value) uintptr { -// return reflect.ValueOf(rv.Type()).Pointer() -// } - -func i2rtid(i interface{}) uintptr { - return reflect.ValueOf(reflect.TypeOf(i)).Pointer() -} - -// -------------------------- - -func isEmptyValue(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - switch v.Kind() { - case reflect.Invalid: - return true - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - if deref { - if v.IsNil() { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return v.IsNil() - case reflect.Struct: - return isEmptyStruct(v, tinfos, deref, checkStruct) - } - return false -} - -// -------------------------- -// type ptrToRvMap struct{} - -// func (*ptrToRvMap) init() {} -// func (*ptrToRvMap) get(i interface{}) reflect.Value { -// return reflect.ValueOf(i).Elem() -// } - -// -------------------------- -type atomicClsErr struct { - v atomic.Value -} - -func (x *atomicClsErr) load() (e clsErr) { - if i := x.v.Load(); i != nil { - e = i.(clsErr) - } - return -} - -func (x *atomicClsErr) store(p clsErr) { - x.v.Store(p) -} - -// -------------------------- -type atomicTypeInfoSlice struct { // expected to be 2 words - v atomic.Value -} - -func (x *atomicTypeInfoSlice) load() (e []rtid2ti) { - if i := x.v.Load(); i != nil { - e = i.([]rtid2ti) - } - return -} - -func (x *atomicTypeInfoSlice) store(p []rtid2ti) { - x.v.Store(p) -} - -// -------------------------- -type atomicRtidFnSlice struct { // expected to be 2 words - v atomic.Value -} - -func (x *atomicRtidFnSlice) load() (e []codecRtidFn) { - if i := x.v.Load(); i != nil { - e = i.([]codecRtidFn) - } - return -} - -func (x *atomicRtidFnSlice) store(p []codecRtidFn) { - x.v.Store(p) -} - -// -------------------------- -func (n *decNaked) ru() reflect.Value { - return reflect.ValueOf(&n.u).Elem() -} -func (n *decNaked) ri() reflect.Value { - return reflect.ValueOf(&n.i).Elem() -} -func (n *decNaked) rf() reflect.Value { - return reflect.ValueOf(&n.f).Elem() -} -func (n *decNaked) rl() reflect.Value { - return reflect.ValueOf(&n.l).Elem() -} -func (n *decNaked) rs() reflect.Value { - return reflect.ValueOf(&n.s).Elem() -} -func (n *decNaked) rt() reflect.Value { - return reflect.ValueOf(&n.t).Elem() -} -func (n *decNaked) rb() reflect.Value { - return reflect.ValueOf(&n.b).Elem() -} - -// -------------------------- -func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { - rv.SetBytes(d.rawBytes()) -} - -func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) { - rv.SetString(d.d.DecodeString()) -} - -func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) { - rv.SetBool(d.d.DecodeBool()) -} - -func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) { - rv.Set(reflect.ValueOf(d.d.DecodeTime())) -} - -func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - fv := d.d.DecodeFloat64() - if chkOvf.Float32(fv) { - d.errorf("float32 overflow: %v", fv) - } - rv.SetFloat(fv) -} - -func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - rv.SetFloat(d.d.DecodeFloat64()) -} - -func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) -} - -func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 8)) -} - -func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 16)) -} - -func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 32)) -} - -func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(d.d.DecodeInt64()) -} - -func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 8)) -} - -func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 16)) -} - -func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 32)) -} - -func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(d.d.DecodeUint64()) -} - -// ---------------- - -func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeBool(rv.Bool()) -} - -func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeTime(rv2i(rv).(time.Time)) -} - -func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { - s := rv.String() - if e.h.StringToRaw { - e.e.EncodeStringBytesRaw(bytesView(s)) - } else { - e.e.EncodeStringEnc(cUTF8, s) - } -} - -func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeFloat64(rv.Float()) -} - -func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeFloat32(float32(rv.Float())) -} - -func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -// // keepAlive4BytesView maintains a reference to the input parameter for bytesView. -// // -// // Usage: call this at point where done with the bytes view. -// func keepAlive4BytesView(v string) {} - -// // keepAlive4BytesView maintains a reference to the input parameter for stringView. -// // -// // Usage: call this at point where done with the string view. -// func keepAlive4StringView(v []byte) {} - -// func definitelyNil(v interface{}) bool { -// rv := reflect.ValueOf(v) -// switch rv.Kind() { -// case reflect.Invalid: -// return true -// case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Slice, reflect.Map, reflect.Func: -// return rv.IsNil() -// default: -// return false -// } -// } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper_unsafe.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper_unsafe.go deleted file mode 100644 index 3bc34d90d7c2c..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/helper_unsafe.go +++ /dev/null @@ -1,745 +0,0 @@ -// +build !safe -// +build !appengine -// +build go1.7 - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "reflect" - "sync/atomic" - "time" - "unsafe" -) - -// This file has unsafe variants of some helper methods. -// NOTE: See helper_not_unsafe.go for the usage information. - -// var zeroRTv [4]uintptr - -const safeMode = false -const unsafeFlagIndir = 1 << 7 // keep in sync with GO_ROOT/src/reflect/value.go - -type unsafeString struct { - Data unsafe.Pointer - Len int -} - -type unsafeSlice struct { - Data unsafe.Pointer - Len int - Cap int -} - -type unsafeIntf struct { - typ unsafe.Pointer - word unsafe.Pointer -} - -type unsafeReflectValue struct { - typ unsafe.Pointer - ptr unsafe.Pointer - flag uintptr -} - -func stringView(v []byte) string { - if len(v) == 0 { - return "" - } - bx := (*unsafeSlice)(unsafe.Pointer(&v)) - return *(*string)(unsafe.Pointer(&unsafeString{bx.Data, bx.Len})) -} - -func bytesView(v string) []byte { - if len(v) == 0 { - return zeroByteSlice - } - sx := (*unsafeString)(unsafe.Pointer(&v)) - return *(*[]byte)(unsafe.Pointer(&unsafeSlice{sx.Data, sx.Len, sx.Len})) -} - -func definitelyNil(v interface{}) bool { - // There is no global way of checking if an interface is nil. - // For true references (map, ptr, func, chan), you can just look - // at the word of the interface. However, for slices, you have to dereference - // the word, and get a pointer to the 3-word interface value. - // - // However, the following are cheap calls - // - TypeOf(interface): cheap 2-line call. - // - ValueOf(interface{}): expensive - // - type.Kind: cheap call through an interface - // - Value.Type(): cheap call - // except it's a method value (e.g. r.Read, which implies that it is a Func) - - return ((*unsafeIntf)(unsafe.Pointer(&v))).word == nil -} - -func rv2i(rv reflect.Value) interface{} { - // TODO: consider a more generally-known optimization for reflect.Value ==> Interface - // - // Currently, we use this fragile method that taps into implememtation details from - // the source go stdlib reflect/value.go, and trims the implementation. - - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - // true references (map, func, chan, ptr - NOT slice) may be double-referenced as flagIndir - var ptr unsafe.Pointer - if refBitset.isset(byte(urv.flag&(1<<5-1))) && urv.flag&unsafeFlagIndir != 0 { - ptr = *(*unsafe.Pointer)(urv.ptr) - } else { - ptr = urv.ptr - } - return *(*interface{})(unsafe.Pointer(&unsafeIntf{typ: urv.typ, word: ptr})) -} - -func rt2id(rt reflect.Type) uintptr { - return uintptr(((*unsafeIntf)(unsafe.Pointer(&rt))).word) -} - -// func rv2rtid(rv reflect.Value) uintptr { -// return uintptr((*unsafeReflectValue)(unsafe.Pointer(&rv)).typ) -// } - -func i2rtid(i interface{}) uintptr { - return uintptr(((*unsafeIntf)(unsafe.Pointer(&i))).typ) -} - -// -------------------------- - -func isEmptyValue(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - urv := (*unsafeReflectValue)(unsafe.Pointer(&v)) - if urv.flag == 0 { - return true - } - switch v.Kind() { - case reflect.Invalid: - return true - case reflect.String: - return (*unsafeString)(urv.ptr).Len == 0 - case reflect.Slice: - return (*unsafeSlice)(urv.ptr).Len == 0 - case reflect.Bool: - return !*(*bool)(urv.ptr) - case reflect.Int: - return *(*int)(urv.ptr) == 0 - case reflect.Int8: - return *(*int8)(urv.ptr) == 0 - case reflect.Int16: - return *(*int16)(urv.ptr) == 0 - case reflect.Int32: - return *(*int32)(urv.ptr) == 0 - case reflect.Int64: - return *(*int64)(urv.ptr) == 0 - case reflect.Uint: - return *(*uint)(urv.ptr) == 0 - case reflect.Uint8: - return *(*uint8)(urv.ptr) == 0 - case reflect.Uint16: - return *(*uint16)(urv.ptr) == 0 - case reflect.Uint32: - return *(*uint32)(urv.ptr) == 0 - case reflect.Uint64: - return *(*uint64)(urv.ptr) == 0 - case reflect.Uintptr: - return *(*uintptr)(urv.ptr) == 0 - case reflect.Float32: - return *(*float32)(urv.ptr) == 0 - case reflect.Float64: - return *(*float64)(urv.ptr) == 0 - case reflect.Interface: - isnil := urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil - if deref { - if isnil { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return isnil - case reflect.Ptr: - // isnil := urv.ptr == nil (not sufficient, as a pointer value encodes the type) - isnil := urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil - if deref { - if isnil { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return isnil - case reflect.Struct: - return isEmptyStruct(v, tinfos, deref, checkStruct) - case reflect.Map, reflect.Array, reflect.Chan: - return v.Len() == 0 - } - return false -} - -// -------------------------- - -// atomicXXX is expected to be 2 words (for symmetry with atomic.Value) -// -// Note that we do not atomically load/store length and data pointer separately, -// as this could lead to some races. Instead, we atomically load/store cappedSlice. -// -// Note: with atomic.(Load|Store)Pointer, we MUST work with an unsafe.Pointer directly. - -// ---------------------- -type atomicTypeInfoSlice struct { - v unsafe.Pointer // *[]rtid2ti - _ uintptr // padding (atomicXXX expected to be 2 words) -} - -func (x *atomicTypeInfoSlice) load() (s []rtid2ti) { - x2 := atomic.LoadPointer(&x.v) - if x2 != nil { - s = *(*[]rtid2ti)(x2) - } - return -} - -func (x *atomicTypeInfoSlice) store(p []rtid2ti) { - atomic.StorePointer(&x.v, unsafe.Pointer(&p)) -} - -// -------------------------- -type atomicRtidFnSlice struct { - v unsafe.Pointer // *[]codecRtidFn - _ uintptr // padding (atomicXXX expected to be 2 words) -} - -func (x *atomicRtidFnSlice) load() (s []codecRtidFn) { - x2 := atomic.LoadPointer(&x.v) - if x2 != nil { - s = *(*[]codecRtidFn)(x2) - } - return -} - -func (x *atomicRtidFnSlice) store(p []codecRtidFn) { - atomic.StorePointer(&x.v, unsafe.Pointer(&p)) -} - -// -------------------------- -type atomicClsErr struct { - v unsafe.Pointer // *clsErr - _ uintptr // padding (atomicXXX expected to be 2 words) -} - -func (x *atomicClsErr) load() (e clsErr) { - x2 := (*clsErr)(atomic.LoadPointer(&x.v)) - if x2 != nil { - e = *x2 - } - return -} - -func (x *atomicClsErr) store(p clsErr) { - atomic.StorePointer(&x.v, unsafe.Pointer(&p)) -} - -// -------------------------- - -// to create a reflect.Value for each member field of decNaked, -// we first create a global decNaked, and create reflect.Value -// for them all. -// This way, we have the flags and type in the reflect.Value. -// Then, when a reflect.Value is called, we just copy it, -// update the ptr to the decNaked's, and return it. - -type unsafeDecNakedWrapper struct { - decNaked - ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above -} - -func (n *unsafeDecNakedWrapper) init() { - n.ru = reflect.ValueOf(&n.u).Elem() - n.ri = reflect.ValueOf(&n.i).Elem() - n.rf = reflect.ValueOf(&n.f).Elem() - n.rl = reflect.ValueOf(&n.l).Elem() - n.rs = reflect.ValueOf(&n.s).Elem() - n.rt = reflect.ValueOf(&n.t).Elem() - n.rb = reflect.ValueOf(&n.b).Elem() - // n.rr[] = reflect.ValueOf(&n.) -} - -var defUnsafeDecNakedWrapper unsafeDecNakedWrapper - -func init() { - defUnsafeDecNakedWrapper.init() -} - -func (n *decNaked) ru() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.ru - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.u) - return -} -func (n *decNaked) ri() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.ri - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.i) - return -} -func (n *decNaked) rf() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.rf - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.f) - return -} -func (n *decNaked) rl() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.rl - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.l) - return -} -func (n *decNaked) rs() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.rs - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.s) - return -} -func (n *decNaked) rt() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.rt - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.t) - return -} -func (n *decNaked) rb() (v reflect.Value) { - v = defUnsafeDecNakedWrapper.rb - ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.b) - return -} - -// -------------------------- -func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*[]byte)(urv.ptr) = d.rawBytes() -} - -func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*string)(urv.ptr) = d.d.DecodeString() -} - -func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*bool)(urv.ptr) = d.d.DecodeBool() -} - -func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*time.Time)(urv.ptr) = d.d.DecodeTime() -} - -func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - fv := d.d.DecodeFloat64() - if chkOvf.Float32(fv) { - d.errorf("float32 overflow: %v", fv) - } - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*float32)(urv.ptr) = float32(fv) -} - -func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*float64)(urv.ptr) = d.d.DecodeFloat64() -} - -func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int)(urv.ptr) = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) -} - -func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int8)(urv.ptr) = int8(chkOvf.IntV(d.d.DecodeInt64(), 8)) -} - -func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int16)(urv.ptr) = int16(chkOvf.IntV(d.d.DecodeInt64(), 16)) -} - -func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int32)(urv.ptr) = int32(chkOvf.IntV(d.d.DecodeInt64(), 32)) -} - -func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int64)(urv.ptr) = d.d.DecodeInt64() -} - -func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint)(urv.ptr) = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uintptr)(urv.ptr) = uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint8)(urv.ptr) = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)) -} - -func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint16)(urv.ptr) = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)) -} - -func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint32)(urv.ptr) = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)) -} - -func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint64)(urv.ptr) = d.d.DecodeUint64() -} - -// ------------ - -func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeBool(*(*bool)(v.ptr)) -} - -func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeTime(*(*time.Time)(v.ptr)) -} - -func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - s := *(*string)(v.ptr) - if e.h.StringToRaw { - e.e.EncodeStringBytesRaw(bytesView(s)) - } else { - e.e.EncodeStringEnc(cUTF8, s) - } -} - -func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeFloat64(*(*float64)(v.ptr)) -} - -func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeFloat32(*(*float32)(v.ptr)) -} - -func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int)(v.ptr))) -} - -func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int8)(v.ptr))) -} - -func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int16)(v.ptr))) -} - -func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int32)(v.ptr))) -} - -func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int64)(v.ptr))) -} - -func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint)(v.ptr))) -} - -func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint8)(v.ptr))) -} - -func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint16)(v.ptr))) -} - -func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint32)(v.ptr))) -} - -func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint64)(v.ptr))) -} - -func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uintptr)(v.ptr))) -} - -// ------------ - -// func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // if urv.flag&unsafeFlagIndir != 0 { -// // urv.ptr = *(*unsafe.Pointer)(urv.ptr) -// // } -// *(*[]byte)(urv.ptr) = d.rawBytes() -// } - -// func rv0t(rt reflect.Type) reflect.Value { -// ut := (*unsafeIntf)(unsafe.Pointer(&rt)) -// // we need to determine whether ifaceIndir, and then whether to just pass 0 as the ptr -// uv := unsafeReflectValue{ut.word, &zeroRTv, flag(rt.Kind())} -// return *(*reflect.Value)(unsafe.Pointer(&uv}) -// } - -// func rv2i(rv reflect.Value) interface{} { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // true references (map, func, chan, ptr - NOT slice) may be double-referenced as flagIndir -// var ptr unsafe.Pointer -// // kk := reflect.Kind(urv.flag & (1<<5 - 1)) -// // if (kk == reflect.Map || kk == reflect.Ptr || kk == reflect.Chan || kk == reflect.Func) && urv.flag&unsafeFlagIndir != 0 { -// if refBitset.isset(byte(urv.flag&(1<<5-1))) && urv.flag&unsafeFlagIndir != 0 { -// ptr = *(*unsafe.Pointer)(urv.ptr) -// } else { -// ptr = urv.ptr -// } -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{typ: urv.typ, word: ptr})) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } - -// func definitelyNil(v interface{}) bool { -// var ui *unsafeIntf = (*unsafeIntf)(unsafe.Pointer(&v)) -// if ui.word == nil { -// return true -// } -// var tk = reflect.TypeOf(v).Kind() -// return (tk == reflect.Interface || tk == reflect.Slice) && *(*unsafe.Pointer)(ui.word) == nil -// fmt.Printf(">>>> definitely nil: isnil: %v, TYPE: \t%T, word: %v, *word: %v, type: %v, nil: %v\n", -// v == nil, v, word, *((*unsafe.Pointer)(word)), ui.typ, nil) -// } - -// func keepAlive4BytesView(v string) { -// runtime.KeepAlive(v) -// } - -// func keepAlive4StringView(v []byte) { -// runtime.KeepAlive(v) -// } - -// func rt2id(rt reflect.Type) uintptr { -// return uintptr(((*unsafeIntf)(unsafe.Pointer(&rt))).word) -// // var i interface{} = rt -// // // ui := (*unsafeIntf)(unsafe.Pointer(&i)) -// // return ((*unsafeIntf)(unsafe.Pointer(&i))).word -// } - -// func rv2i(rv reflect.Value) interface{} { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // non-reference type: already indir -// // reference type: depend on flagIndir property ('cos maybe was double-referenced) -// // const (unsafeRvFlagKindMask = 1<<5 - 1 , unsafeRvFlagIndir = 1 << 7 ) -// // rvk := reflect.Kind(urv.flag & (1<<5 - 1)) -// // if (rvk == reflect.Chan || -// // rvk == reflect.Func || -// // rvk == reflect.Interface || -// // rvk == reflect.Map || -// // rvk == reflect.Ptr || -// // rvk == reflect.UnsafePointer) && urv.flag&(1<<8) != 0 { -// // fmt.Printf(">>>>> ---- double indirect reference: %v, %v\n", rvk, rv.Type()) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // } -// if urv.flag&(1<<5-1) == uintptr(reflect.Map) && urv.flag&(1<<7) != 0 { -// // fmt.Printf(">>>>> ---- double indirect reference: %v, %v\n", rvk, rv.Type()) -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// } -// // fmt.Printf(">>>>> ++++ direct reference: %v, %v\n", rvk, rv.Type()) -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } - -// const ( -// unsafeRvFlagKindMask = 1<<5 - 1 -// unsafeRvKindDirectIface = 1 << 5 -// unsafeRvFlagIndir = 1 << 7 -// unsafeRvFlagAddr = 1 << 8 -// unsafeRvFlagMethod = 1 << 9 - -// _USE_RV_INTERFACE bool = false -// _UNSAFE_RV_DEBUG = true -// ) - -// type unsafeRtype struct { -// _ [2]uintptr -// _ uint32 -// _ uint8 -// _ uint8 -// _ uint8 -// kind uint8 -// _ [2]uintptr -// _ int32 -// } - -// func _rv2i(rv reflect.Value) interface{} { -// // Note: From use, -// // - it's never an interface -// // - the only calls here are for ifaceIndir types. -// // (though that conditional is wrong) -// // To know for sure, we need the value of t.kind (which is not exposed). -// // -// // Need to validate the path: type is indirect ==> only value is indirect ==> default (value is direct) -// // - Type indirect, Value indirect: ==> numbers, boolean, slice, struct, array, string -// // - Type Direct, Value indirect: ==> map??? -// // - Type Direct, Value direct: ==> pointers, unsafe.Pointer, func, chan, map -// // -// // TRANSLATES TO: -// // if typeIndirect { } else if valueIndirect { } else { } -// // -// // Since we don't deal with funcs, then "flagNethod" is unset, and can be ignored. - -// if _USE_RV_INTERFACE { -// return rv.Interface() -// } -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - -// // if urv.flag&unsafeRvFlagMethod != 0 || urv.flag&unsafeRvFlagKindMask == uintptr(reflect.Interface) { -// // println("***** IS flag method or interface: delegating to rv.Interface()") -// // return rv.Interface() -// // } - -// // if urv.flag&unsafeRvFlagKindMask == uintptr(reflect.Interface) { -// // println("***** IS Interface: delegate to rv.Interface") -// // return rv.Interface() -// // } -// // if urv.flag&unsafeRvFlagKindMask&unsafeRvKindDirectIface == 0 { -// // if urv.flag&unsafeRvFlagAddr == 0 { -// // println("***** IS ifaceIndir typ") -// // // ui := unsafeIntf{word: urv.ptr, typ: urv.typ} -// // // return *(*interface{})(unsafe.Pointer(&ui)) -// // // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// // } else if urv.flag&unsafeRvFlagIndir != 0 { -// // println("***** IS flagindir") -// // // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // } else { -// // println("***** NOT flagindir") -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// // println("***** default: delegate to rv.Interface") - -// urt := (*unsafeRtype)(unsafe.Pointer(urv.typ)) -// if _UNSAFE_RV_DEBUG { -// fmt.Printf(">>>> start: %v: ", rv.Type()) -// fmt.Printf("%v - %v\n", *urv, *urt) -// } -// if urt.kind&unsafeRvKindDirectIface == 0 { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** +ifaceIndir type: %v\n", rv.Type()) -// } -// // println("***** IS ifaceIndir typ") -// // if true || urv.flag&unsafeRvFlagAddr == 0 { -// // // println(" ***** IS NOT addr") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// } else if urv.flag&unsafeRvFlagIndir != 0 { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** +flagIndir type: %v\n", rv.Type()) -// } -// // println("***** IS flagindir") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// } else { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** -flagIndir type: %v\n", rv.Type()) -// } -// // println("***** NOT flagindir") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } -// // println("***** default: delegating to rv.Interface()") -// // return rv.Interface() -// } - -// var staticM0 = make(map[string]uint64) -// var staticI0 = (int32)(-5) - -// func staticRv2iTest() { -// i0 := (int32)(-5) -// m0 := make(map[string]uint16) -// m0["1"] = 1 -// for _, i := range []interface{}{ -// (int)(7), -// (uint)(8), -// (int16)(-9), -// (uint16)(19), -// (uintptr)(77), -// (bool)(true), -// float32(-32.7), -// float64(64.9), -// complex(float32(19), 5), -// complex(float64(-32), 7), -// [4]uint64{1, 2, 3, 4}, -// (chan<- int)(nil), // chan, -// rv2i, // func -// io.Writer(ioutil.Discard), -// make(map[string]uint), -// (map[string]uint)(nil), -// staticM0, -// m0, -// &m0, -// i0, -// &i0, -// &staticI0, -// &staticM0, -// []uint32{6, 7, 8}, -// "abc", -// Raw{}, -// RawExt{}, -// &Raw{}, -// &RawExt{}, -// unsafe.Pointer(&i0), -// } { -// i2 := rv2i(reflect.ValueOf(i)) -// eq := reflect.DeepEqual(i, i2) -// fmt.Printf(">>>> %v == %v? %v\n", i, i2, eq) -// } -// // os.Exit(0) -// } - -// func init() { -// staticRv2iTest() -// } - -// func rv2i(rv reflect.Value) interface{} { -// if _USE_RV_INTERFACE || rv.Kind() == reflect.Interface || rv.CanAddr() { -// return rv.Interface() -// } -// // var i interface{} -// // ui := (*unsafeIntf)(unsafe.Pointer(&i)) -// var ui unsafeIntf -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // fmt.Printf("urv: flag: %b, typ: %b, ptr: %b\n", urv.flag, uintptr(urv.typ), uintptr(urv.ptr)) -// if (urv.flag&unsafeRvFlagKindMask)&unsafeRvKindDirectIface == 0 { -// if urv.flag&unsafeRvFlagAddr != 0 { -// println("***** indirect and addressable! Needs typed move - delegate to rv.Interface()") -// return rv.Interface() -// } -// println("****** indirect type/kind") -// ui.word = urv.ptr -// } else if urv.flag&unsafeRvFlagIndir != 0 { -// println("****** unsafe rv flag indir") -// ui.word = *(*unsafe.Pointer)(urv.ptr) -// } else { -// println("****** default: assign prt to word directly") -// ui.word = urv.ptr -// } -// // ui.word = urv.ptr -// ui.typ = urv.typ -// // fmt.Printf("(pointers) ui.typ: %p, word: %p\n", ui.typ, ui.word) -// // fmt.Printf("(binary) ui.typ: %b, word: %b\n", uintptr(ui.typ), uintptr(ui.word)) -// return *(*interface{})(unsafe.Pointer(&ui)) -// // return i -// } diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/json.go b/vendor/github.com/hashicorp/go-msgpack/codec/json.go deleted file mode 100644 index a731c8165e678..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/json.go +++ /dev/null @@ -1,1491 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// By default, this json support uses base64 encoding for bytes, because you cannot -// store and read any arbitrary string in json (only unicode). -// However, the user can configre how to encode/decode bytes. -// -// This library specifically supports UTF-8 for encoding and decoding only. -// -// Note that the library will happily encode/decode things which are not valid -// json e.g. a map[int64]string. We do it for consistency. With valid json, -// we will encode and decode appropriately. -// Users can specify their map type if necessary to force it. -// -// Note: -// - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently. -// We implement it here. - -// Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver -// MUST not call one-another. - -import ( - "bytes" - "encoding/base64" - "math" - "reflect" - "strconv" - "time" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -//-------------------------------- - -var jsonLiterals = [...]byte{ - '"', 't', 'r', 'u', 'e', '"', - '"', 'f', 'a', 'l', 's', 'e', '"', - '"', 'n', 'u', 'l', 'l', '"', -} - -const ( - jsonLitTrueQ = 0 - jsonLitTrue = 1 - jsonLitFalseQ = 6 - jsonLitFalse = 7 - // jsonLitNullQ = 13 - jsonLitNull = 14 -) - -var ( - jsonLiteral4True = jsonLiterals[jsonLitTrue+1 : jsonLitTrue+4] - jsonLiteral4False = jsonLiterals[jsonLitFalse+1 : jsonLitFalse+5] - jsonLiteral4Null = jsonLiterals[jsonLitNull+1 : jsonLitNull+4] -) - -const ( - jsonU4Chk2 = '0' - jsonU4Chk1 = 'a' - 10 - jsonU4Chk0 = 'A' - 10 - - jsonScratchArrayLen = 64 -) - -const ( - // If !jsonValidateSymbols, decoding will be faster, by skipping some checks: - // - If we see first character of null, false or true, - // do not validate subsequent characters. - // - e.g. if we see a n, assume null and skip next 3 characters, - // and do not validate they are ull. - // P.S. Do not expect a significant decoding boost from this. - jsonValidateSymbols = true - - jsonSpacesOrTabsLen = 128 - - jsonAlwaysReturnInternString = false -) - -var ( - // jsonTabs and jsonSpaces are used as caches for indents - jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte - - jsonCharHtmlSafeSet bitset256 - jsonCharSafeSet bitset256 - jsonCharWhitespaceSet bitset256 - jsonNumSet bitset256 -) - -func init() { - var i byte - for i = 0; i < jsonSpacesOrTabsLen; i++ { - jsonSpaces[i] = ' ' - jsonTabs[i] = '\t' - } - - // populate the safe values as true: note: ASCII control characters are (0-31) - // jsonCharSafeSet: all true except (0-31) " \ - // jsonCharHtmlSafeSet: all true except (0-31) " \ < > & - for i = 32; i < utf8.RuneSelf; i++ { - switch i { - case '"', '\\': - case '<', '>', '&': - jsonCharSafeSet.set(i) // = true - default: - jsonCharSafeSet.set(i) - jsonCharHtmlSafeSet.set(i) - } - } - for i = 0; i <= utf8.RuneSelf; i++ { - switch i { - case ' ', '\t', '\r', '\n': - jsonCharWhitespaceSet.set(i) - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-': - jsonNumSet.set(i) - } - } -} - -// ---------------- - -type jsonEncDriverTypical struct { - jsonEncDriver -} - -func (e *jsonEncDriverTypical) typical() {} - -func (e *jsonEncDriverTypical) WriteArrayStart(length int) { - e.w.writen1('[') - e.c = containerArrayStart -} - -func (e *jsonEncDriverTypical) WriteArrayElem() { - if e.c != containerArrayStart { - e.w.writen1(',') - } - e.c = containerArrayElem -} - -func (e *jsonEncDriverTypical) WriteArrayEnd() { - e.w.writen1(']') - e.c = containerArrayEnd -} - -func (e *jsonEncDriverTypical) WriteMapStart(length int) { - e.w.writen1('{') - e.c = containerMapStart -} - -func (e *jsonEncDriverTypical) WriteMapElemKey() { - if e.c != containerMapStart { - e.w.writen1(',') - } - e.c = containerMapKey -} - -func (e *jsonEncDriverTypical) WriteMapElemValue() { - e.w.writen1(':') - e.c = containerMapValue -} - -func (e *jsonEncDriverTypical) WriteMapEnd() { - e.w.writen1('}') - e.c = containerMapEnd -} - -func (e *jsonEncDriverTypical) EncodeBool(b bool) { - if b { - e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5]) - } -} - -func (e *jsonEncDriverTypical) EncodeFloat64(f float64) { - fmt, prec := jsonFloatStrconvFmtPrec(f) - e.w.writeb(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64)) -} - -func (e *jsonEncDriverTypical) EncodeInt(v int64) { - e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverTypical) EncodeUint(v uint64) { - e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverTypical) EncodeFloat32(f float32) { - e.EncodeFloat64(float64(f)) -} - -// func (e *jsonEncDriverTypical) atEndOfEncode() { -// if e.tw { -// e.w.writen1(' ') -// } -// } - -// ---------------- - -type jsonEncDriverGeneric struct { - jsonEncDriver - // ds string // indent string - di int8 // indent per - d bool // indenting? - dt bool // indent using tabs - dl uint16 // indent level - ks bool // map key as string - is byte // integer as string - _ byte // padding - _ [2]uint64 // padding -} - -// indent is done as below: -// - newline and indent are added before each mapKey or arrayElem -// - newline and indent are added before each ending, -// except there was no entry (so we can have {} or []) - -func (e *jsonEncDriverGeneric) reset() { - e.jsonEncDriver.reset() - e.d, e.dt, e.dl, e.di = false, false, 0, 0 - if e.h.Indent > 0 { - e.d = true - e.di = int8(e.h.Indent) - } else if e.h.Indent < 0 { - e.d = true - e.dt = true - e.di = int8(-e.h.Indent) - } - e.ks = e.h.MapKeyAsString - e.is = e.h.IntegerAsString -} - -func (e *jsonEncDriverGeneric) WriteArrayStart(length int) { - if e.d { - e.dl++ - } - e.w.writen1('[') - e.c = containerArrayStart -} - -func (e *jsonEncDriverGeneric) WriteArrayElem() { - if e.c != containerArrayStart { - e.w.writen1(',') - } - if e.d { - e.writeIndent() - } - e.c = containerArrayElem -} - -func (e *jsonEncDriverGeneric) WriteArrayEnd() { - if e.d { - e.dl-- - if e.c != containerArrayStart { - e.writeIndent() - } - } - e.w.writen1(']') - e.c = containerArrayEnd -} - -func (e *jsonEncDriverGeneric) WriteMapStart(length int) { - if e.d { - e.dl++ - } - e.w.writen1('{') - e.c = containerMapStart -} - -func (e *jsonEncDriverGeneric) WriteMapElemKey() { - if e.c != containerMapStart { - e.w.writen1(',') - } - if e.d { - e.writeIndent() - } - e.c = containerMapKey -} - -func (e *jsonEncDriverGeneric) WriteMapElemValue() { - if e.d { - e.w.writen2(':', ' ') - } else { - e.w.writen1(':') - } - e.c = containerMapValue -} - -func (e *jsonEncDriverGeneric) WriteMapEnd() { - if e.d { - e.dl-- - if e.c != containerMapStart { - e.writeIndent() - } - } - e.w.writen1('}') - e.c = containerMapEnd -} - -func (e *jsonEncDriverGeneric) writeIndent() { - e.w.writen1('\n') - x := int(e.di) * int(e.dl) - if e.dt { - for x > jsonSpacesOrTabsLen { - e.w.writeb(jsonTabs[:]) - x -= jsonSpacesOrTabsLen - } - e.w.writeb(jsonTabs[:x]) - } else { - for x > jsonSpacesOrTabsLen { - e.w.writeb(jsonSpaces[:]) - x -= jsonSpacesOrTabsLen - } - e.w.writeb(jsonSpaces[:x]) - } -} - -func (e *jsonEncDriverGeneric) EncodeBool(b bool) { - if e.ks && e.c == containerMapKey { - if b { - e.w.writeb(jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7]) - } - } else { - if b { - e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5]) - } - } -} - -func (e *jsonEncDriverGeneric) EncodeFloat64(f float64) { - // instead of using 'g', specify whether to use 'e' or 'f' - fmt, prec := jsonFloatStrconvFmtPrec(f) - - var blen int - if e.ks && e.c == containerMapKey { - blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, prec, 64)) - e.b[0] = '"' - e.b[blen-1] = '"' - } else { - blen = len(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64)) - } - e.w.writeb(e.b[:blen]) -} - -func (e *jsonEncDriverGeneric) EncodeInt(v int64) { - x := e.is - if x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) || (e.ks && e.c == containerMapKey) { - blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10)) - e.b[0] = '"' - e.b[blen-1] = '"' - e.w.writeb(e.b[:blen]) - return - } - e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverGeneric) EncodeUint(v uint64) { - x := e.is - if x == 'A' || x == 'L' && v > 1<<53 || (e.ks && e.c == containerMapKey) { - blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10)) - e.b[0] = '"' - e.b[blen-1] = '"' - e.w.writeb(e.b[:blen]) - return - } - e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverGeneric) EncodeFloat32(f float32) { - // e.encodeFloat(float64(f), 32) - // always encode all floats as IEEE 64-bit floating point. - // It also ensures that we can decode in full precision even if into a float32, - // as what is written is always to float64 precision. - e.EncodeFloat64(float64(f)) -} - -// func (e *jsonEncDriverGeneric) atEndOfEncode() { -// if e.tw { -// if e.d { -// e.w.writen1('\n') -// } else { -// e.w.writen1(' ') -// } -// } -// } - -// -------------------- - -type jsonEncDriver struct { - noBuiltInTypes - e *Encoder - h *JsonHandle - w *encWriterSwitch - se extWrapper - // ---- cpu cache line boundary? - bs []byte // scratch - // ---- cpu cache line boundary? - // scratch: encode time, etc. - // include scratch buffer and padding, but leave space for containerstate - b [jsonScratchArrayLen + 8 + 8 - 1]byte - c containerState - // _ [2]uint64 // padding -} - -func (e *jsonEncDriver) EncodeNil() { - // We always encode nil as just null (never in quotes) - // This allows us to easily decode if a nil in the json stream - // ie if initial token is n. - e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4]) - - // if e.h.MapKeyAsString && e.c == containerMapKey { - // e.w.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6]) - // } else { - // e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4]) - // } -} - -func (e *jsonEncDriver) EncodeTime(t time.Time) { - // Do NOT use MarshalJSON, as it allocates internally. - // instead, we call AppendFormat directly, using our scratch buffer (e.b) - if t.IsZero() { - e.EncodeNil() - } else { - e.b[0] = '"' - b := t.AppendFormat(e.b[1:1], time.RFC3339Nano) - e.b[len(b)+1] = '"' - e.w.writeb(e.b[:len(b)+2]) - } - // v, err := t.MarshalJSON(); if err != nil { e.e.error(err) } e.w.writeb(v) -} - -func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) { - if v := ext.ConvertExt(rv); v == nil { - e.EncodeNil() - } else { - en.encode(v) - } -} - -func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { - // only encodes re.Value (never re.Data) - if re.Value == nil { - e.EncodeNil() - } else { - en.encode(re.Value) - } -} - -func (e *jsonEncDriver) EncodeString(c charEncoding, v string) { - e.quoteStr(v) -} - -func (e *jsonEncDriver) EncodeStringEnc(c charEncoding, v string) { - e.quoteStr(v) -} - -func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - // if encoding raw bytes and RawBytesExt is configured, use it to encode - if v == nil { - e.EncodeNil() - return - } - if c == cRAW { - if e.se.InterfaceExt != nil { - e.EncodeExt(v, 0, &e.se, e.e) - return - } - - slen := base64.StdEncoding.EncodedLen(len(v)) + 2 - if cap(e.bs) >= slen { - e.bs = e.bs[:slen] - } else { - e.bs = make([]byte, slen) - } - e.bs[0] = '"' - base64.StdEncoding.Encode(e.bs[1:], v) - e.bs[slen-1] = '"' - e.w.writeb(e.bs) - } else { - e.quoteStr(stringView(v)) - } -} - -func (e *jsonEncDriver) EncodeStringBytesRaw(v []byte) { - // if encoding raw bytes and RawBytesExt is configured, use it to encode - if v == nil { - e.EncodeNil() - return - } - if e.se.InterfaceExt != nil { - e.EncodeExt(v, 0, &e.se, e.e) - return - } - - slen := base64.StdEncoding.EncodedLen(len(v)) + 2 - if cap(e.bs) >= slen { - e.bs = e.bs[:slen] - } else { - e.bs = make([]byte, slen) - } - e.bs[0] = '"' - base64.StdEncoding.Encode(e.bs[1:], v) - e.bs[slen-1] = '"' - e.w.writeb(e.bs) -} - -func (e *jsonEncDriver) EncodeAsis(v []byte) { - e.w.writeb(v) -} - -func (e *jsonEncDriver) quoteStr(s string) { - // adapted from std pkg encoding/json - const hex = "0123456789abcdef" - w := e.w - htmlasis := e.h.HTMLCharsAsIs - w.writen1('"') - var start int - for i, slen := 0, len(s); i < slen; { - // encode all bytes < 0x20 (except \r, \n). - // also encode < > & to prevent security holes when served to some browsers. - if b := s[i]; b < utf8.RuneSelf { - // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { - // if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) { - if jsonCharHtmlSafeSet.isset(b) || (htmlasis && jsonCharSafeSet.isset(b)) { - i++ - continue - } - if start < i { - w.writestr(s[start:i]) - } - switch b { - case '\\', '"': - w.writen2('\\', b) - case '\n': - w.writen2('\\', 'n') - case '\r': - w.writen2('\\', 'r') - case '\b': - w.writen2('\\', 'b') - case '\f': - w.writen2('\\', 'f') - case '\t': - w.writen2('\\', 't') - default: - w.writestr(`\u00`) - w.writen2(hex[b>>4], hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRuneInString(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - w.writestr(s[start:i]) - } - w.writestr(`\ufffd`) - i += size - start = i - continue - } - // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR. - // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally. - if c == '\u2028' || c == '\u2029' { - if start < i { - w.writestr(s[start:i]) - } - w.writestr(`\u202`) - w.writen1(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - w.writestr(s[start:]) - } - w.writen1('"') -} - -func (e *jsonEncDriver) atEndOfEncode() { - // if e.c == 0 { // scalar written, output space - // e.w.writen1(' ') - // } else if e.h.TermWhitespace { // container written, output new-line - // e.w.writen1('\n') - // } - if e.h.TermWhitespace { - if e.c == 0 { // scalar written, output space - e.w.writen1(' ') - } else { // container written, output new-line - e.w.writen1('\n') - } - } - - // e.c = 0 -} - -type jsonDecDriver struct { - noBuiltInTypes - d *Decoder - h *JsonHandle - r *decReaderSwitch - se extWrapper - - // ---- writable fields during execution --- *try* to keep in sep cache line - - c containerState - // tok is used to store the token read right after skipWhiteSpace. - tok uint8 - fnull bool // found null from appendStringAsBytes - bs []byte // scratch. Initialized from b. Used for parsing strings or numbers. - bstr [8]byte // scratch used for string \UXXX parsing - // ---- cpu cache line boundary? - b [jsonScratchArrayLen]byte // scratch 1, used for parsing strings or numbers or time.Time - b2 [jsonScratchArrayLen]byte // scratch 2, used only for readUntil, decNumBytes - - // _ [3]uint64 // padding - // n jsonNum -} - -// func jsonIsWS(b byte) bool { -// // return b == ' ' || b == '\t' || b == '\r' || b == '\n' -// return jsonCharWhitespaceSet.isset(b) -// } - -func (d *jsonDecDriver) uncacheRead() { - if d.tok != 0 { - d.r.unreadn1() - d.tok = 0 - } -} - -func (d *jsonDecDriver) ReadMapStart() int { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - const xc uint8 = '{' - if d.tok != xc { - d.d.errorf("read map - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapStart - return -1 -} - -func (d *jsonDecDriver) ReadArrayStart() int { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - const xc uint8 = '[' - if d.tok != xc { - d.d.errorf("read array - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerArrayStart - return -1 -} - -func (d *jsonDecDriver) CheckBreak() bool { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - return d.tok == '}' || d.tok == ']' -} - -// For the ReadXXX methods below, we could just delegate to helper functions -// readContainerState(c containerState, xc uint8, check bool) -// - ReadArrayElem would become: -// readContainerState(containerArrayElem, ',', d.c != containerArrayStart) -// -// However, until mid-stack inlining comes in go1.11 which supports inlining of -// one-liners, we explicitly write them all 5 out to elide the extra func call. -// -// TODO: For Go 1.11, if inlined, consider consolidating these. - -func (d *jsonDecDriver) ReadArrayElem() { - const xc uint8 = ',' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.c != containerArrayStart { - if d.tok != xc { - d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - } - d.c = containerArrayElem -} - -func (d *jsonDecDriver) ReadArrayEnd() { - const xc uint8 = ']' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerArrayEnd -} - -func (d *jsonDecDriver) ReadMapElemKey() { - const xc uint8 = ',' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.c != containerMapStart { - if d.tok != xc { - d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - } - d.c = containerMapKey -} - -func (d *jsonDecDriver) ReadMapElemValue() { - const xc uint8 = ':' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read map value - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapValue -} - -func (d *jsonDecDriver) ReadMapEnd() { - const xc uint8 = '}' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapEnd -} - -// func (d *jsonDecDriver) readLit(length, fromIdx uint8) { -// // length here is always less than 8 (literals are: null, true, false) -// bs := d.r.readx(int(length)) -// d.tok = 0 -// if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) { -// d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs) -// } -// } - -func (d *jsonDecDriver) readLit4True() { - bs := d.r.readx(3) - d.tok = 0 - if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4True) { - d.d.errorf("expecting %s: got %s", jsonLiteral4True, bs) - } -} - -func (d *jsonDecDriver) readLit4False() { - bs := d.r.readx(4) - d.tok = 0 - if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4False) { - d.d.errorf("expecting %s: got %s", jsonLiteral4False, bs) - } -} - -func (d *jsonDecDriver) readLit4Null() { - bs := d.r.readx(3) - d.tok = 0 - if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4Null) { - d.d.errorf("expecting %s: got %s", jsonLiteral4Null, bs) - } -} - -func (d *jsonDecDriver) TryDecodeAsNil() bool { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - // we shouldn't try to see if "null" was here, right? - // only the plain string: `null` denotes a nil (ie not quotes) - if d.tok == 'n' { - d.readLit4Null() - return true - } - return false -} - -func (d *jsonDecDriver) DecodeBool() (v bool) { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - fquot := d.c == containerMapKey && d.tok == '"' - if fquot { - d.tok = d.r.readn1() - } - switch d.tok { - case 'f': - d.readLit4False() - // v = false - case 't': - d.readLit4True() - v = true - default: - d.d.errorf("decode bool: got first char %c", d.tok) - // v = false // "unreachable" - } - if fquot { - d.r.readn1() - } - return -} - -func (d *jsonDecDriver) DecodeTime() (t time.Time) { - // read string, and pass the string into json.unmarshal - d.appendStringAsBytes() - if d.fnull { - return - } - t, err := time.Parse(time.RFC3339, stringView(d.bs)) - if err != nil { - d.d.errorv(err) - } - return -} - -func (d *jsonDecDriver) ContainerType() (vt valueType) { - // check container type by checking the first char - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - - // optimize this, so we don't do 4 checks but do one computation. - // return jsonContainerSet[d.tok] - - // ContainerType is mostly called for Map and Array, - // so this conditional is good enough (max 2 checks typically) - if b := d.tok; b == '{' { - return valueTypeMap - } else if b == '[' { - return valueTypeArray - } else if b == 'n' { - return valueTypeNil - } else if b == '"' { - return valueTypeString - } - return valueTypeUnset -} - -func (d *jsonDecDriver) decNumBytes() (bs []byte) { - // stores num bytes in d.bs - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok == '"' { - bs = d.r.readUntil(d.b2[:0], '"') - bs = bs[:len(bs)-1] - } else { - d.r.unreadn1() - bs = d.r.readTo(d.bs[:0], &jsonNumSet) - } - d.tok = 0 - return bs -} - -func (d *jsonDecDriver) DecodeUint64() (u uint64) { - bs := d.decNumBytes() - if len(bs) == 0 { - return - } - n, neg, badsyntax, overflow := jsonParseInteger(bs) - if overflow { - d.d.errorf("overflow parsing unsigned integer: %s", bs) - } else if neg { - d.d.errorf("minus found parsing unsigned integer: %s", bs) - } else if badsyntax { - // fallback: try to decode as float, and cast - n = d.decUint64ViaFloat(stringView(bs)) - } - return n -} - -func (d *jsonDecDriver) DecodeInt64() (i int64) { - const cutoff = uint64(1 << uint(64-1)) - bs := d.decNumBytes() - if len(bs) == 0 { - return - } - n, neg, badsyntax, overflow := jsonParseInteger(bs) - if overflow { - d.d.errorf("overflow parsing integer: %s", bs) - } else if badsyntax { - // d.d.errorf("invalid syntax for integer: %s", bs) - // fallback: try to decode as float, and cast - if neg { - n = d.decUint64ViaFloat(stringView(bs[1:])) - } else { - n = d.decUint64ViaFloat(stringView(bs)) - } - } - if neg { - if n > cutoff { - d.d.errorf("overflow parsing integer: %s", bs) - } - i = -(int64(n)) - } else { - if n >= cutoff { - d.d.errorf("overflow parsing integer: %s", bs) - } - i = int64(n) - } - return -} - -func (d *jsonDecDriver) decUint64ViaFloat(s string) (u uint64) { - if len(s) == 0 { - return - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - d.d.errorf("invalid syntax for integer: %s", s) - // d.d.errorv(err) - } - fi, ff := math.Modf(f) - if ff > 0 { - d.d.errorf("fractional part found parsing integer: %s", s) - } else if fi > float64(math.MaxUint64) { - d.d.errorf("overflow parsing integer: %s", s) - } - return uint64(fi) -} - -func (d *jsonDecDriver) DecodeFloat64() (f float64) { - bs := d.decNumBytes() - if len(bs) == 0 { - return - } - f, err := strconv.ParseFloat(stringView(bs), 64) - if err != nil { - d.d.errorv(err) - } - return -} - -func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if ext == nil { - re := rv.(*RawExt) - re.Tag = xtag - d.d.decode(&re.Value) - } else { - var v interface{} - d.d.decode(&v) - ext.UpdateExt(rv, v) - } - return -} - -func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode. - if d.se.InterfaceExt != nil { - bsOut = bs - d.DecodeExt(&bsOut, 0, &d.se) - return - } - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.tok == '[' { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - d.appendStringAsBytes() - // base64 encodes []byte{} as "", and we encode nil []byte as null. - // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}. - // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs. - // However, it sets a fnull field to true, so we can check if a null was found. - if len(d.bs) == 0 { - if d.fnull { - return nil - } - return []byte{} - } - bs0 := d.bs - slen := base64.StdEncoding.DecodedLen(len(bs0)) - if slen <= cap(bs) { - bsOut = bs[:slen] - } else if zerocopy && slen <= cap(d.b2) { - bsOut = d.b2[:slen] - } else { - bsOut = make([]byte, slen) - } - slen2, err := base64.StdEncoding.Decode(bsOut, bs0) - if err != nil { - d.d.errorf("error decoding base64 binary '%s': %v", bs0, err) - return nil - } - if slen != slen2 { - bsOut = bsOut[:slen2] - } - return -} - -func (d *jsonDecDriver) DecodeString() (s string) { - d.appendStringAsBytes() - return d.bsToString() -} - -func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) { - d.appendStringAsBytes() - return d.bs -} - -func (d *jsonDecDriver) appendStringAsBytes() { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - - d.fnull = false - if d.tok != '"' { - // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok) - // handle non-string scalar: null, true, false or a number - switch d.tok { - case 'n': - d.readLit4Null() - d.bs = d.bs[:0] - d.fnull = true - case 'f': - d.readLit4False() - d.bs = d.bs[:5] - copy(d.bs, "false") - case 't': - d.readLit4True() - d.bs = d.bs[:4] - copy(d.bs, "true") - default: - // try to parse a valid number - bs := d.decNumBytes() - if len(bs) <= cap(d.bs) { - d.bs = d.bs[:len(bs)] - } else { - d.bs = make([]byte, len(bs)) - } - copy(d.bs, bs) - } - return - } - - d.tok = 0 - r := d.r - var cs = r.readUntil(d.b2[:0], '"') - var cslen = uint(len(cs)) - var c uint8 - v := d.bs[:0] - // append on each byte seen can be expensive, so we just - // keep track of where we last read a contiguous set of - // non-special bytes (using cursor variable), - // and when we see a special byte - // e.g. end-of-slice, " or \, - // we will append the full range into the v slice before proceeding - var i, cursor uint - for { - if i == cslen { - v = append(v, cs[cursor:]...) - cs = r.readUntil(d.b2[:0], '"') - cslen = uint(len(cs)) - i, cursor = 0, 0 - } - c = cs[i] - if c == '"' { - v = append(v, cs[cursor:i]...) - break - } - if c != '\\' { - i++ - continue - } - v = append(v, cs[cursor:i]...) - i++ - c = cs[i] - switch c { - case '"', '\\', '/', '\'': - v = append(v, c) - case 'b': - v = append(v, '\b') - case 'f': - v = append(v, '\f') - case 'n': - v = append(v, '\n') - case 'r': - v = append(v, '\r') - case 't': - v = append(v, '\t') - case 'u': - var r rune - var rr uint32 - if cslen < i+4 { - d.d.errorf("need at least 4 more bytes for unicode sequence") - } - var j uint - for _, c = range cs[i+1 : i+5] { // bounds-check-elimination - // best to use explicit if-else - // - not a table, etc which involve memory loads, array lookup with bounds checks, etc - if c >= '0' && c <= '9' { - rr = rr*16 + uint32(c-jsonU4Chk2) - } else if c >= 'a' && c <= 'f' { - rr = rr*16 + uint32(c-jsonU4Chk1) - } else if c >= 'A' && c <= 'F' { - rr = rr*16 + uint32(c-jsonU4Chk0) - } else { - r = unicode.ReplacementChar - i += 4 - goto encode_rune - } - } - r = rune(rr) - i += 4 - if utf16.IsSurrogate(r) { - if len(cs) >= int(i+6) { - var cx = cs[i+1:][:6:6] // [:6] affords bounds-check-elimination - if cx[0] == '\\' && cx[1] == 'u' { - i += 2 - var rr1 uint32 - for j = 2; j < 6; j++ { - c = cx[j] - if c >= '0' && c <= '9' { - rr = rr*16 + uint32(c-jsonU4Chk2) - } else if c >= 'a' && c <= 'f' { - rr = rr*16 + uint32(c-jsonU4Chk1) - } else if c >= 'A' && c <= 'F' { - rr = rr*16 + uint32(c-jsonU4Chk0) - } else { - r = unicode.ReplacementChar - i += 4 - goto encode_rune - } - } - r = utf16.DecodeRune(r, rune(rr1)) - i += 4 - goto encode_rune - } - } - r = unicode.ReplacementChar - } - encode_rune: - w2 := utf8.EncodeRune(d.bstr[:], r) - v = append(v, d.bstr[:w2]...) - default: - d.d.errorf("unsupported escaped value: %c", c) - } - i++ - cursor = i - } - d.bs = v -} - -func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) { - const cutoff = uint64(1 << uint(64-1)) - - var n uint64 - var neg, badsyntax, overflow bool - - if len(bs) == 0 { - if d.h.PreferFloat { - z.v = valueTypeFloat - z.f = 0 - } else if d.h.SignedInteger { - z.v = valueTypeInt - z.i = 0 - } else { - z.v = valueTypeUint - z.u = 0 - } - return - } - if d.h.PreferFloat { - goto F - } - n, neg, badsyntax, overflow = jsonParseInteger(bs) - if badsyntax || overflow { - goto F - } - if neg { - if n > cutoff { - goto F - } - z.v = valueTypeInt - z.i = -(int64(n)) - } else if d.h.SignedInteger { - if n >= cutoff { - goto F - } - z.v = valueTypeInt - z.i = int64(n) - } else { - z.v = valueTypeUint - z.u = n - } - return -F: - z.v = valueTypeFloat - z.f, err = strconv.ParseFloat(stringView(bs), 64) - return -} - -func (d *jsonDecDriver) bsToString() string { - // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key - if jsonAlwaysReturnInternString || d.c == containerMapKey { - return d.d.string(d.bs) - } - return string(d.bs) -} - -func (d *jsonDecDriver) DecodeNaked() { - z := d.d.naked() - // var decodeFurther bool - - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - switch d.tok { - case 'n': - d.readLit4Null() - z.v = valueTypeNil - case 'f': - d.readLit4False() - z.v = valueTypeBool - z.b = false - case 't': - d.readLit4True() - z.v = valueTypeBool - z.b = true - case '{': - z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart - case '[': - z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart - case '"': - // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first - d.appendStringAsBytes() - if len(d.bs) > 0 && d.c == containerMapKey && d.h.MapKeyAsString { - switch stringView(d.bs) { - case "null": - z.v = valueTypeNil - case "true": - z.v = valueTypeBool - z.b = true - case "false": - z.v = valueTypeBool - z.b = false - default: - // check if a number: float, int or uint - if err := d.nakedNum(z, d.bs); err != nil { - z.v = valueTypeString - z.s = d.bsToString() - } - } - } else { - z.v = valueTypeString - z.s = d.bsToString() - } - default: // number - bs := d.decNumBytes() - if len(bs) == 0 { - d.d.errorf("decode number from empty string") - return - } - if err := d.nakedNum(z, bs); err != nil { - d.d.errorf("decode number from %s: %v", bs, err) - return - } - } - // if decodeFurther { - // d.s.sc.retryRead() - // } -} - -//---------------------- - -// JsonHandle is a handle for JSON encoding format. -// -// Json is comprehensively supported: -// - decodes numbers into interface{} as int, uint or float64 -// based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc. -// - decode integers from float formatted numbers e.g. 1.27e+8 -// - decode any json value (numbers, bool, etc) from quoted strings -// - configurable way to encode/decode []byte . -// by default, encodes and decodes []byte using base64 Std Encoding -// - UTF-8 support for encoding and decoding -// -// It has better performance than the json library in the standard library, -// by leveraging the performance improvements of the codec library. -// -// In addition, it doesn't read more bytes than necessary during a decode, which allows -// reading multiple values from a stream containing json and non-json content. -// For example, a user can read a json value, then a cbor value, then a msgpack value, -// all from the same stream in sequence. -// -// Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are -// not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD. -type JsonHandle struct { - textEncodingType - BasicHandle - - // Indent indicates how a value is encoded. - // - If positive, indent by that number of spaces. - // - If negative, indent by that number of tabs. - Indent int8 - - // IntegerAsString controls how integers (signed and unsigned) are encoded. - // - // Per the JSON Spec, JSON numbers are 64-bit floating point numbers. - // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision. - // This can be mitigated by configuring how to encode integers. - // - // IntegerAsString interpretes the following values: - // - if 'L', then encode integers > 2^53 as a json string. - // - if 'A', then encode all integers as a json string - // containing the exact integer representation as a decimal. - // - else encode all integers as a json number (default) - IntegerAsString byte - - // HTMLCharsAsIs controls how to encode some special characters to html: < > & - // - // By default, we encode them as \uXXX - // to prevent security holes when served from some browsers. - HTMLCharsAsIs bool - - // PreferFloat says that we will default to decoding a number as a float. - // If not set, we will examine the characters of the number and decode as an - // integer type if it doesn't have any of the characters [.eE]. - PreferFloat bool - - // TermWhitespace says that we add a whitespace character - // at the end of an encoding. - // - // The whitespace is important, especially if using numbers in a context - // where multiple items are written to a stream. - TermWhitespace bool - - // MapKeyAsString says to encode all map keys as strings. - // - // Use this to enforce strict json output. - // The only caveat is that nil value is ALWAYS written as null (never as "null") - MapKeyAsString bool - - // _ [2]byte // padding - - // Note: below, we store hardly-used items e.g. RawBytesExt is cached in the (en|de)cDriver. - - // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way. - // If not configured, raw bytes are encoded to/from base64 text. - RawBytesExt InterfaceExt - - _ [2]uint64 // padding -} - -// Name returns the name of the handle: json -func (h *JsonHandle) Name() string { return "json" } -func (h *JsonHandle) hasElemSeparators() bool { return true } -func (h *JsonHandle) typical() bool { - return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L' -} - -type jsonTypical interface { - typical() -} - -func (h *JsonHandle) recreateEncDriver(ed encDriver) (v bool) { - _, v = ed.(jsonTypical) - return v != h.typical() -} - -// SetInterfaceExt sets an extension -func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext}) -} - -func (h *JsonHandle) newEncDriver(e *Encoder) (ee encDriver) { - var hd *jsonEncDriver - if h.typical() { - var v jsonEncDriverTypical - ee = &v - hd = &v.jsonEncDriver - } else { - var v jsonEncDriverGeneric - ee = &v - hd = &v.jsonEncDriver - } - hd.e, hd.h, hd.bs = e, h, hd.b[:0] - hd.se.BytesExt = bytesExtFailer{} - ee.reset() - return -} - -func (h *JsonHandle) newDecDriver(d *Decoder) decDriver { - // d := jsonDecDriver{r: r.(*bytesDecReader), h: h} - hd := jsonDecDriver{d: d, h: h} - hd.se.BytesExt = bytesExtFailer{} - hd.bs = hd.b[:0] - hd.reset() - return &hd -} - -func (e *jsonEncDriver) reset() { - e.w = e.e.w - e.se.InterfaceExt = e.h.RawBytesExt - if e.bs != nil { - e.bs = e.bs[:0] - } - e.c = 0 -} - -func (d *jsonDecDriver) reset() { - d.r = d.d.r - d.se.InterfaceExt = d.h.RawBytesExt - if d.bs != nil { - d.bs = d.bs[:0] - } - d.c, d.tok = 0, 0 - // d.n.reset() -} - -func jsonFloatStrconvFmtPrec(f float64) (fmt byte, prec int) { - prec = -1 - var abs = math.Abs(f) - if abs != 0 && (abs < 1e-6 || abs >= 1e21) { - fmt = 'e' - } else { - fmt = 'f' - // set prec to 1 iff mod is 0. - // better than using jsonIsFloatBytesB2 to check if a . or E in the float bytes. - // this ensures that every float has an e or .0 in it. - if abs <= 1 { - if abs == 0 || abs == 1 { - prec = 1 - } - } else if _, mod := math.Modf(abs); mod == 0 { - prec = 1 - } - } - return -} - -// custom-fitted version of strconv.Parse(Ui|I)nt. -// Also ensures we don't have to search for .eE to determine if a float or not. -// Note: s CANNOT be a zero-length slice. -func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) { - const maxUint64 = (1<<64 - 1) - const cutoff = maxUint64/10 + 1 - - if len(s) == 0 { // bounds-check-elimination - // treat empty string as zero value - // badSyntax = true - return - } - switch s[0] { - case '+': - s = s[1:] - case '-': - s = s[1:] - neg = true - } - for _, c := range s { - if c < '0' || c > '9' { - badSyntax = true - return - } - // unsigned integers don't overflow well on multiplication, so check cutoff here - // e.g. (maxUint64-5)*10 doesn't overflow well ... - if n >= cutoff { - overflow = true - return - } - n *= 10 - n1 := n + uint64(c-'0') - if n1 < n || n1 > maxUint64 { - overflow = true - return - } - n = n1 - } - return -} - -var _ decDriver = (*jsonDecDriver)(nil) -var _ encDriver = (*jsonEncDriverGeneric)(nil) -var _ encDriver = (*jsonEncDriverTypical)(nil) -var _ jsonTypical = (*jsonEncDriverTypical)(nil) diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/mammoth-test.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/mammoth-test.go.tmpl deleted file mode 100644 index c598cc73a5eba..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/mammoth-test.go.tmpl +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from mammoth-test.go.tmpl - DO NOT EDIT. - -package codec - -import "testing" -import "fmt" -import "reflect" - -// TestMammoth has all the different paths optimized in fast-path -// It has all the primitives, slices and maps. -// -// For each of those types, it has a pointer and a non-pointer field. - -func init() { _ = fmt.Printf } // so we can include fmt as needed - -type TestMammoth struct { - -{{range .Values }}{{if .Primitive }}{{/* -*/}}{{ .MethodNamePfx "F" true }} {{ .Primitive }} -{{ .MethodNamePfx "Fptr" true }} *{{ .Primitive }} -{{end}}{{end}} - -{{range .Values }}{{if not .Primitive }}{{if not .MapKey }}{{/* -*/}}{{ .MethodNamePfx "F" false }} []{{ .Elem }} -{{ .MethodNamePfx "Fptr" false }} *[]{{ .Elem }} -{{end}}{{end}}{{end}} - -{{range .Values }}{{if not .Primitive }}{{if .MapKey }}{{/* -*/}}{{ .MethodNamePfx "F" false }} map[{{ .MapKey }}]{{ .Elem }} -{{ .MethodNamePfx "Fptr" false }} *map[{{ .MapKey }}]{{ .Elem }} -{{end}}{{end}}{{end}} - -} - -{{range .Values }}{{if not .Primitive }}{{if not .MapKey }}{{/* -*/}} type {{ .MethodNamePfx "typMbs" false }} []{{ .Elem }} -func (_ {{ .MethodNamePfx "typMbs" false }}) MapBySlice() { } -{{end}}{{end}}{{end}} - -{{range .Values }}{{if not .Primitive }}{{if .MapKey }}{{/* -*/}} type {{ .MethodNamePfx "typMap" false }} map[{{ .MapKey }}]{{ .Elem }} -{{end}}{{end}}{{end}} - -func doTestMammothSlices(t *testing.T, h Handle) { -{{range $i, $e := .Values }}{{if not .Primitive }}{{if not .MapKey }}{{/* -*/}} - var v{{$i}}va [8]{{ .Elem }} - for _, v := range [][]{{ .Elem }}{ nil, {}, { {{ nonzerocmd .Elem }}, {{ zerocmd .Elem }}, {{ zerocmd .Elem }}, {{ nonzerocmd .Elem }} } } { {{/* - // fmt.Printf(">>>> running mammoth slice v{{$i}}: %v\n", v) - // - encode value to some []byte - // - decode into a length-wise-equal []byte - // - check if equal to initial slice - // - encode ptr to the value - // - check if encode bytes are same - // - decode into ptrs to: nil, then 1-elem slice, equal-length, then large len slice - // - decode into non-addressable slice of equal length, then larger len - // - for each decode, compare elem-by-elem to the original slice - // - - // - rinse and repeat for a MapBySlice version - // - - */}} - var v{{$i}}v1, v{{$i}}v2 []{{ .Elem }} - v{{$i}}v1 = v - bs{{$i}} := testMarshalErr(v{{$i}}v1, h, t, "enc-slice-v{{$i}}") - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make([]{{ .Elem }}, len(v)) } - testUnmarshalErr(v{{$i}}v2, bs{{$i}}, h, t, "dec-slice-v{{$i}}") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}") - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make([]{{ .Elem }}, len(v)) } - testUnmarshalErr(reflect.ValueOf(v{{$i}}v2), bs{{$i}}, h, t, "dec-slice-v{{$i}}-noaddr") // non-addressable value - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}-noaddr") - // ... - bs{{$i}} = testMarshalErr(&v{{$i}}v1, h, t, "enc-slice-v{{$i}}-p") - v{{$i}}v2 = nil - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-slice-v{{$i}}-p") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}-p") - v{{$i}}va = [8]{{ .Elem }}{} // clear the array - v{{$i}}v2 = v{{$i}}va[:1:1] - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-slice-v{{$i}}-p-1") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}-p-1") - v{{$i}}va = [8]{{ .Elem }}{} // clear the array - v{{$i}}v2 = v{{$i}}va[:len(v{{$i}}v1):len(v{{$i}}v1)] - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-slice-v{{$i}}-p-len") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}-p-len") - v{{$i}}va = [8]{{ .Elem }}{} // clear the array - v{{$i}}v2 = v{{$i}}va[:] - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-slice-v{{$i}}-p-cap") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-slice-v{{$i}}-p-cap") - if len(v{{$i}}v1) > 1 { - v{{$i}}va = [8]{{ .Elem }}{} // clear the array - testUnmarshalErr((&v{{$i}}va)[:len(v{{$i}}v1)], bs{{$i}}, h, t, "dec-slice-v{{$i}}-p-len-noaddr") - testDeepEqualErr(v{{$i}}v1, v{{$i}}va[:len(v{{$i}}v1)], t, "equal-slice-v{{$i}}-p-len-noaddr") - v{{$i}}va = [8]{{ .Elem }}{} // clear the array - testUnmarshalErr((&v{{$i}}va)[:], bs{{$i}}, h, t, "dec-slice-v{{$i}}-p-cap-noaddr") - testDeepEqualErr(v{{$i}}v1, v{{$i}}va[:len(v{{$i}}v1)], t, "equal-slice-v{{$i}}-p-cap-noaddr") - } - // ... - var v{{$i}}v3, v{{$i}}v4 {{ .MethodNamePfx "typMbs" false }} - v{{$i}}v2 = nil - if v != nil { v{{$i}}v2 = make([]{{ .Elem }}, len(v)) } - v{{$i}}v3 = {{ .MethodNamePfx "typMbs" false }}(v{{$i}}v1) - v{{$i}}v4 = {{ .MethodNamePfx "typMbs" false }}(v{{$i}}v2) - bs{{$i}} = testMarshalErr(v{{$i}}v3, h, t, "enc-slice-v{{$i}}-custom") - testUnmarshalErr(v{{$i}}v4, bs{{$i}}, h, t, "dec-slice-v{{$i}}-custom") - testDeepEqualErr(v{{$i}}v3, v{{$i}}v4, t, "equal-slice-v{{$i}}-custom") - bs{{$i}} = testMarshalErr(&v{{$i}}v3, h, t, "enc-slice-v{{$i}}-custom-p") - v{{$i}}v2 = nil - v{{$i}}v4 = {{ .MethodNamePfx "typMbs" false }}(v{{$i}}v2) - testUnmarshalErr(&v{{$i}}v4, bs{{$i}}, h, t, "dec-slice-v{{$i}}-custom-p") - testDeepEqualErr(v{{$i}}v3, v{{$i}}v4, t, "equal-slice-v{{$i}}-custom-p") - } -{{end}}{{end}}{{end}} -} - -func doTestMammothMaps(t *testing.T, h Handle) { -{{range $i, $e := .Values }}{{if not .Primitive }}{{if .MapKey }}{{/* -*/}} - for _, v := range []map[{{ .MapKey }}]{{ .Elem }}{ nil, {}, { {{ nonzerocmd .MapKey }}:{{ zerocmd .Elem }} {{if ne "bool" .MapKey}}, {{ nonzerocmd .MapKey }}:{{ nonzerocmd .Elem }} {{end}} } } { - // fmt.Printf(">>>> running mammoth map v{{$i}}: %v\n", v) - var v{{$i}}v1, v{{$i}}v2 map[{{ .MapKey }}]{{ .Elem }} - v{{$i}}v1 = v - bs{{$i}} := testMarshalErr(v{{$i}}v1, h, t, "enc-map-v{{$i}}") - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make(map[{{ .MapKey }}]{{ .Elem }}, len(v)) } // reset map - testUnmarshalErr(v{{$i}}v2, bs{{$i}}, h, t, "dec-map-v{{$i}}") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-map-v{{$i}}") - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make(map[{{ .MapKey }}]{{ .Elem }}, len(v)) } // reset map - testUnmarshalErr(reflect.ValueOf(v{{$i}}v2), bs{{$i}}, h, t, "dec-map-v{{$i}}-noaddr") // decode into non-addressable map value - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-map-v{{$i}}-noaddr") - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make(map[{{ .MapKey }}]{{ .Elem }}, len(v)) } // reset map - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-map-v{{$i}}-p-len") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-map-v{{$i}}-p-len") - bs{{$i}} = testMarshalErr(&v{{$i}}v1, h, t, "enc-map-v{{$i}}-p") - v{{$i}}v2 = nil - testUnmarshalErr(&v{{$i}}v2, bs{{$i}}, h, t, "dec-map-v{{$i}}-p-nil") - testDeepEqualErr(v{{$i}}v1, v{{$i}}v2, t, "equal-map-v{{$i}}-p-nil") - // ... - if v == nil { v{{$i}}v2 = nil } else { v{{$i}}v2 = make(map[{{ .MapKey }}]{{ .Elem }}, len(v)) } // reset map - var v{{$i}}v3, v{{$i}}v4 {{ .MethodNamePfx "typMap" false }} - v{{$i}}v3 = {{ .MethodNamePfx "typMap" false }}(v{{$i}}v1) - v{{$i}}v4 = {{ .MethodNamePfx "typMap" false }}(v{{$i}}v2) - bs{{$i}} = testMarshalErr(v{{$i}}v3, h, t, "enc-map-v{{$i}}-custom") - testUnmarshalErr(v{{$i}}v4, bs{{$i}}, h, t, "dec-map-v{{$i}}-p-len") - testDeepEqualErr(v{{$i}}v3, v{{$i}}v4, t, "equal-map-v{{$i}}-p-len") - } -{{end}}{{end}}{{end}} - -} - -func doTestMammothMapsAndSlices(t *testing.T, h Handle) { - doTestMammothSlices(t, h) - doTestMammothMaps(t, h) -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/mammoth2-test.go.tmpl b/vendor/github.com/hashicorp/go-msgpack/codec/mammoth2-test.go.tmpl deleted file mode 100644 index 71eaf618a50a6..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/mammoth2-test.go.tmpl +++ /dev/null @@ -1,94 +0,0 @@ -// +build !notfastpath - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from mammoth2-test.go.tmpl - DO NOT EDIT. - -package codec - -// Increase codecoverage by covering all the codecgen paths, in fast-path and gen-helper.go.... -// -// Add: -// - test file for creating a mammoth generated file as _mammoth_generated.go -// - generate a second mammoth files in a different file: mammoth2_generated_test.go -// - mammoth-test.go.tmpl will do this -// - run codecgen on it, into mammoth2_codecgen_generated_test.go (no build tags) -// - as part of TestMammoth, run it also -// - this will cover all the codecgen, gen-helper, etc in one full run -// - check in mammoth* files into github also -// - then -// -// Now, add some types: -// - some that implement BinaryMarshal, TextMarshal, JSONMarshal, and one that implements none of it -// - create a wrapper type that includes TestMammoth2, with it in slices, and maps, and the custom types -// - this wrapper object is what we work encode/decode (so that the codecgen methods are called) - - -// import "encoding/binary" -import "fmt" - -type TestMammoth2 struct { - -{{range .Values }}{{if .Primitive }}{{/* -*/}}{{ .MethodNamePfx "F" true }} {{ .Primitive }} -{{ .MethodNamePfx "Fptr" true }} *{{ .Primitive }} -{{end}}{{end}} - -{{range .Values }}{{if not .Primitive }}{{if not .MapKey }}{{/* -*/}}{{ .MethodNamePfx "F" false }} []{{ .Elem }} -{{ .MethodNamePfx "Fptr" false }} *[]{{ .Elem }} -{{end}}{{end}}{{end}} - -{{range .Values }}{{if not .Primitive }}{{if .MapKey }}{{/* -*/}}{{ .MethodNamePfx "F" false }} map[{{ .MapKey }}]{{ .Elem }} -{{ .MethodNamePfx "Fptr" false }} *map[{{ .MapKey }}]{{ .Elem }} -{{end}}{{end}}{{end}} - -} - -// ----------- - -type testMammoth2Binary uint64 -func (x testMammoth2Binary) MarshalBinary() (data []byte, err error) { -data = make([]byte, 8) -bigen.PutUint64(data, uint64(x)) -return -} -func (x *testMammoth2Binary) UnmarshalBinary(data []byte) (err error) { -*x = testMammoth2Binary(bigen.Uint64(data)) -return -} - -type testMammoth2Text uint64 -func (x testMammoth2Text) MarshalText() (data []byte, err error) { -data = []byte(fmt.Sprintf("%b", uint64(x))) -return -} -func (x *testMammoth2Text) UnmarshalText(data []byte) (err error) { -_, err = fmt.Sscanf(string(data), "%b", (*uint64)(x)) -return -} - -type testMammoth2Json uint64 -func (x testMammoth2Json) MarshalJSON() (data []byte, err error) { -data = []byte(fmt.Sprintf("%v", uint64(x))) -return -} -func (x *testMammoth2Json) UnmarshalJSON(data []byte) (err error) { -_, err = fmt.Sscanf(string(data), "%v", (*uint64)(x)) -return -} - -type testMammoth2Basic [4]uint64 - -type TestMammoth2Wrapper struct { - V TestMammoth2 - T testMammoth2Text - B testMammoth2Binary - J testMammoth2Json - C testMammoth2Basic - M map[testMammoth2Basic]TestMammoth2 - L []TestMammoth2 - A [4]int64 -} diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go index bf311a6778a27..da0500d19223b 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go @@ -1,5 +1,5 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. /* MSGPACK @@ -15,8 +15,8 @@ For compatibility with behaviour of msgpack-c reference implementation: - Go intX (<0) IS ENCODED AS msgpack -ve fixnum, signed -*/ +*/ package codec import ( @@ -24,144 +24,59 @@ import ( "io" "math" "net/rpc" - "reflect" - "time" ) const ( mpPosFixNumMin byte = 0x00 - mpPosFixNumMax byte = 0x7f - mpFixMapMin byte = 0x80 - mpFixMapMax byte = 0x8f - mpFixArrayMin byte = 0x90 - mpFixArrayMax byte = 0x9f - mpFixStrMin byte = 0xa0 - mpFixStrMax byte = 0xbf - mpNil byte = 0xc0 - _ byte = 0xc1 - mpFalse byte = 0xc2 - mpTrue byte = 0xc3 - mpFloat byte = 0xca - mpDouble byte = 0xcb - mpUint8 byte = 0xcc - mpUint16 byte = 0xcd - mpUint32 byte = 0xce - mpUint64 byte = 0xcf - mpInt8 byte = 0xd0 - mpInt16 byte = 0xd1 - mpInt32 byte = 0xd2 - mpInt64 byte = 0xd3 + mpPosFixNumMax = 0x7f + mpFixMapMin = 0x80 + mpFixMapMax = 0x8f + mpFixArrayMin = 0x90 + mpFixArrayMax = 0x9f + mpFixStrMin = 0xa0 + mpFixStrMax = 0xbf + mpNil = 0xc0 + _ = 0xc1 + mpFalse = 0xc2 + mpTrue = 0xc3 + mpFloat = 0xca + mpDouble = 0xcb + mpUint8 = 0xcc + mpUint16 = 0xcd + mpUint32 = 0xce + mpUint64 = 0xcf + mpInt8 = 0xd0 + mpInt16 = 0xd1 + mpInt32 = 0xd2 + mpInt64 = 0xd3 // extensions below - mpBin8 byte = 0xc4 - mpBin16 byte = 0xc5 - mpBin32 byte = 0xc6 - mpExt8 byte = 0xc7 - mpExt16 byte = 0xc8 - mpExt32 byte = 0xc9 - mpFixExt1 byte = 0xd4 - mpFixExt2 byte = 0xd5 - mpFixExt4 byte = 0xd6 - mpFixExt8 byte = 0xd7 - mpFixExt16 byte = 0xd8 - - mpStr8 byte = 0xd9 // new - mpStr16 byte = 0xda - mpStr32 byte = 0xdb - - mpArray16 byte = 0xdc - mpArray32 byte = 0xdd - - mpMap16 byte = 0xde - mpMap32 byte = 0xdf - - mpNegFixNumMin byte = 0xe0 - mpNegFixNumMax byte = 0xff + mpBin8 = 0xc4 + mpBin16 = 0xc5 + mpBin32 = 0xc6 + mpExt8 = 0xc7 + mpExt16 = 0xc8 + mpExt32 = 0xc9 + mpFixExt1 = 0xd4 + mpFixExt2 = 0xd5 + mpFixExt4 = 0xd6 + mpFixExt8 = 0xd7 + mpFixExt16 = 0xd8 + + mpStr8 = 0xd9 // new + mpStr16 = 0xda + mpStr32 = 0xdb + + mpArray16 = 0xdc + mpArray32 = 0xdd + + mpMap16 = 0xde + mpMap32 = 0xdf + + mpNegFixNumMin = 0xe0 + mpNegFixNumMax = 0xff ) -var mpTimeExtTag int8 = -1 -var mpTimeExtTagU = uint8(mpTimeExtTag) - -// var mpdesc = map[byte]string{ -// mpPosFixNumMin: "PosFixNumMin", -// mpPosFixNumMax: "PosFixNumMax", -// mpFixMapMin: "FixMapMin", -// mpFixMapMax: "FixMapMax", -// mpFixArrayMin: "FixArrayMin", -// mpFixArrayMax: "FixArrayMax", -// mpFixStrMin: "FixStrMin", -// mpFixStrMax: "FixStrMax", -// mpNil: "Nil", -// mpFalse: "False", -// mpTrue: "True", -// mpFloat: "Float", -// mpDouble: "Double", -// mpUint8: "Uint8", -// mpUint16: "Uint16", -// mpUint32: "Uint32", -// mpUint64: "Uint64", -// mpInt8: "Int8", -// mpInt16: "Int16", -// mpInt32: "Int32", -// mpInt64: "Int64", -// mpBin8: "Bin8", -// mpBin16: "Bin16", -// mpBin32: "Bin32", -// mpExt8: "Ext8", -// mpExt16: "Ext16", -// mpExt32: "Ext32", -// mpFixExt1: "FixExt1", -// mpFixExt2: "FixExt2", -// mpFixExt4: "FixExt4", -// mpFixExt8: "FixExt8", -// mpFixExt16: "FixExt16", -// mpStr8: "Str8", -// mpStr16: "Str16", -// mpStr32: "Str32", -// mpArray16: "Array16", -// mpArray32: "Array32", -// mpMap16: "Map16", -// mpMap32: "Map32", -// mpNegFixNumMin: "NegFixNumMin", -// mpNegFixNumMax: "NegFixNumMax", -// } - -func mpdesc(bd byte) string { - switch bd { - case mpNil: - return "nil" - case mpFalse: - return "false" - case mpTrue: - return "true" - case mpFloat, mpDouble: - return "float" - case mpUint8, mpUint16, mpUint32, mpUint64: - return "uint" - case mpInt8, mpInt16, mpInt32, mpInt64: - return "int" - default: - switch { - case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: - return "int" - case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: - return "int" - case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax: - return "string|bytes" - case bd == mpBin8, bd == mpBin16, bd == mpBin32: - return "bytes" - case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax: - return "array" - case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax: - return "map" - case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32: - return "ext" - default: - return "unknown" - } - } -} - // MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec // that the backend RPC service takes multiple arguments, which have been arranged // in sequence in the slice. @@ -172,102 +87,76 @@ type MsgpackSpecRpcMultiArgs []interface{} // A MsgpackContainer type specifies the different types of msgpackContainers. type msgpackContainerType struct { - fixCutoff uint8 - bFixMin, b8, b16, b32 byte - // hasFixMin, has8, has8Always bool + fixCutoff int + bFixMin, b8, b16, b32 byte + hasFixMin, has8, has8Always bool } var ( - msgpackContainerRawLegacy = msgpackContainerType{ - 32, mpFixStrMin, 0, mpStr16, mpStr32, - } - msgpackContainerStr = msgpackContainerType{ - 32, mpFixStrMin, mpStr8, mpStr16, mpStr32, // true, true, false, - } - msgpackContainerBin = msgpackContainerType{ - 0, 0, mpBin8, mpBin16, mpBin32, // false, true, true, - } - msgpackContainerList = msgpackContainerType{ - 16, mpFixArrayMin, 0, mpArray16, mpArray32, // true, false, false, - } - msgpackContainerMap = msgpackContainerType{ - 16, mpFixMapMin, 0, mpMap16, mpMap32, // true, false, false, - } + msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false} + msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true} + msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false} + msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false} ) //--------------------------------------------- type msgpackEncDriver struct { - noBuiltInTypes - encDriverNoopContainerWriter - // encNoSeparator - e *Encoder - w *encWriterSwitch + w encWriter h *MsgpackHandle - x [8]byte - // _ [3]uint64 // padding } -func (e *msgpackEncDriver) EncodeNil() { +func (e *msgpackEncDriver) isBuiltinType(rt uintptr) bool { + //no builtin types. All encodings are based on kinds. Types supported as extensions. + return false +} + +func (e *msgpackEncDriver) encodeBuiltin(rt uintptr, v interface{}) {} + +func (e *msgpackEncDriver) encodeNil() { e.w.writen1(mpNil) } -func (e *msgpackEncDriver) EncodeInt(i int64) { - if e.h.PositiveIntUnsigned && i >= 0 { - e.EncodeUint(uint64(i)) - } else if i > math.MaxInt8 { - if i <= math.MaxInt16 { - e.w.writen1(mpInt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i <= math.MaxInt32 { - e.w.writen1(mpInt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { - e.w.writen1(mpInt64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) - } - } else if i >= -32 { - if e.h.NoFixedNum { - e.w.writen2(mpInt8, byte(i)) - } else { - e.w.writen1(byte(i)) - } - } else if i >= math.MinInt8 { +func (e *msgpackEncDriver) encodeInt(i int64) { + + switch { + case i >= 0: + e.encodeUint(uint64(i)) + case i >= -32: + e.w.writen1(byte(i)) + case i >= math.MinInt8: e.w.writen2(mpInt8, byte(i)) - } else if i >= math.MinInt16 { + case i >= math.MinInt16: e.w.writen1(mpInt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i >= math.MinInt32 { + e.w.writeUint16(uint16(i)) + case i >= math.MinInt32: e.w.writen1(mpInt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { + e.w.writeUint32(uint32(i)) + default: e.w.writen1(mpInt64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) + e.w.writeUint64(uint64(i)) } } -func (e *msgpackEncDriver) EncodeUint(i uint64) { - if i <= math.MaxInt8 { - if e.h.NoFixedNum { - e.w.writen2(mpUint8, byte(i)) - } else { - e.w.writen1(byte(i)) - } - } else if i <= math.MaxUint8 { +func (e *msgpackEncDriver) encodeUint(i uint64) { + switch { + case i <= math.MaxInt8: + e.w.writen1(byte(i)) + case i <= math.MaxUint8: e.w.writen2(mpUint8, byte(i)) - } else if i <= math.MaxUint16 { + case i <= math.MaxUint16: e.w.writen1(mpUint16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i <= math.MaxUint32 { + e.w.writeUint16(uint16(i)) + case i <= math.MaxUint32: e.w.writen1(mpUint32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { + e.w.writeUint32(uint32(i)) + default: e.w.writen1(mpUint64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) + e.w.writeUint64(uint64(i)) } } -func (e *msgpackEncDriver) EncodeBool(b bool) { +func (e *msgpackEncDriver) encodeBool(b bool) { if b { e.w.writen1(mpTrue) } else { @@ -275,318 +164,229 @@ func (e *msgpackEncDriver) EncodeBool(b bool) { } } -func (e *msgpackEncDriver) EncodeFloat32(f float32) { +func (e *msgpackEncDriver) encodeFloat32(f float32) { e.w.writen1(mpFloat) - bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f)) + e.w.writeUint32(math.Float32bits(f)) } -func (e *msgpackEncDriver) EncodeFloat64(f float64) { +func (e *msgpackEncDriver) encodeFloat64(f float64) { e.w.writen1(mpDouble) - bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f)) -} - -func (e *msgpackEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - return - } - t = t.UTC() - sec, nsec := t.Unix(), uint64(t.Nanosecond()) - var data64 uint64 - var l = 4 - if sec >= 0 && sec>>34 == 0 { - data64 = (nsec << 34) | uint64(sec) - if data64&0xffffffff00000000 != 0 { - l = 8 - } - } else { - l = 12 - } - if e.h.WriteExt { - e.encodeExtPreamble(mpTimeExtTagU, l) - } else { - e.writeContainerLen(msgpackContainerRawLegacy, l) - } - switch l { - case 4: - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(data64)) - case 8: - bigenHelper{e.x[:8], e.w}.writeUint64(data64) - case 12: - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(nsec)) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(sec)) - } -} - -func (e *msgpackEncDriver) EncodeExt(v interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(v) - if bs == nil { - e.EncodeNil() - return - } - if e.h.WriteExt { - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) - } else { - e.EncodeStringBytesRaw(bs) - } -} - -func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) + e.w.writeUint64(math.Float64bits(f)) } func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) { - if l == 1 { + switch { + case l == 1: e.w.writen2(mpFixExt1, xtag) - } else if l == 2 { + case l == 2: e.w.writen2(mpFixExt2, xtag) - } else if l == 4 { + case l == 4: e.w.writen2(mpFixExt4, xtag) - } else if l == 8 { + case l == 8: e.w.writen2(mpFixExt8, xtag) - } else if l == 16 { + case l == 16: e.w.writen2(mpFixExt16, xtag) - } else if l < 256 { + case l < 256: e.w.writen2(mpExt8, byte(l)) e.w.writen1(xtag) - } else if l < 65536 { + case l < 65536: e.w.writen1(mpExt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l)) + e.w.writeUint16(uint16(l)) e.w.writen1(xtag) - } else { + default: e.w.writen1(mpExt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l)) + e.w.writeUint32(uint32(l)) e.w.writen1(xtag) } } -func (e *msgpackEncDriver) WriteArrayStart(length int) { +func (e *msgpackEncDriver) encodeArrayPreamble(length int) { e.writeContainerLen(msgpackContainerList, length) } -func (e *msgpackEncDriver) WriteMapStart(length int) { +func (e *msgpackEncDriver) encodeMapPreamble(length int) { e.writeContainerLen(msgpackContainerMap, length) } -func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) { - slen := len(s) - if c == cRAW && e.h.WriteExt { - e.writeContainerLen(msgpackContainerBin, slen) +func (e *msgpackEncDriver) encodeString(c charEncoding, s string) { + if c == c_RAW && e.h.WriteExt { + e.writeContainerLen(msgpackContainerBin, len(s)) } else { - e.writeContainerLen(msgpackContainerRawLegacy, slen) + e.writeContainerLen(msgpackContainerStr, len(s)) } - if slen > 0 { + if len(s) > 0 { e.w.writestr(s) } } -func (e *msgpackEncDriver) EncodeStringEnc(c charEncoding, s string) { - slen := len(s) - if e.h.WriteExt { - e.writeContainerLen(msgpackContainerStr, slen) - } else { - e.writeContainerLen(msgpackContainerRawLegacy, slen) - } - if slen > 0 { - e.w.writestr(s) - } +func (e *msgpackEncDriver) encodeSymbol(v string) { + e.encodeString(c_UTF8, v) } -func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) { - if bs == nil { - e.EncodeNil() - return - } - slen := len(bs) - if c == cRAW && e.h.WriteExt { - e.writeContainerLen(msgpackContainerBin, slen) +func (e *msgpackEncDriver) encodeStringBytes(c charEncoding, bs []byte) { + if c == c_RAW && e.h.WriteExt { + e.writeContainerLen(msgpackContainerBin, len(bs)) } else { - e.writeContainerLen(msgpackContainerRawLegacy, slen) + e.writeContainerLen(msgpackContainerStr, len(bs)) } - if slen > 0 { - e.w.writeb(bs) - } -} - -func (e *msgpackEncDriver) EncodeStringBytesRaw(bs []byte) { - if bs == nil { - e.EncodeNil() - return - } - slen := len(bs) - if e.h.WriteExt { - e.writeContainerLen(msgpackContainerBin, slen) - } else { - e.writeContainerLen(msgpackContainerRawLegacy, slen) - } - if slen > 0 { + if len(bs) > 0 { e.w.writeb(bs) } } func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) { - if ct.fixCutoff > 0 && l < int(ct.fixCutoff) { + switch { + case ct.hasFixMin && l < ct.fixCutoff: e.w.writen1(ct.bFixMin | byte(l)) - } else if ct.b8 > 0 && l < 256 { + case ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt): e.w.writen2(ct.b8, uint8(l)) - } else if l < 65536 { + case l < 65536: e.w.writen1(ct.b16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l)) - } else { + e.w.writeUint16(uint16(l)) + default: e.w.writen1(ct.b32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l)) + e.w.writeUint32(uint32(l)) } } //--------------------------------------------- type msgpackDecDriver struct { - d *Decoder - r *decReaderSwitch - h *MsgpackHandle - // b [scratchByteArrayLen]byte + r decReader + h *MsgpackHandle bd byte bdRead bool - br bool // bytes reader - noBuiltInTypes - // noStreamingCodec - // decNoSeparator - decDriverNoopContainerReader - // _ [3]uint64 // padding + bdType valueType } +func (d *msgpackDecDriver) isBuiltinType(rt uintptr) bool { + //no builtin types. All encodings are based on kinds. Types supported as extensions. + return false +} + +func (d *msgpackDecDriver) decodeBuiltin(rt uintptr, v interface{}) {} + // Note: This returns either a primitive (int, bool, etc) for non-containers, // or a containerType, or a specific type denoting nil or extension. // It is called when a nil interface{} is passed, leaving it up to the DecDriver // to introspect the stream and decide how best to decode. // It deciphers the value by looking at the stream first. -func (d *msgpackDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) { + d.initReadNext() bd := d.bd - n := d.d.naked() - var decodeFurther bool switch bd { case mpNil: - n.v = valueTypeNil + vt = valueTypeNil d.bdRead = false case mpFalse: - n.v = valueTypeBool - n.b = false + vt = valueTypeBool + v = false case mpTrue: - n.v = valueTypeBool - n.b = true + vt = valueTypeBool + v = true case mpFloat: - n.v = valueTypeFloat - n.f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) + vt = valueTypeFloat + v = float64(math.Float32frombits(d.r.readUint32())) case mpDouble: - n.v = valueTypeFloat - n.f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) + vt = valueTypeFloat + v = math.Float64frombits(d.r.readUint64()) case mpUint8: - n.v = valueTypeUint - n.u = uint64(d.r.readn1()) + vt = valueTypeUint + v = uint64(d.r.readn1()) case mpUint16: - n.v = valueTypeUint - n.u = uint64(bigen.Uint16(d.r.readx(2))) + vt = valueTypeUint + v = uint64(d.r.readUint16()) case mpUint32: - n.v = valueTypeUint - n.u = uint64(bigen.Uint32(d.r.readx(4))) + vt = valueTypeUint + v = uint64(d.r.readUint32()) case mpUint64: - n.v = valueTypeUint - n.u = uint64(bigen.Uint64(d.r.readx(8))) + vt = valueTypeUint + v = uint64(d.r.readUint64()) case mpInt8: - n.v = valueTypeInt - n.i = int64(int8(d.r.readn1())) + vt = valueTypeInt + v = int64(int8(d.r.readn1())) case mpInt16: - n.v = valueTypeInt - n.i = int64(int16(bigen.Uint16(d.r.readx(2)))) + vt = valueTypeInt + v = int64(int16(d.r.readUint16())) case mpInt32: - n.v = valueTypeInt - n.i = int64(int32(bigen.Uint32(d.r.readx(4)))) + vt = valueTypeInt + v = int64(int32(d.r.readUint32())) case mpInt64: - n.v = valueTypeInt - n.i = int64(int64(bigen.Uint64(d.r.readx(8)))) + vt = valueTypeInt + v = int64(int64(d.r.readUint64())) default: switch { case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: // positive fixnum (always signed) - n.v = valueTypeInt - n.i = int64(int8(bd)) + vt = valueTypeInt + v = int64(int8(bd)) case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: // negative fixnum - n.v = valueTypeInt - n.i = int64(int8(bd)) + vt = valueTypeInt + v = int64(int8(bd)) case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax: - if d.h.WriteExt || d.h.RawToString { - n.v = valueTypeString - n.s = d.DecodeString() + if d.h.RawToString { + var rvm string + vt = valueTypeString + v = &rvm } else { - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) + var rvm = []byte{} + vt = valueTypeBytes + v = &rvm } + decodeFurther = true case bd == mpBin8, bd == mpBin16, bd == mpBin32: - decNakedReadRawBytes(d, d.d, n, d.h.RawToString) + var rvm = []byte{} + vt = valueTypeBytes + v = &rvm + decodeFurther = true case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax: - n.v = valueTypeArray + vt = valueTypeArray decodeFurther = true case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax: - n.v = valueTypeMap + vt = valueTypeMap decodeFurther = true case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32: - n.v = valueTypeExt clen := d.readExtLen() - n.u = uint64(d.r.readn1()) - if n.u == uint64(mpTimeExtTagU) { - n.v = valueTypeTime - n.t = d.decodeTime(clen) - } else if d.br { - n.l = d.r.readx(uint(clen)) - } else { - n.l = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:]) - } + var re RawExt + re.Tag = d.r.readn1() + re.Data = d.r.readn(clen) + v = &re + vt = valueTypeExt default: - d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd)) + decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd) } } if !decodeFurther { d.bdRead = false } - if n.v == valueTypeUint && d.h.SignedInteger { - n.v = valueTypeInt - n.i = int64(n.u) - } + return } // int can be decoded from msgpack type: intXXX or uintXXX -func (d *msgpackDecDriver) DecodeInt64() (i int64) { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) decodeInt(bitsize uint8) (i int64) { switch d.bd { case mpUint8: i = int64(uint64(d.r.readn1())) case mpUint16: - i = int64(uint64(bigen.Uint16(d.r.readx(2)))) + i = int64(uint64(d.r.readUint16())) case mpUint32: - i = int64(uint64(bigen.Uint32(d.r.readx(4)))) + i = int64(uint64(d.r.readUint32())) case mpUint64: - i = int64(bigen.Uint64(d.r.readx(8))) + i = int64(d.r.readUint64()) case mpInt8: i = int64(int8(d.r.readn1())) case mpInt16: - i = int64(int16(bigen.Uint16(d.r.readx(2)))) + i = int64(int16(d.r.readUint16())) case mpInt32: - i = int64(int32(bigen.Uint32(d.r.readx(4)))) + i = int64(int32(d.r.readUint32())) case mpInt64: - i = int64(bigen.Uint64(d.r.readx(8))) + i = int64(d.r.readUint64()) default: switch { case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax: @@ -594,8 +394,13 @@ func (d *msgpackDecDriver) DecodeInt64() (i int64) { case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax: i = int64(int8(d.bd)) default: - d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return + decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd) + } + } + // check overflow (logic adapted from std pkg reflect/value.go OverflowUint() + if bitsize > 0 { + if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc { + decErr("Overflow int value: %v", i) } } d.bdRead = false @@ -603,57 +408,54 @@ func (d *msgpackDecDriver) DecodeInt64() (i int64) { } // uint can be decoded from msgpack type: intXXX or uintXXX -func (d *msgpackDecDriver) DecodeUint64() (ui uint64) { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) decodeUint(bitsize uint8) (ui uint64) { switch d.bd { case mpUint8: ui = uint64(d.r.readn1()) case mpUint16: - ui = uint64(bigen.Uint16(d.r.readx(2))) + ui = uint64(d.r.readUint16()) case mpUint32: - ui = uint64(bigen.Uint32(d.r.readx(4))) + ui = uint64(d.r.readUint32()) case mpUint64: - ui = bigen.Uint64(d.r.readx(8)) + ui = d.r.readUint64() case mpInt8: if i := int64(int8(d.r.readn1())); i >= 0 { ui = uint64(i) } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } case mpInt16: - if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 { + if i := int64(int16(d.r.readUint16())); i >= 0 { ui = uint64(i) } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } case mpInt32: - if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 { + if i := int64(int32(d.r.readUint32())); i >= 0 { ui = uint64(i) } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } case mpInt64: - if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 { + if i := int64(d.r.readUint64()); i >= 0 { ui = uint64(i) } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } default: switch { case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax: ui = uint64(d.bd) case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax: - d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd)) - return + decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd)) default: - d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return + decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd) + } + } + // check overflow (logic adapted from std pkg reflect/value.go OverflowUint() + if bitsize > 0 { + if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc { + decErr("Overflow uint value: %v", ui) } } d.bdRead = false @@ -661,173 +463,160 @@ func (d *msgpackDecDriver) DecodeUint64() (ui uint64) { } // float can either be decoded from msgpack type: float, double or intX -func (d *msgpackDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpFloat { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if d.bd == mpDouble { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else { - f = float64(d.DecodeInt64()) +func (d *msgpackDecDriver) decodeFloat(chkOverflow32 bool) (f float64) { + switch d.bd { + case mpFloat: + f = float64(math.Float32frombits(d.r.readUint32())) + case mpDouble: + f = math.Float64frombits(d.r.readUint64()) + default: + f = float64(d.decodeInt(0)) } + checkOverflowFloat32(f, chkOverflow32) d.bdRead = false return } // bool can be decoded from bool, fixnum 0 or 1. -func (d *msgpackDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpFalse || d.bd == 0 { +func (d *msgpackDecDriver) decodeBool() (b bool) { + switch d.bd { + case mpFalse, 0: // b = false - } else if d.bd == mpTrue || d.bd == 1 { + case mpTrue, 1: b = true - } else { - d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return + default: + decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd) } d.bdRead = false return } -func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() +func (d *msgpackDecDriver) decodeString() (s string) { + clen := d.readContainerLen(msgpackContainerStr) + if clen > 0 { + s = string(d.r.readn(clen)) } + d.bdRead = false + return +} - bd := d.bd +// Callers must check if changed=true (to decide whether to replace the one they have) +func (d *msgpackDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) { + // bytes can be decoded from msgpackContainerStr or msgpackContainerBin var clen int - if bd == mpNil { - d.bdRead = false - return - } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - clen = d.readContainerLen(msgpackContainerBin) // binary - } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) { - clen = d.readContainerLen(msgpackContainerStr) // string/raw - } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) { - // check if an "array" of uint8's - if zerocopy && len(bs) == 0 { - bs = d.d.b[:] - } - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } else { - d.d.errorf("invalid byte descriptor for decoding bytes, got: 0x%x", d.bd) - return + switch d.bd { + case mpBin8, mpBin16, mpBin32: + clen = d.readContainerLen(msgpackContainerBin) + default: + clen = d.readContainerLen(msgpackContainerStr) } - - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(uint(clen)) - } else if len(bs) == 0 { - bs = d.d.b[:] + // if clen < 0 { + // changed = true + // panic("length cannot be zero. this cannot be nil.") + // } + if clen > 0 { + // if no contents in stream, don't update the passed byteslice + if len(bs) != clen { + // Return changed=true if length of passed slice diff from length of bytes in stream + if len(bs) > clen { + bs = bs[:clen] + } else { + bs = make([]byte, clen) + } + bsOut = bs + changed = true } + d.r.readb(bs) } - return decByteSlice(d.r, clen, d.h.MaxInitLen, bs) -} - -func (d *msgpackDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *msgpackDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true + d.bdRead = false + return } -func (d *msgpackDecDriver) uncacheRead() { +// Every top-level decode funcs (i.e. decodeValue, decode) must call this first. +func (d *msgpackDecDriver) initReadNext() { if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *msgpackDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() + return } - bd := d.bd - // if bd == mpNil { - // // nil - // } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - // // binary - // } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) { - // // string/raw - // } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) { - // // array - // } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) { - // // map - // } - if bd == mpNil { - return valueTypeNil - } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - return valueTypeBytes - } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) { - if d.h.WriteExt || d.h.RawToString { // UTF-8 string (new spec) - return valueTypeString + d.bd = d.r.readn1() + d.bdRead = true + d.bdType = valueTypeUnset +} + +func (d *msgpackDecDriver) currentEncodedType() valueType { + if d.bdType == valueTypeUnset { + bd := d.bd + switch bd { + case mpNil: + d.bdType = valueTypeNil + case mpFalse, mpTrue: + d.bdType = valueTypeBool + case mpFloat, mpDouble: + d.bdType = valueTypeFloat + case mpUint8, mpUint16, mpUint32, mpUint64: + d.bdType = valueTypeUint + case mpInt8, mpInt16, mpInt32, mpInt64: + d.bdType = valueTypeInt + default: + switch { + case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: + d.bdType = valueTypeInt + case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: + d.bdType = valueTypeInt + case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax: + if d.h.RawToString { + d.bdType = valueTypeString + } else { + d.bdType = valueTypeBytes + } + case bd == mpBin8, bd == mpBin16, bd == mpBin32: + d.bdType = valueTypeBytes + case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax: + d.bdType = valueTypeArray + case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax: + d.bdType = valueTypeMap + case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32: + d.bdType = valueTypeExt + default: + decErr("currentEncodedType: Undeciphered descriptor: %s: hex: %x, dec: %d", msgBadDesc, bd, bd) + } } - return valueTypeBytes // raw (old spec) - } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) { - return valueTypeArray - } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) { - return valueTypeMap } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset + return d.bdType } -func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) tryDecodeAsNil() bool { if d.bd == mpNil { d.bdRead = false return true } - return + return false } func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) { bd := d.bd - if bd == mpNil { + switch { + case bd == mpNil: clen = -1 // to represent nil - } else if bd == ct.b8 { + case bd == ct.b8: clen = int(d.r.readn1()) - } else if bd == ct.b16 { - clen = int(bigen.Uint16(d.r.readx(2))) - } else if bd == ct.b32 { - clen = int(bigen.Uint32(d.r.readx(4))) - } else if (ct.bFixMin & bd) == ct.bFixMin { + case bd == ct.b16: + clen = int(d.r.readUint16()) + case bd == ct.b32: + clen = int(d.r.readUint32()) + case (ct.bFixMin & bd) == ct.bFixMin: clen = int(ct.bFixMin ^ bd) - } else { - d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd) - return + default: + decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd) } d.bdRead = false return } -func (d *msgpackDecDriver) ReadMapStart() int { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) readMapLen() int { return d.readContainerLen(msgpackContainerMap) } -func (d *msgpackDecDriver) ReadArrayStart() int { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) readArrayLen() int { return d.readContainerLen(msgpackContainerList) } @@ -848,107 +637,30 @@ func (d *msgpackDecDriver) readExtLen() (clen int) { case mpExt8: clen = int(d.r.readn1()) case mpExt16: - clen = int(bigen.Uint16(d.r.readx(2))) + clen = int(d.r.readUint16()) case mpExt32: - clen = int(bigen.Uint32(d.r.readx(4))) - default: - d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd) - return - } - return -} - -func (d *msgpackDecDriver) DecodeTime() (t time.Time) { - // decode time from string bytes or ext - if !d.bdRead { - d.readNextBd() - } - bd := d.bd - var clen int - if bd == mpNil { - d.bdRead = false - return - } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - clen = d.readContainerLen(msgpackContainerBin) // binary - } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) { - clen = d.readContainerLen(msgpackContainerStr) // string/raw - } else { - // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1 - d.bdRead = false - b2 := d.r.readn1() - if d.bd == mpFixExt4 && b2 == mpTimeExtTagU { - clen = 4 - } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU { - clen = 8 - } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU { - clen = 12 - } else { - d.d.errorf("invalid stream for decoding time as extension: got 0x%x, 0x%x", d.bd, b2) - return - } - } - return d.decodeTime(clen) -} - -func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) { - // bs = d.r.readx(clen) - d.bdRead = false - switch clen { - case 4: - t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC() - case 8: - tv := bigen.Uint64(d.r.readx(8)) - t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC() - case 12: - nsec := bigen.Uint32(d.r.readx(4)) - sec := bigen.Uint64(d.r.readx(8)) - t = time.Unix(int64(sec), int64(nsec)).UTC() + clen = int(d.r.readUint32()) default: - d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen) - return + decErr("decoding ext bytes: found unexpected byte: %x", d.bd) } return } -func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) - } - return -} - -func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } +func (d *msgpackDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) { xbd := d.bd - if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 { - xbs = d.DecodeBytes(nil, true) - } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 || - (xbd >= mpFixStrMin && xbd <= mpFixStrMax) { - xbs = d.DecodeStringAsBytes() - } else { + switch { + case xbd == mpBin8, xbd == mpBin16, xbd == mpBin32: + xbs, _ = d.decodeBytes(nil) + case xbd == mpStr8, xbd == mpStr16, xbd == mpStr32, + xbd >= mpFixStrMin && xbd <= mpFixStrMax: + xbs = []byte(d.decodeString()) + default: clen := d.readExtLen() xtag = d.r.readn1() if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag - got %b, expecting %v", xtag, tag) - return - } - if d.br { - xbs = d.r.readx(uint(clen)) - } else { - xbs = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:]) + decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag) } + xbs = d.r.readn(clen) } d.bdRead = false return @@ -960,55 +672,35 @@ func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs type MsgpackHandle struct { BasicHandle - // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum. - NoFixedNum bool - - // WriteExt controls whether the new spec is honored. - // - // With WriteExt=true, we can encode configured extensions with extension tags - // and encode string/[]byte/extensions in a way compatible with the new spec - // but incompatible with the old spec. + // RawToString controls how raw bytes are decoded into a nil interface{}. + RawToString bool + // WriteExt flag supports encoding configured extensions with extension tags. + // It also controls whether other elements of the new spec are encoded (ie Str8). // - // For compatibility with the old spec, set WriteExt=false. + // With WriteExt=false, configured extensions are serialized as raw bytes + // and Str8 is not encoded. // - // With WriteExt=false: - // configured extensions are serialized as raw bytes (not msgpack extensions). - // reserved byte descriptors like Str8 and those enabling the new msgpack Binary type - // are not encoded. + // A stream can still be decoded into a typed value, provided an appropriate value + // is provided, but the type cannot be inferred from the stream. If no appropriate + // type is provided (e.g. decoding into a nil interface{}), you get back + // a []byte or string based on the setting of RawToString. WriteExt bool - - // PositiveIntUnsigned says to encode positive integers as unsigned. - PositiveIntUnsigned bool - - binaryEncodingType - noElemSeparators - - // _ [1]uint64 // padding } -// Name returns the name of the handle: msgpack -func (h *MsgpackHandle) Name() string { return "msgpack" } - -// SetBytesExt sets an extension -func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) +func (h *MsgpackHandle) newEncDriver(w encWriter) encDriver { + return &msgpackEncDriver{w: w, h: h} } -func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver { - return &msgpackEncDriver{e: e, w: e.w, h: h} +func (h *MsgpackHandle) newDecDriver(r decReader) decDriver { + return &msgpackDecDriver{r: r, h: h} } -func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver { - return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes} +func (h *MsgpackHandle) writeExt() bool { + return h.WriteExt } -func (e *msgpackEncDriver) reset() { - e.w = e.e.w -} - -func (d *msgpackDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false +func (h *MsgpackHandle) getBasicHandle() *BasicHandle { + return &h.BasicHandle } //-------------------------------------------------- @@ -1029,7 +721,7 @@ func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) err bodyArr = []interface{}{body} } r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr} - return c.write(r2, nil, false) + return c.write(r2, nil, false, true) } func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error { @@ -1041,7 +733,7 @@ func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) e body = nil } r2 := []interface{}{1, uint32(r.Seq), moe, body} - return c.write(r2, nil, false) + return c.write(r2, nil, false, true) } func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error { @@ -1061,7 +753,8 @@ func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error { } func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) { - if cls := c.cls.load(); cls.closed { + + if c.cls { return io.EOF } @@ -1074,34 +767,28 @@ func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1) // return // } - var ba [1]byte - var n int - for { - n, err = c.r.Read(ba[:]) - if err != nil { - return - } - if n == 1 { - break - } + var b byte + b, err = c.br.ReadByte() + if err != nil { + return } - - var b = ba[0] if b != fia { - err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b)) - } else { - err = c.read(&b) - if err == nil { - if b != expectTypeByte { - err = fmt.Errorf("%s - expecting %v but got %x/%s", - msgBadDesc, expectTypeByte, b, mpdesc(b)) - } else { - err = c.read(msgid) - if err == nil { - err = c.read(methodOrError) - } - } - } + err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, b) + return + } + + if err = c.read(&b); err != nil { + return + } + if b != expectTypeByte { + err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b) + return + } + if err = c.read(msgid); err != nil { + return + } + if err = c.read(methodOrError); err != nil { + return } return } @@ -1114,8 +801,7 @@ type msgpackSpecRpc struct{} // MsgpackSpecRpc implements Rpc using the communication protocol defined in // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md . -// -// See GoRpc documentation, for information on buffering for better performance. +// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered. var MsgpackSpecRpc msgpackSpecRpc func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec { diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/test.py b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py similarity index 69% rename from vendor/github.com/hashicorp/go-msgpack/codec/test.py rename to vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py index 800376f6841b4..e933838c56a89 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/test.py +++ b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py @@ -4,14 +4,7 @@ # A Test calls this internally to create the golden files # So it can process them (so we don't have to checkin the files). -# Ensure msgpack-python and cbor are installed first, using: -# sudo apt-get install python-dev -# sudo apt-get install python-pip -# pip install --user msgpack-python msgpack-rpc-python cbor - -# Ensure all "string" keys are utf strings (else encoded as bytes) - -import cbor, msgpack, msgpackrpc, sys, os, threading +import msgpack, msgpackrpc, sys, os, threading def get_test_data_list(): # get list with all primitive types, and a combo type @@ -28,52 +21,43 @@ def get_test_data_list(): -3232.0, -6464646464.0, 3232.0, - 6464.0, 6464646464.0, False, True, - u"null", None, - u"some&day>some<day", + "someday", + "", + "bytestring", 1328176922000002000, - u"", -2206187877999998000, - u"bytestring", - 270, - u"none", - -2013855847999995777, - #-6795364578871345152, + 0, + -6795364578871345152 ] l1 = [ { "true": True, "false": False }, - { "true": u"True", + { "true": "True", "false": False, "uint16(1616)": 1616 }, { "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ], "int32":32323232, "bool": True, - "LONG STRING": u"123456789012345678901234567890123456789012345678901234567890", - "SHORT STRING": u"1234567890" }, - { True: "true", 138: False, "false": 200 } + "LONG STRING": "123456789012345678901234567890123456789012345678901234567890", + "SHORT STRING": "1234567890" }, + { True: "true", 8: False, "false": 0 } ] l = [] l.extend(l0) l.append(l0) - l.append(1) l.extend(l1) return l def build_test_data(destdir): l = get_test_data_list() for i in range(len(l)): - # packer = msgpack.Packer() - serialized = msgpack.dumps(l[i]) - f = open(os.path.join(destdir, str(i) + '.msgpack.golden'), 'wb') - f.write(serialized) - f.close() - serialized = cbor.dumps(l[i]) - f = open(os.path.join(destdir, str(i) + '.cbor.golden'), 'wb') + packer = msgpack.Packer() + serialized = packer.pack(l[i]) + f = open(os.path.join(destdir, str(i) + '.golden'), 'wb') f.write(serialized) f.close() @@ -84,7 +68,7 @@ def Echo123(self, msg1, msg2, msg3): def EchoStruct(self, msg): return ("%s" % msg) - addr = msgpackrpc.Address('127.0.0.1', port) + addr = msgpackrpc.Address('localhost', port) server = msgpackrpc.Server(EchoHandler()) server.listen(addr) # run thread to stop it after stopTimeSec seconds if > 0 @@ -96,14 +80,14 @@ def myStopRpcServer(): server.start() def doRpcClientToPythonSvc(port): - address = msgpackrpc.Address('127.0.0.1', port) + address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("Echo123", "A1", "B2", "C3") print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doRpcClientToGoSvc(port): # print ">>>> port: ", port, " <<<<<" - address = msgpackrpc.Address('127.0.0.1', port) + address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"]) print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) @@ -118,7 +102,7 @@ def doMain(args): elif len(args) == 2 and args[0] == "rpc-client-go-service": doRpcClientToGoSvc(int(args[1])) else: - print("Usage: test.py " + + print("Usage: msgpack_test.py " + "[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...") if __name__ == "__main__": diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go index 3925088152dc1..d014dbdcc7d0a 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go @@ -1,150 +1,99 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec import ( "bufio" - "errors" "io" "net/rpc" + "sync" ) -var errRpcJsonNeedsTermWhitespace = errors.New("rpc requires JsonHandle with TermWhitespace=true") - // Rpc provides a rpc Server or Client Codec for rpc communication. type Rpc interface { ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec } -// RPCOptions holds options specific to rpc functionality -type RPCOptions struct { - // RPCNoBuffer configures whether we attempt to buffer reads and writes during RPC calls. - // - // Set RPCNoBuffer=true to turn buffering off. - // Buffering can still be done if buffered connections are passed in, or - // buffering is configured on the handle. - RPCNoBuffer bool +// RpcCodecBuffered allows access to the underlying bufio.Reader/Writer +// used by the rpc connection. It accomodates use-cases where the connection +// should be used by rpc and non-rpc functions, e.g. streaming a file after +// sending an rpc response. +type RpcCodecBuffered interface { + BufferedReader() *bufio.Reader + BufferedWriter() *bufio.Writer } +// ------------------------------------- + // rpcCodec defines the struct members and common methods. type rpcCodec struct { - c io.Closer - r io.Reader - w io.Writer - f ioFlusher - + rwc io.ReadWriteCloser dec *Decoder enc *Encoder - // bw *bufio.Writer - // br *bufio.Reader - h Handle - - cls atomicClsErr + bw *bufio.Writer + br *bufio.Reader + mu sync.Mutex + cls bool } func newRPCCodec(conn io.ReadWriteCloser, h Handle) rpcCodec { - // return newRPCCodec2(bufio.NewReader(conn), bufio.NewWriter(conn), conn, h) - return newRPCCodec2(conn, conn, conn, h) -} - -func newRPCCodec2(r io.Reader, w io.Writer, c io.Closer, h Handle) rpcCodec { - // defensive: ensure that jsonH has TermWhitespace turned on. - if jsonH, ok := h.(*JsonHandle); ok && !jsonH.TermWhitespace { - panic(errRpcJsonNeedsTermWhitespace) - } - // always ensure that we use a flusher, and always flush what was written to the connection. - // we lose nothing by using a buffered writer internally. - f, ok := w.(ioFlusher) - bh := basicHandle(h) - if !bh.RPCNoBuffer { - if bh.WriterBufferSize <= 0 { - if !ok { - bw := bufio.NewWriter(w) - f, w = bw, bw - } - } - if bh.ReaderBufferSize <= 0 { - if _, ok = w.(ioPeeker); !ok { - if _, ok = w.(ioBuffered); !ok { - br := bufio.NewReader(r) - r = br - } - } - } - } + bw := bufio.NewWriter(conn) + br := bufio.NewReader(conn) return rpcCodec{ - c: c, - w: w, - r: r, - f: f, - h: h, - enc: NewEncoder(w, h), - dec: NewDecoder(r, h), + rwc: conn, + bw: bw, + br: br, + enc: NewEncoder(bw, h), + dec: NewDecoder(br, h), } } -func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2 bool) (err error) { - if c.c != nil { - cls := c.cls.load() - if cls.closed { - return cls.errClosed - } +func (c *rpcCodec) BufferedReader() *bufio.Reader { + return c.br +} + +func (c *rpcCodec) BufferedWriter() *bufio.Writer { + return c.bw +} + +func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2, doFlush bool) (err error) { + if c.cls { + return io.EOF } - err = c.enc.Encode(obj1) - if err == nil { - if writeObj2 { - err = c.enc.Encode(obj2) - } - // if err == nil && c.f != nil { - // err = c.f.Flush() - // } + if err = c.enc.Encode(obj1); err != nil { + return } - if c.f != nil { - if err == nil { - err = c.f.Flush() - } else { - _ = c.f.Flush() // swallow flush error, so we maintain prior error on write + if writeObj2 { + if err = c.enc.Encode(obj2); err != nil { + return } } + if doFlush && c.bw != nil { + return c.bw.Flush() + } return } -func (c *rpcCodec) swallow(err *error) { - defer panicToErr(c.dec, err) - c.dec.swallow() -} - func (c *rpcCodec) read(obj interface{}) (err error) { - if c.c != nil { - cls := c.cls.load() - if cls.closed { - return cls.errClosed - } + if c.cls { + return io.EOF } - //If nil is passed in, we should read and discard + //If nil is passed in, we should still attempt to read content to nowhere. if obj == nil { - // var obj2 interface{} - // return c.dec.Decode(&obj2) - c.swallow(&err) - return + var obj2 interface{} + return c.dec.Decode(&obj2) } return c.dec.Decode(obj) } func (c *rpcCodec) Close() error { - if c.c == nil { - return nil - } - cls := c.cls.load() - if cls.closed { - return cls.errClosed + if c.cls { + return io.EOF } - cls.errClosed = c.c.Close() - cls.closed = true - c.cls.store(cls) - return cls.errClosed + c.cls = true + return c.rwc.Close() } func (c *rpcCodec) ReadResponseBody(body interface{}) error { @@ -158,11 +107,16 @@ type goRpcCodec struct { } func (c *goRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error { - return c.write(r, body, true) + // Must protect for concurrent access as per API + c.mu.Lock() + defer c.mu.Unlock() + return c.write(r, body, true, true) } func (c *goRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error { - return c.write(r, body, true) + c.mu.Lock() + defer c.mu.Unlock() + return c.write(r, body, true, true) } func (c *goRpcCodec) ReadResponseHeader(r *rpc.Response) error { @@ -184,36 +138,7 @@ func (c *goRpcCodec) ReadRequestBody(body interface{}) error { type goRpc struct{} // GoRpc implements Rpc using the communication protocol defined in net/rpc package. -// -// Note: network connection (from net.Dial, of type io.ReadWriteCloser) is not buffered. -// -// For performance, you should configure WriterBufferSize and ReaderBufferSize on the handle. -// This ensures we use an adequate buffer during reading and writing. -// If not configured, we will internally initialize and use a buffer during reads and writes. -// This can be turned off via the RPCNoBuffer option on the Handle. -// var handle codec.JsonHandle -// handle.RPCNoBuffer = true // turns off attempt by rpc module to initialize a buffer -// -// Example 1: one way of configuring buffering explicitly: -// var handle codec.JsonHandle // codec handle -// handle.ReaderBufferSize = 1024 -// handle.WriterBufferSize = 1024 -// var conn io.ReadWriteCloser // connection got from a socket -// var serverCodec = GoRpc.ServerCodec(conn, handle) -// var clientCodec = GoRpc.ClientCodec(conn, handle) -// -// Example 2: you can also explicitly create a buffered connection yourself, -// and not worry about configuring the buffer sizes in the Handle. -// var handle codec.Handle // codec handle -// var conn io.ReadWriteCloser // connection got from a socket -// var bufconn = struct { // bufconn here is a buffered io.ReadWriteCloser -// io.Closer -// *bufio.Reader -// *bufio.Writer -// }{conn, bufio.NewReader(conn), bufio.NewWriter(conn)} -// var serverCodec = GoRpc.ServerCodec(bufconn, handle) -// var clientCodec = GoRpc.ClientCodec(bufconn, handle) -// +// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered. var GoRpc goRpc func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec { @@ -223,3 +148,5 @@ func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec { func (x goRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec { return &goRpcCodec{newRPCCodec(conn, h)} } + +var _ RpcCodecBuffered = (*rpcCodec)(nil) // ensure *rpcCodec implements RpcCodecBuffered diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/simple.go b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go index a3257c1a7bdd3..9e4d148a2a179 100644 --- a/vendor/github.com/hashicorp/go-msgpack/codec/simple.go +++ b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go @@ -1,13 +1,9 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec -import ( - "math" - "reflect" - "time" -) +import "math" const ( _ uint8 = iota @@ -21,8 +17,6 @@ const ( simpleVdPosInt = 8 simpleVdNegInt = 12 - simpleVdTime = 24 - // containers: each lasts for 4 (ie n, n+1, n+2, ... n+7) simpleVdString = 216 simpleVdByteArray = 224 @@ -32,27 +26,23 @@ const ( ) type simpleEncDriver struct { - noBuiltInTypes - // encNoSeparator - e *Encoder h *SimpleHandle - w *encWriterSwitch - b [8]byte - // c containerState - encDriverTrackContainerWriter - // encDriverNoopContainerWriter - _ [3]uint64 // padding + w encWriter + //b [8]byte +} + +func (e *simpleEncDriver) isBuiltinType(rt uintptr) bool { + return false } -func (e *simpleEncDriver) EncodeNil() { +func (e *simpleEncDriver) encodeBuiltin(rt uintptr, v interface{}) { +} + +func (e *simpleEncDriver) encodeNil() { e.w.writen1(simpleVdNil) } -func (e *simpleEncDriver) EncodeBool(b bool) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && !b { - e.EncodeNil() - return - } +func (e *simpleEncDriver) encodeBool(b bool) { if b { e.w.writen1(simpleVdTrue) } else { @@ -60,25 +50,17 @@ func (e *simpleEncDriver) EncodeBool(b bool) { } } -func (e *simpleEncDriver) EncodeFloat32(f float32) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && f == 0.0 { - e.EncodeNil() - return - } +func (e *simpleEncDriver) encodeFloat32(f float32) { e.w.writen1(simpleVdFloat32) - bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f)) + e.w.writeUint32(math.Float32bits(f)) } -func (e *simpleEncDriver) EncodeFloat64(f float64) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && f == 0.0 { - e.EncodeNil() - return - } +func (e *simpleEncDriver) encodeFloat64(f float64) { e.w.writen1(simpleVdFloat64) - bigenHelper{e.b[:8], e.w}.writeUint64(math.Float64bits(f)) + e.w.writeUint64(math.Float64bits(f)) } -func (e *simpleEncDriver) EncodeInt(v int64) { +func (e *simpleEncDriver) encodeInt(v int64) { if v < 0 { e.encUint(uint64(-v), simpleVdNegInt) } else { @@ -86,185 +68,123 @@ func (e *simpleEncDriver) EncodeInt(v int64) { } } -func (e *simpleEncDriver) EncodeUint(v uint64) { +func (e *simpleEncDriver) encodeUint(v uint64) { e.encUint(v, simpleVdPosInt) } func (e *simpleEncDriver) encUint(v uint64, bd uint8) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == 0 { - e.EncodeNil() - return - } - if v <= math.MaxUint8 { + switch { + case v <= math.MaxUint8: e.w.writen2(bd, uint8(v)) - } else if v <= math.MaxUint16 { + case v <= math.MaxUint16: e.w.writen1(bd + 1) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { + e.w.writeUint16(uint16(v)) + case v <= math.MaxUint32: e.w.writen1(bd + 2) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v)) - } else { // if v <= math.MaxUint64 { + e.w.writeUint32(uint32(v)) + case v <= math.MaxUint64: e.w.writen1(bd + 3) - bigenHelper{e.b[:8], e.w}.writeUint64(v) + e.w.writeUint64(v) } } func (e *simpleEncDriver) encLen(bd byte, length int) { - if length == 0 { + switch { + case length == 0: e.w.writen1(bd) - } else if length <= math.MaxUint8 { + case length <= math.MaxUint8: e.w.writen1(bd + 1) e.w.writen1(uint8(length)) - } else if length <= math.MaxUint16 { + case length <= math.MaxUint16: e.w.writen1(bd + 2) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(length)) - } else if int64(length) <= math.MaxUint32 { + e.w.writeUint16(uint16(length)) + case int64(length) <= math.MaxUint32: e.w.writen1(bd + 3) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(length)) - } else { + e.w.writeUint32(uint32(length)) + default: e.w.writen1(bd + 4) - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(length)) + e.w.writeUint64(uint64(length)) } } -func (e *simpleEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(rv) - if bs == nil { - e.EncodeNil() - return - } - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) -} - -func (e *simpleEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) -} - func (e *simpleEncDriver) encodeExtPreamble(xtag byte, length int) { e.encLen(simpleVdExt, length) e.w.writen1(xtag) } -func (e *simpleEncDriver) WriteArrayStart(length int) { - e.c = containerArrayStart +func (e *simpleEncDriver) encodeArrayPreamble(length int) { e.encLen(simpleVdArray, length) } -func (e *simpleEncDriver) WriteMapStart(length int) { - e.c = containerMapStart +func (e *simpleEncDriver) encodeMapPreamble(length int) { e.encLen(simpleVdMap, length) } -// func (e *simpleEncDriver) EncodeSymbol(v string) { -// e.EncodeStringEnc(cUTF8, v) -// } - -func (e *simpleEncDriver) EncodeStringEnc(c charEncoding, v string) { - if false && e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == "" { - e.EncodeNil() - return - } +func (e *simpleEncDriver) encodeString(c charEncoding, v string) { e.encLen(simpleVdString, len(v)) e.w.writestr(v) } -func (e *simpleEncDriver) EncodeString(c charEncoding, v string) { - e.EncodeStringEnc(c, v) +func (e *simpleEncDriver) encodeSymbol(v string) { + e.encodeString(c_UTF8, v) } -func (e *simpleEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - e.EncodeStringBytesRaw(v) -} - -func (e *simpleEncDriver) EncodeStringBytesRaw(v []byte) { - // if e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == nil { - if v == nil { - e.EncodeNil() - return - } +func (e *simpleEncDriver) encodeStringBytes(c charEncoding, v []byte) { e.encLen(simpleVdByteArray, len(v)) e.w.writeb(v) } -func (e *simpleEncDriver) EncodeTime(t time.Time) { - // if e.h.EncZeroValuesAsNil && e.c != containerMapKey && t.IsZero() { - if t.IsZero() { - e.EncodeNil() - return - } - v, err := t.MarshalBinary() - if err != nil { - e.e.errorv(err) - return - } - // time.Time marshalbinary takes about 14 bytes. - e.w.writen2(simpleVdTime, uint8(len(v))) - e.w.writeb(v) -} - //------------------------------------ type simpleDecDriver struct { - d *Decoder h *SimpleHandle - r *decReaderSwitch + r decReader bdRead bool + bdType valueType bd byte - br bool // a bytes reader? - c containerState - // b [scratchByteArrayLen]byte - noBuiltInTypes - // noStreamingCodec - decDriverNoopContainerReader - // _ [3]uint64 // padding + //b [8]byte } -func (d *simpleDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true -} - -func (d *simpleDecDriver) uncacheRead() { +func (d *simpleDecDriver) initReadNext() { if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *simpleDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() + return } - switch d.bd { - case simpleVdNil: - return valueTypeNil - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - return valueTypeBytes - case simpleVdString, simpleVdString + 1, - simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: - return valueTypeString - case simpleVdArray, simpleVdArray + 1, - simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4: - return valueTypeArray - case simpleVdMap, simpleVdMap + 1, - simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4: - return valueTypeMap - // case simpleVdTime: - // return valueTypeTime + d.bd = d.r.readn1() + d.bdRead = true + d.bdType = valueTypeUnset +} + +func (d *simpleDecDriver) currentEncodedType() valueType { + if d.bdType == valueTypeUnset { + switch d.bd { + case simpleVdNil: + d.bdType = valueTypeNil + case simpleVdTrue, simpleVdFalse: + d.bdType = valueTypeBool + case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3: + d.bdType = valueTypeUint + case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3: + d.bdType = valueTypeInt + case simpleVdFloat32, simpleVdFloat64: + d.bdType = valueTypeFloat + case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: + d.bdType = valueTypeString + case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: + d.bdType = valueTypeBytes + case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4: + d.bdType = valueTypeExt + case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4: + d.bdType = valueTypeArray + case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4: + d.bdType = valueTypeMap + default: + decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.bd) + } } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset + return d.bdType } -func (d *simpleDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } +func (d *simpleDecDriver) tryDecodeAsNil() bool { if d.bd == simpleVdNil { d.bdRead = false return true @@ -272,137 +192,112 @@ func (d *simpleDecDriver) TryDecodeAsNil() bool { return false } -func (d *simpleDecDriver) decCheckInteger() (ui uint64, neg bool) { - if !d.bdRead { - d.readNextBd() - } +func (d *simpleDecDriver) isBuiltinType(rt uintptr) bool { + return false +} + +func (d *simpleDecDriver) decodeBuiltin(rt uintptr, v interface{}) { +} + +func (d *simpleDecDriver) decIntAny() (ui uint64, i int64, neg bool) { switch d.bd { case simpleVdPosInt: ui = uint64(d.r.readn1()) + i = int64(ui) case simpleVdPosInt + 1: - ui = uint64(bigen.Uint16(d.r.readx(2))) + ui = uint64(d.r.readUint16()) + i = int64(ui) case simpleVdPosInt + 2: - ui = uint64(bigen.Uint32(d.r.readx(4))) + ui = uint64(d.r.readUint32()) + i = int64(ui) case simpleVdPosInt + 3: - ui = uint64(bigen.Uint64(d.r.readx(8))) + ui = uint64(d.r.readUint64()) + i = int64(ui) case simpleVdNegInt: ui = uint64(d.r.readn1()) + i = -(int64(ui)) neg = true case simpleVdNegInt + 1: - ui = uint64(bigen.Uint16(d.r.readx(2))) + ui = uint64(d.r.readUint16()) + i = -(int64(ui)) neg = true case simpleVdNegInt + 2: - ui = uint64(bigen.Uint32(d.r.readx(4))) + ui = uint64(d.r.readUint32()) + i = -(int64(ui)) neg = true case simpleVdNegInt + 3: - ui = uint64(bigen.Uint64(d.r.readx(8))) + ui = uint64(d.r.readUint64()) + i = -(int64(ui)) neg = true default: - d.d.errorf("integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd) - return + decErr("decIntAny: Integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd) } // don't do this check, because callers may only want the unsigned value. // if ui > math.MaxInt64 { - // d.d.errorf("decIntAny: Integer out of range for signed int64: %v", ui) - // return + // decErr("decIntAny: Integer out of range for signed int64: %v", ui) // } return } -func (d *simpleDecDriver) DecodeInt64() (i int64) { - ui, neg := d.decCheckInteger() - i = chkOvf.SignedIntV(ui) - if neg { - i = -i - } +func (d *simpleDecDriver) decodeInt(bitsize uint8) (i int64) { + _, i, _ = d.decIntAny() + checkOverflow(0, i, bitsize) d.bdRead = false return } -func (d *simpleDecDriver) DecodeUint64() (ui uint64) { - ui, neg := d.decCheckInteger() +func (d *simpleDecDriver) decodeUint(bitsize uint8) (ui uint64) { + ui, i, neg := d.decIntAny() if neg { - d.d.errorf("assigning negative signed value to unsigned type") - return + decErr("Assigning negative signed value: %v, to unsigned type", i) } + checkOverflow(ui, 0, bitsize) d.bdRead = false return } -func (d *simpleDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdFloat32 { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if d.bd == simpleVdFloat64 { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else { +func (d *simpleDecDriver) decodeFloat(chkOverflow32 bool) (f float64) { + switch d.bd { + case simpleVdFloat32: + f = float64(math.Float32frombits(d.r.readUint32())) + case simpleVdFloat64: + f = math.Float64frombits(d.r.readUint64()) + default: if d.bd >= simpleVdPosInt && d.bd <= simpleVdNegInt+3 { - f = float64(d.DecodeInt64()) + _, i, _ := d.decIntAny() + f = float64(i) } else { - d.d.errorf("float only valid from float32/64: Invalid descriptor: %v", d.bd) - return + decErr("Float only valid from float32/64: Invalid descriptor: %v", d.bd) } } + checkOverflowFloat32(f, chkOverflow32) d.bdRead = false return } // bool can be decoded from bool only (single byte). -func (d *simpleDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdTrue { +func (d *simpleDecDriver) decodeBool() (b bool) { + switch d.bd { + case simpleVdTrue: b = true - } else if d.bd == simpleVdFalse { - } else { - d.d.errorf("cannot decode bool - %s: %x", msgBadDesc, d.bd) - return + case simpleVdFalse: + default: + decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd) } d.bdRead = false return } -func (d *simpleDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } +func (d *simpleDecDriver) readMapLen() (length int) { d.bdRead = false - d.c = containerMapStart return d.decLen() } -func (d *simpleDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } +func (d *simpleDecDriver) readArrayLen() (length int) { d.bdRead = false - d.c = containerArrayStart return d.decLen() } -func (d *simpleDecDriver) ReadArrayElem() { - d.c = containerArrayElem -} - -func (d *simpleDecDriver) ReadArrayEnd() { - d.c = containerArrayEnd -} - -func (d *simpleDecDriver) ReadMapElemKey() { - d.c = containerMapKey -} - -func (d *simpleDecDriver) ReadMapElemValue() { - d.c = containerMapValue -} - -func (d *simpleDecDriver) ReadMapEnd() { - d.c = containerMapEnd -} - func (d *simpleDecDriver) decLen() int { switch d.bd % 8 { case 0: @@ -410,196 +305,116 @@ func (d *simpleDecDriver) decLen() int { case 1: return int(d.r.readn1()) case 2: - return int(bigen.Uint16(d.r.readx(2))) + return int(d.r.readUint16()) case 3: - ui := uint64(bigen.Uint32(d.r.readx(4))) - if chkOvf.Uint(ui, intBitsize) { - d.d.errorf("overflow integer: %v", ui) - return 0 - } + ui := uint64(d.r.readUint32()) + checkOverflow(ui, 0, intBitsize) return int(ui) case 4: - ui := bigen.Uint64(d.r.readx(8)) - if chkOvf.Uint(ui, intBitsize) { - d.d.errorf("overflow integer: %v", ui) - return 0 - } + ui := d.r.readUint64() + checkOverflow(ui, 0, intBitsize) return int(ui) } - d.d.errorf("cannot read length: bd%%8 must be in range 0..4. Got: %d", d.bd%8) + decErr("decLen: Cannot read length: bd%8 must be in range 0..4. Got: %d", d.bd%8) return -1 } -func (d *simpleDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *simpleDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *simpleDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdNil { - d.bdRead = false - return - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.bd >= simpleVdArray && d.bd <= simpleVdMap+4 { - if len(bs) == 0 && zerocopy { - bs = d.d.b[:] - } - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - - clen := d.decLen() - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(uint(clen)) - } else if len(bs) == 0 { - bs = d.d.b[:] - } - } - return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs) -} - -func (d *simpleDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdNil { - d.bdRead = false - return - } - if d.bd != simpleVdTime { - d.d.errorf("invalid descriptor for time.Time - expect 0x%x, received 0x%x", simpleVdTime, d.bd) - return - } +func (d *simpleDecDriver) decodeString() (s string) { + s = string(d.r.readn(d.decLen())) d.bdRead = false - clen := int(d.r.readn1()) - b := d.r.readx(uint(clen)) - if err := (&t).UnmarshalBinary(b); err != nil { - d.d.errorv(err) - } return } -func (d *simpleDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) +func (d *simpleDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) { + if clen := d.decLen(); clen > 0 { + // if no contents in stream, don't update the passed byteslice + if len(bs) != clen { + if len(bs) > clen { + bs = bs[:clen] + } else { + bs = make([]byte, clen) + } + bsOut = bs + changed = true + } + d.r.readb(bs) } + d.bdRead = false return } -func (d *simpleDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } +func (d *simpleDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) { switch d.bd { case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4: l := d.decLen() xtag = d.r.readn1() if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag. Got %b. Expecting: %v", xtag, tag) - return + decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag) } - if d.br { - xbs = d.r.readx(uint(l)) - } else { - xbs = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:]) - } - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - xbs = d.DecodeBytes(nil, true) + xbs = d.r.readn(l) + case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: + xbs, _ = d.decodeBytes(nil) default: - d.d.errorf("ext - %s - expecting extensions/bytearray, got: 0x%x", msgBadDesc, d.bd) - return + decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.bd) } d.bdRead = false return } -func (d *simpleDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.naked() - var decodeFurther bool +func (d *simpleDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) { + d.initReadNext() switch d.bd { case simpleVdNil: - n.v = valueTypeNil + vt = valueTypeNil case simpleVdFalse: - n.v = valueTypeBool - n.b = false + vt = valueTypeBool + v = false case simpleVdTrue: - n.v = valueTypeBool - n.b = true + vt = valueTypeBool + v = true case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3: - if d.h.SignedInteger { - n.v = valueTypeInt - n.i = d.DecodeInt64() - } else { - n.v = valueTypeUint - n.u = d.DecodeUint64() - } + vt = valueTypeUint + ui, _, _ := d.decIntAny() + v = ui case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3: - n.v = valueTypeInt - n.i = d.DecodeInt64() + vt = valueTypeInt + _, i, _ := d.decIntAny() + v = i case simpleVdFloat32: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() + vt = valueTypeFloat + v = d.decodeFloat(true) case simpleVdFloat64: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() - case simpleVdTime: - n.v = valueTypeTime - n.t = d.DecodeTime() - case simpleVdString, simpleVdString + 1, - simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: - n.v = valueTypeString - n.s = d.DecodeString() - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - decNakedReadRawBytes(d, d.d, n, d.h.RawToString) + vt = valueTypeFloat + v = d.decodeFloat(false) + case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: + vt = valueTypeString + v = d.decodeString() + case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: + vt = valueTypeBytes + v, _ = d.decodeBytes(nil) case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4: - n.v = valueTypeExt + vt = valueTypeExt l := d.decLen() - n.u = uint64(d.r.readn1()) - if d.br { - n.l = d.r.readx(uint(l)) - } else { - n.l = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:]) - } - case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, - simpleVdArray + 3, simpleVdArray + 4: - n.v = valueTypeArray + var re RawExt + re.Tag = d.r.readn1() + re.Data = d.r.readn(l) + v = &re + vt = valueTypeExt + case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4: + vt = valueTypeArray decodeFurther = true case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4: - n.v = valueTypeMap + vt = valueTypeMap decodeFurther = true default: - d.d.errorf("cannot infer value - %s 0x%x", msgBadDesc, d.bd) + decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.bd) } if !decodeFurther { d.bdRead = false } + return } //------------------------------------ @@ -607,12 +422,12 @@ func (d *simpleDecDriver) DecodeNaked() { // SimpleHandle is a Handle for a very simple encoding format. // // simple is a simplistic codec similar to binc, but not as compact. -// - Encoding of a value is always preceded by the descriptor byte (bd) +// - Encoding of a value is always preceeded by the descriptor byte (bd) // - True, false, nil are encoded fully in 1 byte (the descriptor) // - Integers (intXXX, uintXXX) are encoded in 1, 2, 4 or 8 bytes (plus a descriptor byte). // There are positive (uintXXX and intXXX >= 0) and negative (intXXX < 0) integers. // - Floats are encoded in 4 or 8 bytes (plus a descriptor byte) -// - Length of containers (strings, bytes, array, map, extensions) +// - Lenght of containers (strings, bytes, array, map, extensions) // are encoded in 0, 1, 2, 4 or 8 bytes. // Zero-length containers have no length encoded. // For others, the number of bytes is given by pow(2, bd%3) @@ -620,46 +435,26 @@ func (d *simpleDecDriver) DecodeNaked() { // - arrays are encoded as [bd] [length] [value]... // - extensions are encoded as [bd] [length] [tag] [byte]... // - strings/bytearrays are encoded as [bd] [length] [byte]... -// - time.Time are encoded as [bd] [length] [byte]... // // The full spec will be published soon. type SimpleHandle struct { BasicHandle - binaryEncodingType - noElemSeparators - // EncZeroValuesAsNil says to encode zero values for numbers, bool, string, etc as nil - EncZeroValuesAsNil bool - - // _ [1]uint64 // padding } -// Name returns the name of the handle: simple -func (h *SimpleHandle) Name() string { return "simple" } - -// SetBytesExt sets an extension -func (h *SimpleHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) -} - -func (h *SimpleHandle) hasElemSeparators() bool { return true } // as it implements Write(Map|Array)XXX - -func (h *SimpleHandle) newEncDriver(e *Encoder) encDriver { - return &simpleEncDriver{e: e, w: e.w, h: h} +func (h *SimpleHandle) newEncDriver(w encWriter) encDriver { + return &simpleEncDriver{w: w, h: h} } -func (h *SimpleHandle) newDecDriver(d *Decoder) decDriver { - return &simpleDecDriver{d: d, h: h, r: d.r, br: d.bytes} +func (h *SimpleHandle) newDecDriver(r decReader) decDriver { + return &simpleDecDriver{r: r, h: h} } -func (e *simpleEncDriver) reset() { - e.c = 0 - e.w = e.e.w +func (_ *SimpleHandle) writeExt() bool { + return true } -func (d *simpleDecDriver) reset() { - d.c = 0 - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false +func (h *SimpleHandle) getBasicHandle() *BasicHandle { + return &h.BasicHandle } var _ decDriver = (*simpleDecDriver)(nil) diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/test-cbor-goldens.json b/vendor/github.com/hashicorp/go-msgpack/codec/test-cbor-goldens.json deleted file mode 100644 index 9028586711e44..0000000000000 --- a/vendor/github.com/hashicorp/go-msgpack/codec/test-cbor-goldens.json +++ /dev/null @@ -1,639 +0,0 @@ -[ - { - "cbor": "AA==", - "hex": "00", - "roundtrip": true, - "decoded": 0 - }, - { - "cbor": "AQ==", - "hex": "01", - "roundtrip": true, - "decoded": 1 - }, - { - "cbor": "Cg==", - "hex": "0a", - "roundtrip": true, - "decoded": 10 - }, - { - "cbor": "Fw==", - "hex": "17", - "roundtrip": true, - "decoded": 23 - }, - { - "cbor": "GBg=", - "hex": "1818", - "roundtrip": true, - "decoded": 24 - }, - { - "cbor": "GBk=", - "hex": "1819", - "roundtrip": true, - "decoded": 25 - }, - { - "cbor": "GGQ=", - "hex": "1864", - "roundtrip": true, - "decoded": 100 - }, - { - "cbor": "GQPo", - "hex": "1903e8", - "roundtrip": true, - "decoded": 1000 - }, - { - "cbor": "GgAPQkA=", - "hex": "1a000f4240", - "roundtrip": true, - "decoded": 1000000 - }, - { - "cbor": "GwAAAOjUpRAA", - "hex": "1b000000e8d4a51000", - "roundtrip": true, - "decoded": 1000000000000 - }, - { - "cbor": "G///////////", - "hex": "1bffffffffffffffff", - "roundtrip": true, - "decoded": 18446744073709551615 - }, - { - "cbor": "wkkBAAAAAAAAAAA=", - "hex": "c249010000000000000000", - "roundtrip": true, - "decoded": 18446744073709551616 - }, - { - "cbor": "O///////////", - "hex": "3bffffffffffffffff", - "roundtrip": true, - "decoded": -18446744073709551616, - "skip": true - }, - { - "cbor": "w0kBAAAAAAAAAAA=", - "hex": "c349010000000000000000", - "roundtrip": true, - "decoded": -18446744073709551617 - }, - { - "cbor": "IA==", - "hex": "20", - "roundtrip": true, - "decoded": -1 - }, - { - "cbor": "KQ==", - "hex": "29", - "roundtrip": true, - "decoded": -10 - }, - { - "cbor": "OGM=", - "hex": "3863", - "roundtrip": true, - "decoded": -100 - }, - { - "cbor": "OQPn", - "hex": "3903e7", - "roundtrip": true, - "decoded": -1000 - }, - { - "cbor": "+QAA", - "hex": "f90000", - "roundtrip": true, - "decoded": 0.0 - }, - { - "cbor": "+YAA", - "hex": "f98000", - "roundtrip": true, - "decoded": -0.0 - }, - { - "cbor": "+TwA", - "hex": "f93c00", - "roundtrip": true, - "decoded": 1.0 - }, - { - "cbor": "+z/xmZmZmZma", - "hex": "fb3ff199999999999a", - "roundtrip": true, - "decoded": 1.1 - }, - { - "cbor": "+T4A", - "hex": "f93e00", - "roundtrip": true, - "decoded": 1.5 - }, - { - "cbor": "+Xv/", - "hex": "f97bff", - "roundtrip": true, - "decoded": 65504.0 - }, - { - "cbor": "+kfDUAA=", - "hex": "fa47c35000", - "roundtrip": true, - "decoded": 100000.0 - }, - { - "cbor": "+n9///8=", - "hex": "fa7f7fffff", - "roundtrip": true, - "decoded": 3.4028234663852886e+38 - }, - { - "cbor": "+3435DyIAHWc", - "hex": "fb7e37e43c8800759c", - "roundtrip": true, - "decoded": 1.0e+300 - }, - { - "cbor": "+QAB", - "hex": "f90001", - "roundtrip": true, - "decoded": 5.960464477539063e-08 - }, - { - "cbor": "+QQA", - "hex": "f90400", - "roundtrip": true, - "decoded": 6.103515625e-05 - }, - { - "cbor": "+cQA", - "hex": "f9c400", - "roundtrip": true, - "decoded": -4.0 - }, - { - "cbor": "+8AQZmZmZmZm", - "hex": "fbc010666666666666", - "roundtrip": true, - "decoded": -4.1 - }, - { - "cbor": "+XwA", - "hex": "f97c00", - "roundtrip": true, - "diagnostic": "Infinity" - }, - { - "cbor": "+X4A", - "hex": "f97e00", - "roundtrip": true, - "diagnostic": "NaN" - }, - { - "cbor": "+fwA", - "hex": "f9fc00", - "roundtrip": true, - "diagnostic": "-Infinity" - }, - { - "cbor": "+n+AAAA=", - "hex": "fa7f800000", - "roundtrip": false, - "diagnostic": "Infinity" - }, - { - "cbor": "+n/AAAA=", - "hex": "fa7fc00000", - "roundtrip": false, - "diagnostic": "NaN" - }, - { - "cbor": "+v+AAAA=", - "hex": "faff800000", - "roundtrip": false, - "diagnostic": "-Infinity" - }, - { - "cbor": "+3/wAAAAAAAA", - "hex": "fb7ff0000000000000", - "roundtrip": false, - "diagnostic": "Infinity" - }, - { - "cbor": "+3/4AAAAAAAA", - "hex": "fb7ff8000000000000", - "roundtrip": false, - "diagnostic": "NaN" - }, - { - "cbor": "+//wAAAAAAAA", - "hex": "fbfff0000000000000", - "roundtrip": false, - "diagnostic": "-Infinity" - }, - { - "cbor": "9A==", - "hex": "f4", - "roundtrip": true, - "decoded": false - }, - { - "cbor": "9Q==", - "hex": "f5", - "roundtrip": true, - "decoded": true - }, - { - "cbor": "9g==", - "hex": "f6", - "roundtrip": true, - "decoded": null - }, - { - "cbor": "9w==", - "hex": "f7", - "roundtrip": true, - "diagnostic": "undefined" - }, - { - "cbor": "8A==", - "hex": "f0", - "roundtrip": true, - "diagnostic": "simple(16)" - }, - { - "cbor": "+Bg=", - "hex": "f818", - "roundtrip": true, - "diagnostic": "simple(24)" - }, - { - "cbor": "+P8=", - "hex": "f8ff", - "roundtrip": true, - "diagnostic": "simple(255)" - }, - { - "cbor": "wHQyMDEzLTAzLTIxVDIwOjA0OjAwWg==", - "hex": "c074323031332d30332d32315432303a30343a30305a", - "roundtrip": true, - "diagnostic": "0(\"2013-03-21T20:04:00Z\")" - }, - { - "cbor": "wRpRS2ew", - "hex": "c11a514b67b0", - "roundtrip": true, - "diagnostic": "1(1363896240)" - }, - { - "cbor": "wftB1FLZ7CAAAA==", - "hex": "c1fb41d452d9ec200000", - "roundtrip": true, - "diagnostic": "1(1363896240.5)" - }, - { - "cbor": "10QBAgME", - "hex": "d74401020304", - "roundtrip": true, - "diagnostic": "23(h'01020304')" - }, - { - "cbor": "2BhFZElFVEY=", - "hex": "d818456449455446", - "roundtrip": true, - "diagnostic": "24(h'6449455446')" - }, - { - "cbor": "2CB2aHR0cDovL3d3dy5leGFtcGxlLmNvbQ==", - "hex": "d82076687474703a2f2f7777772e6578616d706c652e636f6d", - "roundtrip": true, - "diagnostic": "32(\"http://www.example.com\")" - }, - { - "cbor": "QA==", - "hex": "40", - "roundtrip": true, - "diagnostic": "h''" - }, - { - "cbor": "RAECAwQ=", - "hex": "4401020304", - "roundtrip": true, - "diagnostic": "h'01020304'" - }, - { - "cbor": "YA==", - "hex": "60", - "roundtrip": true, - "decoded": "" - }, - { - "cbor": "YWE=", - "hex": "6161", - "roundtrip": true, - "decoded": "a" - }, - { - "cbor": "ZElFVEY=", - "hex": "6449455446", - "roundtrip": true, - "decoded": "IETF" - }, - { - "cbor": "YiJc", - "hex": "62225c", - "roundtrip": true, - "decoded": "\"\\" - }, - { - "cbor": "YsO8", - "hex": "62c3bc", - "roundtrip": true, - "decoded": "ü" - }, - { - "cbor": "Y+awtA==", - "hex": "63e6b0b4", - "roundtrip": true, - "decoded": "水" - }, - { - "cbor": "ZPCQhZE=", - "hex": "64f0908591", - "roundtrip": true, - "decoded": "𐅑" - }, - { - "cbor": "gA==", - "hex": "80", - "roundtrip": true, - "decoded": [ - - ] - }, - { - "cbor": "gwECAw==", - "hex": "83010203", - "roundtrip": true, - "decoded": [ - 1, - 2, - 3 - ] - }, - { - "cbor": "gwGCAgOCBAU=", - "hex": "8301820203820405", - "roundtrip": true, - "decoded": [ - 1, - [ - 2, - 3 - ], - [ - 4, - 5 - ] - ] - }, - { - "cbor": "mBkBAgMEBQYHCAkKCwwNDg8QERITFBUWFxgYGBk=", - "hex": "98190102030405060708090a0b0c0d0e0f101112131415161718181819", - "roundtrip": true, - "decoded": [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25 - ] - }, - { - "cbor": "oA==", - "hex": "a0", - "roundtrip": true, - "decoded": { - } - }, - { - "cbor": "ogECAwQ=", - "hex": "a201020304", - "roundtrip": true, - "skip": true, - "diagnostic": "{1: 2, 3: 4}" - }, - { - "cbor": "omFhAWFiggID", - "hex": "a26161016162820203", - "roundtrip": true, - "decoded": { - "a": 1, - "b": [ - 2, - 3 - ] - } - }, - { - "cbor": "gmFhoWFiYWM=", - "hex": "826161a161626163", - "roundtrip": true, - "decoded": [ - "a", - { - "b": "c" - } - ] - }, - { - "cbor": "pWFhYUFhYmFCYWNhQ2FkYURhZWFF", - "hex": "a56161614161626142616361436164614461656145", - "roundtrip": true, - "decoded": { - "a": "A", - "b": "B", - "c": "C", - "d": "D", - "e": "E" - } - }, - { - "cbor": "X0IBAkMDBAX/", - "hex": "5f42010243030405ff", - "roundtrip": false, - "skip": true, - "diagnostic": "(_ h'0102', h'030405')" - }, - { - "cbor": "f2VzdHJlYWRtaW5n/w==", - "hex": "7f657374726561646d696e67ff", - "roundtrip": false, - "decoded": "streaming" - }, - { - "cbor": "n/8=", - "hex": "9fff", - "roundtrip": false, - "decoded": [ - - ] - }, - { - "cbor": "nwGCAgOfBAX//w==", - "hex": "9f018202039f0405ffff", - "roundtrip": false, - "decoded": [ - 1, - [ - 2, - 3 - ], - [ - 4, - 5 - ] - ] - }, - { - "cbor": "nwGCAgOCBAX/", - "hex": "9f01820203820405ff", - "roundtrip": false, - "decoded": [ - 1, - [ - 2, - 3 - ], - [ - 4, - 5 - ] - ] - }, - { - "cbor": "gwGCAgOfBAX/", - "hex": "83018202039f0405ff", - "roundtrip": false, - "decoded": [ - 1, - [ - 2, - 3 - ], - [ - 4, - 5 - ] - ] - }, - { - "cbor": "gwGfAgP/ggQF", - "hex": "83019f0203ff820405", - "roundtrip": false, - "decoded": [ - 1, - [ - 2, - 3 - ], - [ - 4, - 5 - ] - ] - }, - { - "cbor": "nwECAwQFBgcICQoLDA0ODxAREhMUFRYXGBgYGf8=", - "hex": "9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff", - "roundtrip": false, - "decoded": [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25 - ] - }, - { - "cbor": "v2FhAWFinwID//8=", - "hex": "bf61610161629f0203ffff", - "roundtrip": false, - "decoded": { - "a": 1, - "b": [ - 2, - 3 - ] - } - }, - { - "cbor": "gmFhv2FiYWP/", - "hex": "826161bf61626163ff", - "roundtrip": false, - "decoded": [ - "a", - { - "b": "c" - } - ] - }, - { - "cbor": "v2NGdW71Y0FtdCH/", - "hex": "bf6346756ef563416d7421ff", - "roundtrip": false, - "decoded": { - "Fun": true, - "Amt": -2 - } - } -] diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/time.go b/vendor/github.com/hashicorp/go-msgpack/codec/time.go new file mode 100644 index 0000000000000..c86d65328d76a --- /dev/null +++ b/vendor/github.com/hashicorp/go-msgpack/codec/time.go @@ -0,0 +1,193 @@ +// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. +// Use of this source code is governed by a BSD-style license found in the LICENSE file. + +package codec + +import ( + "time" +) + +var ( + timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} +) + +// EncodeTime encodes a time.Time as a []byte, including +// information on the instant in time and UTC offset. +// +// Format Description +// +// A timestamp is composed of 3 components: +// +// - secs: signed integer representing seconds since unix epoch +// - nsces: unsigned integer representing fractional seconds as a +// nanosecond offset within secs, in the range 0 <= nsecs < 1e9 +// - tz: signed integer representing timezone offset in minutes east of UTC, +// and a dst (daylight savings time) flag +// +// When encoding a timestamp, the first byte is the descriptor, which +// defines which components are encoded and how many bytes are used to +// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it +// is not encoded in the byte array explicitly*. +// +// Descriptor 8 bits are of the form `A B C DDD EE`: +// A: Is secs component encoded? 1 = true +// B: Is nsecs component encoded? 1 = true +// C: Is tz component encoded? 1 = true +// DDD: Number of extra bytes for secs (range 0-7). +// If A = 1, secs encoded in DDD+1 bytes. +// If A = 0, secs is not encoded, and is assumed to be 0. +// If A = 1, then we need at least 1 byte to encode secs. +// DDD says the number of extra bytes beyond that 1. +// E.g. if DDD=0, then secs is represented in 1 byte. +// if DDD=2, then secs is represented in 3 bytes. +// EE: Number of extra bytes for nsecs (range 0-3). +// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above) +// +// Following the descriptor bytes, subsequent bytes are: +// +// secs component encoded in `DDD + 1` bytes (if A == 1) +// nsecs component encoded in `EE + 1` bytes (if B == 1) +// tz component encoded in 2 bytes (if C == 1) +// +// secs and nsecs components are integers encoded in a BigEndian +// 2-complement encoding format. +// +// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to +// Least significant bit 0 are described below: +// +// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes). +// Bit 15 = have\_dst: set to 1 if we set the dst flag. +// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not. +// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format. +// +func encodeTime(t time.Time) []byte { + //t := rv.Interface().(time.Time) + tsecs, tnsecs := t.Unix(), t.Nanosecond() + var ( + bd byte + btmp [8]byte + bs [16]byte + i int = 1 + ) + l := t.Location() + if l == time.UTC { + l = nil + } + if tsecs != 0 { + bd = bd | 0x80 + bigen.PutUint64(btmp[:], uint64(tsecs)) + f := pruneSignExt(btmp[:], tsecs >= 0) + bd = bd | (byte(7-f) << 2) + copy(bs[i:], btmp[f:]) + i = i + (8 - f) + } + if tnsecs != 0 { + bd = bd | 0x40 + bigen.PutUint32(btmp[:4], uint32(tnsecs)) + f := pruneSignExt(btmp[:4], true) + bd = bd | byte(3-f) + copy(bs[i:], btmp[f:4]) + i = i + (4 - f) + } + if l != nil { + bd = bd | 0x20 + // Note that Go Libs do not give access to dst flag. + _, zoneOffset := t.Zone() + //zoneName, zoneOffset := t.Zone() + zoneOffset /= 60 + z := uint16(zoneOffset) + bigen.PutUint16(btmp[:2], z) + // clear dst flags + bs[i] = btmp[0] & 0x3f + bs[i+1] = btmp[1] + i = i + 2 + } + bs[0] = bd + return bs[0:i] +} + +// DecodeTime decodes a []byte into a time.Time. +func decodeTime(bs []byte) (tt time.Time, err error) { + bd := bs[0] + var ( + tsec int64 + tnsec uint32 + tz uint16 + i byte = 1 + i2 byte + n byte + ) + if bd&(1<<7) != 0 { + var btmp [8]byte + n = ((bd >> 2) & 0x7) + 1 + i2 = i + n + copy(btmp[8-n:], bs[i:i2]) + //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it) + if bs[i]&(1<<7) != 0 { + copy(btmp[0:8-n], bsAll0xff) + //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff } + } + i = i2 + tsec = int64(bigen.Uint64(btmp[:])) + } + if bd&(1<<6) != 0 { + var btmp [4]byte + n = (bd & 0x3) + 1 + i2 = i + n + copy(btmp[4-n:], bs[i:i2]) + i = i2 + tnsec = bigen.Uint32(btmp[:]) + } + if bd&(1<<5) == 0 { + tt = time.Unix(tsec, int64(tnsec)).UTC() + return + } + // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name. + // However, we need name here, so it can be shown when time is printed. + // Zone name is in form: UTC-08:00. + // Note that Go Libs do not give access to dst flag, so we ignore dst bits + + i2 = i + 2 + tz = bigen.Uint16(bs[i:i2]) + i = i2 + // sign extend sign bit into top 2 MSB (which were dst bits): + if tz&(1<<13) == 0 { // positive + tz = tz & 0x3fff //clear 2 MSBs: dst bits + } else { // negative + tz = tz | 0xc000 //set 2 MSBs: dst bits + //tzname[3] = '-' (TODO: verify. this works here) + } + tzint := int16(tz) + if tzint == 0 { + tt = time.Unix(tsec, int64(tnsec)).UTC() + } else { + // For Go Time, do not use a descriptive timezone. + // It's unnecessary, and makes it harder to do a reflect.DeepEqual. + // The Offset already tells what the offset should be, if not on UTC and unknown zone name. + // var zoneName = timeLocUTCName(tzint) + tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60)) + } + return +} + +func timeLocUTCName(tzint int16) string { + if tzint == 0 { + return "UTC" + } + var tzname = []byte("UTC+00:00") + //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below. + //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first + var tzhr, tzmin int16 + if tzint < 0 { + tzname[3] = '-' // (TODO: verify. this works here) + tzhr, tzmin = -tzint/60, (-tzint)%60 + } else { + tzhr, tzmin = tzint/60, tzint%60 + } + tzname[4] = timeDigits[tzhr/10] + tzname[5] = timeDigits[tzhr%10] + tzname[7] = timeDigits[tzmin/10] + tzname[8] = timeDigits[tzmin%10] + return string(tzname) + //return time.FixedZone(string(tzname), int(tzint)*60) +} diff --git a/vendor/golang.org/x/net/http2/h2c/h2c.go b/vendor/golang.org/x/net/http2/h2c/h2c.go new file mode 100644 index 0000000000000..2d6bf861b975b --- /dev/null +++ b/vendor/golang.org/x/net/http2/h2c/h2c.go @@ -0,0 +1,240 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package h2c implements the unencrypted "h2c" form of HTTP/2. +// +// The h2c protocol is the non-TLS version of HTTP/2 which is not available from +// net/http or golang.org/x/net/http2. +package h2c + +import ( + "bufio" + "bytes" + "encoding/base64" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/textproto" + "os" + "strings" + + "golang.org/x/net/http/httpguts" + "golang.org/x/net/http2" +) + +var ( + http2VerboseLogs bool +) + +func init() { + e := os.Getenv("GODEBUG") + if strings.Contains(e, "http2debug=1") || strings.Contains(e, "http2debug=2") { + http2VerboseLogs = true + } +} + +// h2cHandler is a Handler which implements h2c by hijacking the HTTP/1 traffic +// that should be h2c traffic. There are two ways to begin a h2c connection +// (RFC 7540 Section 3.2 and 3.4): (1) Starting with Prior Knowledge - this +// works by starting an h2c connection with a string of bytes that is valid +// HTTP/1, but unlikely to occur in practice and (2) Upgrading from HTTP/1 to +// h2c - this works by using the HTTP/1 Upgrade header to request an upgrade to +// h2c. When either of those situations occur we hijack the HTTP/1 connection, +// convert it to an HTTP/2 connection and pass the net.Conn to http2.ServeConn. +type h2cHandler struct { + Handler http.Handler + s *http2.Server +} + +// NewHandler returns an http.Handler that wraps h, intercepting any h2c +// traffic. If a request is an h2c connection, it's hijacked and redirected to +// s.ServeConn. Otherwise the returned Handler just forwards requests to h. This +// works because h2c is designed to be parseable as valid HTTP/1, but ignored by +// any HTTP server that does not handle h2c. Therefore we leverage the HTTP/1 +// compatible parts of the Go http library to parse and recognize h2c requests. +// Once a request is recognized as h2c, we hijack the connection and convert it +// to an HTTP/2 connection which is understandable to s.ServeConn. (s.ServeConn +// understands HTTP/2 except for the h2c part of it.) +// +// The first request on an h2c connection is read entirely into memory before +// the Handler is called. To limit the memory consumed by this request, wrap +// the result of NewHandler in an http.MaxBytesHandler. +func NewHandler(h http.Handler, s *http2.Server) http.Handler { + return &h2cHandler{ + Handler: h, + s: s, + } +} + +// extractServer extracts existing http.Server instance from http.Request or create an empty http.Server +func extractServer(r *http.Request) *http.Server { + server, ok := r.Context().Value(http.ServerContextKey).(*http.Server) + if ok { + return server + } + return new(http.Server) +} + +// ServeHTTP implement the h2c support that is enabled by h2c.GetH2CHandler. +func (s h2cHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Handle h2c with prior knowledge (RFC 7540 Section 3.4) + if r.Method == "PRI" && len(r.Header) == 0 && r.URL.Path == "*" && r.Proto == "HTTP/2.0" { + if http2VerboseLogs { + log.Print("h2c: attempting h2c with prior knowledge.") + } + conn, err := initH2CWithPriorKnowledge(w) + if err != nil { + if http2VerboseLogs { + log.Printf("h2c: error h2c with prior knowledge: %v", err) + } + return + } + defer conn.Close() + s.s.ServeConn(conn, &http2.ServeConnOpts{ + Context: r.Context(), + BaseConfig: extractServer(r), + Handler: s.Handler, + SawClientPreface: true, + }) + return + } + // Handle Upgrade to h2c (RFC 7540 Section 3.2) + if isH2CUpgrade(r.Header) { + conn, settings, err := h2cUpgrade(w, r) + if err != nil { + if http2VerboseLogs { + log.Printf("h2c: error h2c upgrade: %v", err) + } + w.WriteHeader(http.StatusInternalServerError) + return + } + defer conn.Close() + s.s.ServeConn(conn, &http2.ServeConnOpts{ + Context: r.Context(), + BaseConfig: extractServer(r), + Handler: s.Handler, + UpgradeRequest: r, + Settings: settings, + }) + return + } + s.Handler.ServeHTTP(w, r) + return +} + +// initH2CWithPriorKnowledge implements creating a h2c connection with prior +// knowledge (Section 3.4) and creates a net.Conn suitable for http2.ServeConn. +// All we have to do is look for the client preface that is suppose to be part +// of the body, and reforward the client preface on the net.Conn this function +// creates. +func initH2CWithPriorKnowledge(w http.ResponseWriter) (net.Conn, error) { + hijacker, ok := w.(http.Hijacker) + if !ok { + return nil, errors.New("h2c: connection does not support Hijack") + } + conn, rw, err := hijacker.Hijack() + if err != nil { + return nil, err + } + + const expectedBody = "SM\r\n\r\n" + + buf := make([]byte, len(expectedBody)) + n, err := io.ReadFull(rw, buf) + if err != nil { + return nil, fmt.Errorf("h2c: error reading client preface: %s", err) + } + + if string(buf[:n]) == expectedBody { + return newBufConn(conn, rw), nil + } + + conn.Close() + return nil, errors.New("h2c: invalid client preface") +} + +// h2cUpgrade establishes a h2c connection using the HTTP/1 upgrade (Section 3.2). +func h2cUpgrade(w http.ResponseWriter, r *http.Request) (_ net.Conn, settings []byte, err error) { + settings, err = getH2Settings(r.Header) + if err != nil { + return nil, nil, err + } + hijacker, ok := w.(http.Hijacker) + if !ok { + return nil, nil, errors.New("h2c: connection does not support Hijack") + } + + body, err := io.ReadAll(r.Body) + if err != nil { + return nil, nil, err + } + r.Body = io.NopCloser(bytes.NewBuffer(body)) + + conn, rw, err := hijacker.Hijack() + if err != nil { + return nil, nil, err + } + + rw.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: h2c\r\n\r\n")) + return newBufConn(conn, rw), settings, nil +} + +// isH2CUpgrade returns true if the header properly request an upgrade to h2c +// as specified by Section 3.2. +func isH2CUpgrade(h http.Header) bool { + return httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Upgrade")], "h2c") && + httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Connection")], "HTTP2-Settings") +} + +// getH2Settings returns the settings in the HTTP2-Settings header. +func getH2Settings(h http.Header) ([]byte, error) { + vals, ok := h[textproto.CanonicalMIMEHeaderKey("HTTP2-Settings")] + if !ok { + return nil, errors.New("missing HTTP2-Settings header") + } + if len(vals) != 1 { + return nil, fmt.Errorf("expected 1 HTTP2-Settings. Got: %v", vals) + } + settings, err := base64.RawURLEncoding.DecodeString(vals[0]) + if err != nil { + return nil, err + } + return settings, nil +} + +func newBufConn(conn net.Conn, rw *bufio.ReadWriter) net.Conn { + rw.Flush() + if rw.Reader.Buffered() == 0 { + // If there's no buffered data to be read, + // we can just discard the bufio.ReadWriter. + return conn + } + return &bufConn{conn, rw.Reader} +} + +// bufConn wraps a net.Conn, but reads drain the bufio.Reader first. +type bufConn struct { + net.Conn + *bufio.Reader +} + +func (c *bufConn) Read(p []byte) (int, error) { + if c.Reader == nil { + return c.Conn.Read(p) + } + n := c.Reader.Buffered() + if n == 0 { + c.Reader = nil + return c.Conn.Read(p) + } + if n < len(p) { + p = p[:n] + } + return c.Reader.Read(p) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 06dcc4f304446..a513055e42f06 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -988,6 +988,17 @@ github.com/gorilla/mux # github.com/gorilla/websocket v1.5.3 ## explicit; go 1.12 github.com/gorilla/websocket +# github.com/grafana/ckit v0.0.0-20250109002736-4ca45886e452 +## explicit; go 1.20 +github.com/grafana/ckit +github.com/grafana/ckit/internal/chash +github.com/grafana/ckit/internal/gossiphttp +github.com/grafana/ckit/internal/lamport +github.com/grafana/ckit/internal/messages +github.com/grafana/ckit/internal/metricsutil +github.com/grafana/ckit/internal/queue +github.com/grafana/ckit/peer +github.com/grafana/ckit/shard # github.com/grafana/cloudflare-go v0.0.0-20230110200409-c627cf6792f2 ## explicit; go 1.17 github.com/grafana/cloudflare-go @@ -1088,8 +1099,8 @@ github.com/hashicorp/go-hclog # github.com/hashicorp/go-immutable-radix v1.3.1 ## explicit github.com/hashicorp/go-immutable-radix -# github.com/hashicorp/go-msgpack v1.1.5 -## explicit; go 1.13 +# github.com/hashicorp/go-msgpack v0.5.5 +## explicit github.com/hashicorp/go-msgpack/codec # github.com/hashicorp/go-multierror v1.1.1 ## explicit; go 1.13 @@ -1114,7 +1125,7 @@ github.com/hashicorp/golang-lru/simplelru github.com/hashicorp/golang-lru/v2 github.com/hashicorp/golang-lru/v2/internal github.com/hashicorp/golang-lru/v2/simplelru -# github.com/hashicorp/memberlist v0.5.1 => github.com/grafana/memberlist v0.3.1-0.20220714140823-09ffed8adbbe +# github.com/hashicorp/memberlist v0.5.2 => github.com/grafana/memberlist v0.3.1-0.20220714140823-09ffed8adbbe ## explicit; go 1.12 github.com/hashicorp/memberlist # github.com/hashicorp/serf v0.10.1 @@ -1924,6 +1935,7 @@ golang.org/x/net/html/atom golang.org/x/net/http/httpguts golang.org/x/net/http/httpproxy golang.org/x/net/http2 +golang.org/x/net/http2/h2c golang.org/x/net/http2/hpack golang.org/x/net/idna golang.org/x/net/internal/httpcommon
feat
Distributed Operational UI (#16097)
dac64c4d474093f7689adae4564f6e805973f2fb
2022-03-30 23:41:45
Periklis Tsirakidis
operator: Add missing label matcher for openshift logging tenant mode (#5729)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index ba0661bf9b32e..abe2fd8643adc 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [5729](https://github.com/grafana/loki/pull/5729) **periklis**: Add missing label matcher for openshift logging tenant mode (OpenShift) - [5691](https://github.com/grafana/loki/pull/5691) **sasagarw**: Fix immediate reset of degraded condition - [5704](https://github.com/grafana/loki/pull/5704) **xperimental**: Update operator-sdk to 1.18.1 - [5693](https://github.com/grafana/loki/pull/5693) **periklis**: Replace frontend_worker parallelism with match_max_concurrent diff --git a/operator/internal/manifests/gateway_tenants_test.go b/operator/internal/manifests/gateway_tenants_test.go index 5606c3f5ccf54..a13b510edc8aa 100644 --- a/operator/internal/manifests/gateway_tenants_test.go +++ b/operator/internal/manifests/gateway_tenants_test.go @@ -200,6 +200,7 @@ func TestConfigureDeploymentForMode(t *testing.T) { Args: []string{ "--log.level=warn", "--opa.package=lokistack", + "--opa.matcher=kubernetes_namespace_name", "--web.listen=:8082", "--web.internal.listen=:8083", "--web.healthchecks.url=http://localhost:8082", @@ -293,6 +294,7 @@ func TestConfigureDeploymentForMode(t *testing.T) { Args: []string{ "--log.level=warn", "--opa.package=lokistack", + "--opa.matcher=kubernetes_namespace_name", "--web.listen=:8082", "--web.internal.listen=:8083", "--web.healthchecks.url=http://localhost:8082", @@ -430,6 +432,7 @@ func TestConfigureDeploymentForMode(t *testing.T) { Args: []string{ "--log.level=warn", "--opa.package=lokistack", + "--opa.matcher=kubernetes_namespace_name", "--web.listen=:8082", "--web.internal.listen=:8083", "--web.healthchecks.url=http://localhost:8082", diff --git a/operator/internal/manifests/openshift/opa_openshift.go b/operator/internal/manifests/openshift/opa_openshift.go index bf2d377b470c3..0fbb26e385d58 100644 --- a/operator/internal/manifests/openshift/opa_openshift.go +++ b/operator/internal/manifests/openshift/opa_openshift.go @@ -10,12 +10,13 @@ import ( ) const ( - envRelatedImageOPA = "RELATED_IMAGE_OPA" - defaultOPAImage = "quay.io/observatorium/opa-openshift:latest" - opaContainerName = "opa" - opaDefaultPackage = "lokistack" - opaDefaultAPIGroup = "loki.grafana.com" - opaMetricsPortName = "opa-metrics" + envRelatedImageOPA = "RELATED_IMAGE_OPA" + defaultOPAImage = "quay.io/observatorium/opa-openshift:latest" + opaContainerName = "opa" + opaDefaultPackage = "lokistack" + opaDefaultAPIGroup = "loki.grafana.com" + opaMetricsPortName = "opa-metrics" + opaDefaultLabelMatcher = "kubernetes_namespace_name" ) func newOPAOpenShiftContainer(sercretVolumeName, tlsDir, certFile, keyFile string, withTLS bool) corev1.Container { @@ -35,6 +36,7 @@ func newOPAOpenShiftContainer(sercretVolumeName, tlsDir, certFile, keyFile strin args = []string{ "--log.level=warn", fmt.Sprintf("--opa.package=%s", opaDefaultPackage), + fmt.Sprintf("--opa.matcher=%s", opaDefaultLabelMatcher), fmt.Sprintf("--web.listen=:%d", GatewayOPAHTTPPort), fmt.Sprintf("--web.internal.listen=:%d", GatewayOPAInternalPort), fmt.Sprintf("--web.healthchecks.url=http://localhost:%d", GatewayOPAHTTPPort),
operator
Add missing label matcher for openshift logging tenant mode (#5729)
8ca1d1e0a4c43b6cc22bdbee85d64d4cca8330c4
2023-08-08 17:44:29
Ed Welch
loki: simplify the FetchChunks method and optimize the experimental l2 cache a little more (#10160)
false
diff --git a/cmd/migrate/main.go b/cmd/migrate/main.go index f6d22f1b34ddf..9f7e584597fb7 100644 --- a/cmd/migrate/main.go +++ b/cmd/migrate/main.go @@ -8,7 +8,6 @@ import ( "net/http" _ "net/http/pprof" "os" - "sort" "sync" "time" @@ -330,28 +329,19 @@ func (m *chunkMover) moveChunks(ctx context.Context, threadID int, syncRangeCh < chunks := schemaGroups[i][j:k] //log.Printf("%v Processing chunks %v-%v of %v\n", threadID, j, k, len(schemaGroups[i])) - keys := make([]string, 0, len(chunks)) chks := make([]chunk.Chunk, 0, len(chunks)) - // FetchChunks requires chunks to be ordered by external key. - sort.Slice(chunks, func(x, y int) bool { - return m.schema.ExternalKey(chunks[x].ChunkRef) < m.schema.ExternalKey(chunks[y].ChunkRef) - }) - for _, chk := range chunks { - key := m.schema.ExternalKey(chk.ChunkRef) - keys = append(keys, key) - chks = append(chks, chk) - } - finalChks, err := f.FetchChunks(m.ctx, chks, keys) + chks = append(chks, chunks...) + + finalChks, err := f.FetchChunks(m.ctx, chks) if err != nil { log.Println(threadID, "Error retrieving chunks, will go through them one by one:", err) finalChks = make([]chunk.Chunk, 0, len(chunks)) for i := range chks { onechunk := []chunk.Chunk{chunks[i]} - onekey := []string{keys[i]} var retry int for retry = 4; retry >= 0; retry-- { - onechunk, err = f.FetchChunks(m.ctx, onechunk, onekey) + onechunk, err = f.FetchChunks(m.ctx, onechunk) if err != nil { if retry == 0 { log.Println(threadID, "Final error retrieving chunks, giving up:", err) diff --git a/pkg/storage/batch.go b/pkg/storage/batch.go index 76ea1dd583d43..a1a0ec9784ea4 100644 --- a/pkg/storage/batch.go +++ b/pkg/storage/batch.go @@ -701,21 +701,15 @@ func fetchLazyChunks(ctx context.Context, s config.SchemaConfig, chunks []*LazyC errChan := make(chan error) for f, chunks := range chksByFetcher { go func(fetcher *fetcher.Fetcher, chunks []*LazyChunk) { - keys := make([]string, 0, len(chunks)) chks := make([]chunk.Chunk, 0, len(chunks)) index := make(map[string]*LazyChunk, len(chunks)) - // FetchChunks requires chunks to be ordered by external key. - sort.Slice(chunks, func(i, j int) bool { - return s.ExternalKey(chunks[i].Chunk.ChunkRef) < s.ExternalKey(chunks[j].Chunk.ChunkRef) - }) for _, chk := range chunks { key := s.ExternalKey(chk.Chunk.ChunkRef) - keys = append(keys, key) chks = append(chks, chk.Chunk) index[key] = chk } - chks, err := fetcher.FetchChunks(ctx, chks, keys) + chks, err := fetcher.FetchChunks(ctx, chks) if ctx.Err() != nil { errChan <- nil return diff --git a/pkg/storage/chunk/cache/cache_test.go b/pkg/storage/chunk/cache/cache_test.go index 0387e4d5d815c..c054636d061c7 100644 --- a/pkg/storage/chunk/cache/cache_test.go +++ b/pkg/storage/chunk/cache/cache_test.go @@ -117,7 +117,7 @@ func testCacheMultiple(t *testing.T, cache cache.Cache, keys []string, chunks [] require.Equal(t, chunks, result) } -func testChunkFetcher(t *testing.T, c cache.Cache, keys []string, chunks []chunk.Chunk) { +func testChunkFetcher(t *testing.T, c cache.Cache, chunks []chunk.Chunk) { s := config.SchemaConfig{ Configs: []config.PeriodConfig{ { @@ -132,7 +132,7 @@ func testChunkFetcher(t *testing.T, c cache.Cache, keys []string, chunks []chunk require.NoError(t, err) defer fetcher.Stop() - found, err := fetcher.FetchChunks(context.Background(), chunks, keys) + found, err := fetcher.FetchChunks(context.Background(), chunks) require.NoError(t, err) sort.Sort(byExternalKey{found, s}) sort.Sort(byExternalKey{chunks, s}) @@ -181,7 +181,7 @@ func testCache(t *testing.T, cache cache.Cache) { testCacheMiss(t, cache) }) t.Run("Fetcher", func(t *testing.T) { - testChunkFetcher(t, cache, keys, chunks) + testChunkFetcher(t, cache, chunks) }) } diff --git a/pkg/storage/chunk/cache/mock.go b/pkg/storage/chunk/cache/mock.go index d181bd19f2527..d8e62c16059dd 100644 --- a/pkg/storage/chunk/cache/mock.go +++ b/pkg/storage/chunk/cache/mock.go @@ -11,10 +11,12 @@ type MockCache interface { Cache NumKeyUpdates() int GetInternal() map[string][]byte + KeysRequested() int } type mockCache struct { numKeyUpdates int + keysRequested int sync.Mutex cache map[string][]byte } @@ -33,6 +35,7 @@ func (m *mockCache) Fetch(_ context.Context, keys []string) (found []string, buf m.Lock() defer m.Unlock() for _, key := range keys { + m.keysRequested++ buf, ok := m.cache[key] if ok { found = append(found, key) @@ -59,6 +62,10 @@ func (m *mockCache) GetInternal() map[string][]byte { return m.cache } +func (m *mockCache) KeysRequested() int { + return m.keysRequested +} + // NewMockCache makes a new MockCache. func NewMockCache() MockCache { return &mockCache{ diff --git a/pkg/storage/chunk/fetcher/fetcher.go b/pkg/storage/chunk/fetcher/fetcher.go index e08cd7f0609d8..dc87d6be42f41 100644 --- a/pkg/storage/chunk/fetcher/fetcher.go +++ b/pkg/storage/chunk/fetcher/fetcher.go @@ -175,9 +175,8 @@ func (c *Fetcher) Client() client.Client { return c.storage } -// FetchChunks fetches a set of chunks from cache and store. Note that the keys passed in must be -// lexicographically sorted, while the returned chunks are not in the same order as the passed in chunks. -func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk, keys []string) ([]chunk.Chunk, error) { +// FetchChunks fetches a set of chunks from cache and store. Note, returned chunks are not in the same order they are passed in +func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk) ([]chunk.Chunk, error) { if ctx.Err() != nil { return nil, ctx.Err() } @@ -186,6 +185,24 @@ func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk, keys [] log := spanlogger.FromContext(ctx) defer log.Span.Finish() + // Extend the extendedHandoff to be 10% larger to allow for some overlap becasue this is a sliding window + // and the l1 cache may be oversized enough to allow for some extra chunks + extendedHandoff := c.l2CacheHandoff + (c.l2CacheHandoff / 10) + + keys := make([]string, 0, len(chunks)) + l2OnlyChunks := make([]chunk.Chunk, 0, len(chunks)) + + for _, m := range chunks { + // Similar to below, this is an optimization to not bother looking in the l1 cache if there isn't a reasonable + // expectation to find it there. + if c.l2CacheHandoff > 0 && m.From.Time().Before(time.Now().UTC().Add(-extendedHandoff)) { + l2OnlyChunks = append(l2OnlyChunks, m) + continue + } + chunkKey := c.schema.ExternalKey(m.ChunkRef) + keys = append(keys, chunkKey) + } + // Fetch from L1 chunk cache cacheHits, cacheBufs, _, err := c.cache.Fetch(ctx, keys) if err != nil { @@ -196,21 +213,11 @@ func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk, keys [] chunkFetchedSize.WithLabelValues("cache").Observe(float64(len(buf))) } - fromCache, missing, err := c.processCacheResponse(ctx, chunks, cacheHits, cacheBufs) - if err != nil { - level.Warn(log).Log("msg", "error process response from cache", "err", err) - } - - var fromCacheL2 []chunk.Chunk - if c.l2CacheHandoff > 0 { // Fetch missing from L2 chunks cache - missingL1Keys := make([]string, 0, len(missing)) - for _, m := range missing { + missingL1Keys := make([]string, 0, len(l2OnlyChunks)) + for _, m := range l2OnlyChunks { // A small optimization to prevent looking up a chunk in l2 cache that can't possibly be there - // Note, we don't need to keep track of the chunks that we are skipping here because - // processCacheResponse below takes in the initial list of chunks and returns the missing ones - // which will include the ones we are skipping here. if m.From.Time().After(time.Now().UTC().Add(-c.l2CacheHandoff)) { continue } @@ -227,10 +234,15 @@ func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk, keys [] chunkFetchedSize.WithLabelValues("cache_l2").Observe(float64(len(buf))) } - fromCacheL2, missing, err = c.processCacheResponse(ctx, chunks, cacheHitsL2, cacheBufsL2) - if err != nil { - level.Warn(log).Log("msg", "error process response from cache", "err", err) - } + cacheHits = append(cacheHits, cacheHitsL2...) + cacheBufs = append(cacheBufs, cacheBufsL2...) + } + + // processCacheResponse will decode all the fetched chunks and also provide us with a list of + // missing chunks that we need to fetch from the storage layer + fromCache, missing, err := c.processCacheResponse(ctx, chunks, cacheHits, cacheBufs) + if err != nil { + level.Warn(log).Log("msg", "error process response from cache", "err", err) } // Fetch missing from storage @@ -266,8 +278,7 @@ func (c *Fetcher) FetchChunks(ctx context.Context, chunks []chunk.Chunk, keys [] return nil, promql.ErrStorage{Err: err} } - allChunks := append(fromCache, fromCacheL2...) - allChunks = append(allChunks, fromStorage...) + allChunks := append(fromCache, fromStorage...) return allChunks, nil } @@ -322,29 +333,23 @@ func (c *Fetcher) processCacheResponse(ctx context.Context, chunks []chunk.Chunk logger = util_log.WithContext(ctx, util_log.Logger) ) - i, j := 0, 0 - for i < len(chunks) && j < len(keys) { - chunkKey := c.schema.ExternalKey(chunks[i].ChunkRef) + cm := make(map[string][]byte, len(chunks)) + for i, k := range keys { + cm[k] = bufs[i] + } - if chunkKey < keys[j] { - missing = append(missing, chunks[i]) - i++ - } else if chunkKey > keys[j] { - level.Warn(logger).Log("msg", "got chunk from cache we didn't ask for") - j++ - } else { + for i, ck := range chunks { + if b, ok := cm[c.schema.ExternalKey(ck.ChunkRef)]; ok { requests = append(requests, decodeRequest{ chunk: chunks[i], - buf: bufs[j], + buf: b, responses: responses, }) - i++ - j++ + } else { + missing = append(missing, chunks[i]) } } - for ; i < len(chunks); i++ { - missing = append(missing, chunks[i]) - } + level.Debug(logger).Log("chunks", len(chunks), "decodeRequests", len(requests), "missing", len(missing)) go func() { @@ -353,10 +358,8 @@ func (c *Fetcher) processCacheResponse(ctx context.Context, chunks []chunk.Chunk } }() - var ( - err error - found []chunk.Chunk - ) + var err error + found := make([]chunk.Chunk, 0, len(requests)) for i := 0; i < len(requests); i++ { response := <-responses diff --git a/pkg/storage/chunk/fetcher/fetcher_test.go b/pkg/storage/chunk/fetcher/fetcher_test.go index ab2fe8e59637b..a5cefb39b412d 100644 --- a/pkg/storage/chunk/fetcher/fetcher_test.go +++ b/pkg/storage/chunk/fetcher/fetcher_test.go @@ -2,6 +2,7 @@ package fetcher import ( "context" + "strconv" "testing" "time" @@ -20,74 +21,132 @@ import ( func Test(t *testing.T) { now := time.Now() tests := []struct { - name string - handoff time.Duration - storeStart []chunk.Chunk - l1Start []chunk.Chunk - l2Start []chunk.Chunk - fetch []chunk.Chunk - l1End []chunk.Chunk - l2End []chunk.Chunk + name string + handoff time.Duration + storeStart []chunk.Chunk + l1Start []chunk.Chunk + l2Start []chunk.Chunk + fetch []chunk.Chunk + l1KeysRequested int + l1End []chunk.Chunk + l2KeysRequested int + l2End []chunk.Chunk }{ { - name: "all found in L1 cache", - handoff: 0, - storeStart: []chunk.Chunk{}, - l1Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l2Start: []chunk.Chunk{}, - fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l2End: []chunk.Chunk{}, + name: "all found in L1 cache", + handoff: 0, + storeStart: []chunk.Chunk{}, + l1Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2End: []chunk.Chunk{}, }, { - name: "all found in L2 cache", - handoff: 1, // Only needs to be greater than zero so that we check L2 cache - storeStart: []chunk.Chunk{}, - l1Start: []chunk.Chunk{}, - l2Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l1End: []chunk.Chunk{}, - l2End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + name: "all found in L2 cache", + handoff: 1, // Only needs to be greater than zero so that we check L2 cache + storeStart: []chunk.Chunk{}, + l1Start: []chunk.Chunk{}, + l2Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l1End: []chunk.Chunk{}, + l2KeysRequested: 3, + l2End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), }, { - name: "some in L1, some in L2", - handoff: 1, // Only needs to be greater than zero so that we check L2 cache - storeStart: []chunk.Chunk{}, - l1Start: []chunk.Chunk{}, - l2Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l1End: []chunk.Chunk{}, - l2End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + name: "some in L1, some in L2", + handoff: 5 * time.Hour, + storeStart: []chunk.Chunk{}, + l1Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2Start: makeChunks(now, c{7 * time.Hour, 8 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{7 * time.Hour, 8 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2KeysRequested: 3, + l2End: makeChunks(now, c{7 * time.Hour, 8 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), }, { - name: "writeback l1", - handoff: 24 * time.Hour, - storeStart: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l1Start: []chunk.Chunk{}, - l2Start: []chunk.Chunk{}, - fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l2End: []chunk.Chunk{}, + name: "some in L1, some in L2, some in store", + handoff: 5 * time.Hour, + storeStart: makeChunks(now, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), + l1Start: makeChunks(now, c{time.Hour, 2 * time.Hour}), + l2Start: makeChunks(now, c{7 * time.Hour, 8 * time.Hour}), + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{7 * time.Hour, 8 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2KeysRequested: 3, + l2End: makeChunks(now, c{7 * time.Hour, 8 * time.Hour}, c{8 * time.Hour, 9 * time.Hour}, c{9 * time.Hour, 10 * time.Hour}), }, { - name: "writeback l2", - handoff: 24 * time.Hour, - storeStart: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), - l1Start: []chunk.Chunk{}, - l2Start: []chunk.Chunk{}, - fetch: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), - l1End: []chunk.Chunk{}, - l2End: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + name: "writeback l1", + handoff: 24 * time.Hour, + storeStart: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l1Start: []chunk.Chunk{}, + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2End: []chunk.Chunk{}, }, { - name: "writeback l1 and l2", - handoff: 24 * time.Hour, - storeStart: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), - l1Start: []chunk.Chunk{}, - l2Start: []chunk.Chunk{}, - fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), - l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), - l2End: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + name: "writeback l2", + handoff: 24 * time.Hour, + storeStart: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1Start: []chunk.Chunk{}, + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1End: []chunk.Chunk{}, + l2KeysRequested: 3, + l2End: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + }, + { + name: "writeback l1 and l2", + handoff: 24 * time.Hour, + storeStart: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1Start: []chunk.Chunk{}, + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2KeysRequested: 3, + l2End: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + }, + { + name: "verify l1 skip optimization", + handoff: 24 * time.Hour, + storeStart: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1Start: []chunk.Chunk{}, + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1KeysRequested: 0, + l1End: []chunk.Chunk{}, + l2KeysRequested: 3, + l2End: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + }, + { + name: "verify l1 skip optimization plus extended", + handoff: 20 * time.Hour, // 20 hours, 10% extension should be 22 hours + storeStart: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1Start: makeChunks(now, c{20 * time.Hour, 21 * time.Hour}, c{21 * time.Hour, 22 * time.Hour}, c{22 * time.Hour, 23 * time.Hour}), + l2Start: makeChunks(now, c{21 * time.Hour, 22 * time.Hour}, c{22 * time.Hour, 23 * time.Hour}), + fetch: makeChunks(now, c{20 * time.Hour, 21 * time.Hour}, c{21 * time.Hour, 22 * time.Hour}, c{22 * time.Hour, 23 * time.Hour}), + l1KeysRequested: 2, + l1End: makeChunks(now, c{20 * time.Hour, 21 * time.Hour}, c{21 * time.Hour, 22 * time.Hour}, c{22 * time.Hour, 23 * time.Hour}), + l2KeysRequested: 1, // We won't look for the extended handoff key in L2, so only one lookup should go to L2 + l2End: makeChunks(now, c{21 * time.Hour, 22 * time.Hour}, c{22 * time.Hour, 23 * time.Hour}), + }, + { + name: "verify l2 skip optimization", + handoff: 24 * time.Hour, + storeStart: makeChunks(now, c{31 * time.Hour, 32 * time.Hour}, c{32 * time.Hour, 33 * time.Hour}, c{33 * time.Hour, 34 * time.Hour}), + l1Start: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2Start: []chunk.Chunk{}, + fetch: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l1KeysRequested: 3, + l1End: makeChunks(now, c{time.Hour, 2 * time.Hour}, c{2 * time.Hour, 3 * time.Hour}, c{3 * time.Hour, 4 * time.Hour}), + l2KeysRequested: 0, + l2End: []chunk.Chunk{}, }, } for _, test := range tests { @@ -137,30 +196,120 @@ func Test(t *testing.T) { assert.NoError(t, s.PutChunks(context.Background(), test.storeStart)) // Build fetcher - f, err := New(c1, c2, true, sc, s, 1, 1, test.handoff) + f, err := New(c1, c2, false, sc, s, 1, 1, test.handoff) assert.NoError(t, err) - // Generate keys from chunks - keys = make([]string, 0, len(test.fetch)) - for _, f := range test.fetch { - k := sc.ExternalKey(f.ChunkRef) - keys = append(keys, k) - } - // Run the test - chks, err := f.FetchChunks(context.Background(), test.fetch, keys) + chks, err := f.FetchChunks(context.Background(), test.fetch) assert.NoError(t, err) assertChunks(t, test.fetch, chks) l1actual, err := makeChunksFromMap(c1.GetInternal()) assert.NoError(t, err) + assert.Equal(t, test.l1KeysRequested, c1.KeysRequested()) assertChunks(t, test.l1End, l1actual) l2actual, err := makeChunksFromMap(c2.GetInternal()) assert.NoError(t, err) + assert.Equal(t, test.l2KeysRequested, c2.KeysRequested()) assertChunks(t, test.l2End, l2actual) }) } } +func BenchmarkFetch(b *testing.B) { + now := time.Now() + + numchunks := 100 + l1Start := make([]chunk.Chunk, 0, numchunks/3) + for i := 0; i < numchunks/3; i++ { + l1Start = append(l1Start, makeChunks(now, c{time.Duration(i) * time.Hour, time.Duration(i+1) * time.Hour})...) + } + l2Start := make([]chunk.Chunk, 0, numchunks/3) + for i := numchunks/3 + 1000; i < (numchunks/3)+numchunks/3+1000; i++ { + l2Start = append(l2Start, makeChunks(now, c{time.Duration(i) * time.Hour, time.Duration(i+1) * time.Hour})...) + } + storeStart := make([]chunk.Chunk, 0, numchunks/3) + for i := numchunks/3 + 10000; i < (numchunks/3)+numchunks/3+10000; i++ { + storeStart = append(storeStart, makeChunks(now, c{time.Duration(i) * time.Hour, time.Duration(i+1) * time.Hour})...) + } + fetch := make([]chunk.Chunk, 0, numchunks) + fetch = append(fetch, l1Start...) + fetch = append(fetch, l2Start...) + fetch = append(fetch, storeStart...) + + test := struct { + name string + handoff time.Duration + storeStart []chunk.Chunk + l1Start []chunk.Chunk + l2Start []chunk.Chunk + fetch []chunk.Chunk + l1KeysRequested int + l1End []chunk.Chunk + l2KeysRequested int + l2End []chunk.Chunk + }{ + name: "some in L1, some in L2", + handoff: time.Duration(numchunks/3+100) * time.Hour, + storeStart: storeStart, + l1Start: l1Start, + l2Start: l2Start, + fetch: fetch, + } + + c1 := cache.NewMockCache() + c2 := cache.NewMockCache() + s := testutils.NewMockStorage() + // Note this is copied from the schema config used in the MockStorage + sc := config.SchemaConfig{ + Configs: []config.PeriodConfig{ + { + From: config.DayTime{Time: 0}, + Schema: "v11", + RowShards: 16, + }, + }, + } + + // Prepare l1 cache + keys := make([]string, 0, len(test.l1Start)) + chunks := make([][]byte, 0, len(test.l1Start)) + for _, c := range test.l1Start { + // Encode first to set the checksum + b, _ := c.Encoded() + + k := sc.ExternalKey(c.ChunkRef) + keys = append(keys, k) + chunks = append(chunks, b) + } + _ = c1.Store(context.Background(), keys, chunks) + + // Prepare l2 cache + keys = make([]string, 0, len(test.l2Start)) + chunks = make([][]byte, 0, len(test.l2Start)) + for _, c := range test.l2Start { + b, _ := c.Encoded() + + k := sc.ExternalKey(c.ChunkRef) + keys = append(keys, k) + chunks = append(chunks, b) + } + _ = c2.Store(context.Background(), keys, chunks) + + // Prepare store + _ = s.PutChunks(context.Background(), test.storeStart) + + // Build fetcher + f, _ := New(c1, c2, false, sc, s, 1, 1, test.handoff) + + for i := 0; i < b.N; i++ { + _, err := f.FetchChunks(context.Background(), test.fetch) + if err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() +} + type c struct { from, through time.Duration } @@ -175,9 +324,18 @@ func makeChunks(now time.Time, tpls ...c) []chunk.Chunk { Through: model.TimeFromUnix(now.Add(-chk.through).UTC().Unix()), }, } - c.Metric = labels.Labels{} - // This isn't even the write format for Loki but we dont' care for the sake of these tests + from := int(chk.from) / int(time.Hour) + // This is only here because it's helpful for debugging. + c.Metric = labels.Labels{labels.Label{Name: "start", Value: strconv.Itoa(from)}} + // This isn't even the write format for Loki but we dont' care for the sake of these tests. c.Data = chunk.New() + // To make sure the fetcher doesn't swap keys and buffers each chunk is built with different, but deterministic data + for i := 0; i < from; i++ { + _, _ = c.Data.Add(model.SamplePair{ + Timestamp: model.TimeFromUnix(int64(i)), + Value: model.SampleValue(from), + }) + } // Encode to set the checksum _ = c.Encode() chks = append(chks, c) @@ -206,11 +364,11 @@ func sortChunks(chks []chunk.Chunk) { } func assertChunks(t *testing.T, expected, actual []chunk.Chunk) { - sortChunks(expected) - sortChunks(actual) assert.Eventually(t, func() bool { return len(expected) == len(actual) }, 2*time.Second, time.Millisecond*100, "expected %d chunks, got %d", len(expected), len(actual)) + sortChunks(expected) + sortChunks(actual) for i := range expected { assert.Equal(t, expected[i].ChunkRef, actual[i].ChunkRef) } diff --git a/pkg/storage/stores/series/series_index_store.go b/pkg/storage/stores/series/series_index_store.go index cb6de6818f9ad..da92fdbf60c9b 100644 --- a/pkg/storage/stores/series/series_index_store.go +++ b/pkg/storage/stores/series/series_index_store.go @@ -197,16 +197,17 @@ func (c *indexReaderWriter) SetChunkFilterer(f chunk.RequestChunkFilterer) { } type chunkGroup struct { + schema config.SchemaConfig chunks []chunk.Chunk - keys []string } func (c chunkGroup) Len() int { return len(c.chunks) } func (c chunkGroup) Swap(i, j int) { c.chunks[i], c.chunks[j] = c.chunks[j], c.chunks[i] - c.keys[i], c.keys[j] = c.keys[j], c.keys[i] } -func (c chunkGroup) Less(i, j int) bool { return c.keys[i] < c.keys[j] } +func (c chunkGroup) Less(i, j int) bool { + return c.schema.ExternalKey(c.chunks[i].ChunkRef) < c.schema.ExternalKey(c.chunks[j].ChunkRef) +} func (c *indexReaderWriter) GetSeries(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) ([]labels.Labels, error) { chks, err := c.GetChunkRefs(ctx, userID, from, through, matchers...) @@ -220,7 +221,7 @@ func (c *indexReaderWriter) GetSeries(ctx context.Context, userID string, from, func (c *indexReaderWriter) chunksToSeries(ctx context.Context, in []logproto.ChunkRef, matchers []*labels.Matcher) ([]labels.Labels, error) { // download one per series and merge // group chunks by series - chunksBySeries, keys := filterChunkRefsByUniqueFingerprint(c.schemaCfg, in) + chunksBySeries := filterChunkRefsByUniqueFingerprint(in) // bound concurrency groups := make([]chunkGroup, 0, len(chunksBySeries)/c.chunkBatchSize+1) @@ -236,9 +237,8 @@ func (c *indexReaderWriter) chunksToSeries(ctx context.Context, in []logproto.Ch } for split > 0 { - groups = append(groups, chunkGroup{chunksBySeries[:split], keys[:split]}) + groups = append(groups, chunkGroup{c.schemaCfg, chunksBySeries[:split]}) chunksBySeries = chunksBySeries[split:] - keys = keys[split:] if len(chunksBySeries) < split { split = len(chunksBySeries) } @@ -251,7 +251,7 @@ func (c *indexReaderWriter) chunksToSeries(ctx context.Context, in []logproto.Ch group := g jobs = append(jobs, f(func() ([]labels.Labels, error) { sort.Sort(group) - chunks, err := c.fetcher.FetchChunks(ctx, group.chunks, group.keys) + chunks, err := c.fetcher.FetchChunks(ctx, group.chunks) if err != nil { return nil, err } @@ -683,13 +683,13 @@ func (c *indexReaderWriter) lookupLabelNamesByChunks(ctx context.Context, from, // Filter out chunks that are not in the selected time range and keep a single chunk per fingerprint filtered := filterChunksByTime(from, through, chunks) - filtered, keys := filterChunksByUniqueFingerprint(c.schemaCfg, filtered) + filtered = filterChunksByUniqueFingerprint(filtered) level.Debug(log).Log("Chunks post filtering", len(chunks)) chunksPerQuery.Observe(float64(len(filtered))) // Now fetch the actual chunk data from Memcache / S3 - allChunks, err := c.fetcher.FetchChunks(ctx, filtered, keys) + allChunks, err := c.fetcher.FetchChunks(ctx, filtered) if err != nil { level.Error(log).Log("msg", "FetchChunks", "err", err) return nil, err diff --git a/pkg/storage/stores/series/series_store_test.go b/pkg/storage/stores/series/series_store_test.go index 7769711da702d..f9bd7eab6b81c 100644 --- a/pkg/storage/stores/series/series_store_test.go +++ b/pkg/storage/stores/series/series_store_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "reflect" - "sort" "testing" "time" @@ -373,7 +372,7 @@ func TestChunkStore_getMetricNameChunks(t *testing.T) { for _, storeCase := range stores { storeCfg := storeCase.configFn() - store, schemaCfg := newTestChunkStoreConfig(t, schema, storeCfg) + store, _ := newTestChunkStoreConfig(t, schema, storeCfg) defer store.Stop() if err := store.Put(ctx, []chunk.Chunk{chunk1, chunk2}); err != nil { @@ -393,15 +392,7 @@ func TestChunkStore_getMetricNameChunks(t *testing.T) { fetchedChunk := []chunk.Chunk{} for _, f := range fetchers { for _, cs := range chunks { - keys := make([]string, 0, len(cs)) - sort.Slice(chunks, func(i, j int) bool { - return schemaCfg.ExternalKey(cs[i].ChunkRef) < schemaCfg.ExternalKey(cs[j].ChunkRef) - }) - - for _, c := range cs { - keys = append(keys, schemaCfg.ExternalKey(c.ChunkRef)) - } - cks, err := f.FetchChunks(ctx, cs, keys) + cks, err := f.FetchChunks(ctx, cs) if err != nil { t.Fatal(err) } diff --git a/pkg/storage/stores/series/series_store_utils.go b/pkg/storage/stores/series/series_store_utils.go index 0e9b44e1cc652..1c8430c9d8fbe 100644 --- a/pkg/storage/stores/series/series_store_utils.go +++ b/pkg/storage/stores/series/series_store_utils.go @@ -8,7 +8,6 @@ import ( "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/storage/chunk" - "github.com/grafana/loki/pkg/storage/config" "github.com/grafana/loki/pkg/util" ) @@ -48,9 +47,8 @@ func labelNamesFromChunks(chunks []chunk.Chunk) []string { return result.Strings() } -func filterChunksByUniqueFingerprint(s config.SchemaConfig, chunks []chunk.Chunk) ([]chunk.Chunk, []string) { +func filterChunksByUniqueFingerprint(chunks []chunk.Chunk) []chunk.Chunk { filtered := make([]chunk.Chunk, 0, len(chunks)) - keys := make([]string, 0, len(chunks)) uniqueFp := map[model.Fingerprint]struct{}{} for _, chunk := range chunks { @@ -58,15 +56,13 @@ func filterChunksByUniqueFingerprint(s config.SchemaConfig, chunks []chunk.Chunk continue } filtered = append(filtered, chunk) - keys = append(keys, s.ExternalKey(chunk.ChunkRef)) uniqueFp[chunk.FingerprintModel()] = struct{}{} } - return filtered, keys + return filtered } -func filterChunkRefsByUniqueFingerprint(s config.SchemaConfig, chunks []logproto.ChunkRef) ([]chunk.Chunk, []string) { +func filterChunkRefsByUniqueFingerprint(chunks []logproto.ChunkRef) []chunk.Chunk { filtered := make([]chunk.Chunk, 0, len(chunks)) - keys := make([]string, 0, len(chunks)) uniqueFp := map[model.Fingerprint]struct{}{} for _, c := range chunks { @@ -76,10 +72,9 @@ func filterChunkRefsByUniqueFingerprint(s config.SchemaConfig, chunks []logproto filtered = append(filtered, chunk.Chunk{ ChunkRef: c, }) - keys = append(keys, s.ExternalKey(c)) uniqueFp[c.FingerprintModel()] = struct{}{} } - return filtered, keys + return filtered } func uniqueStrings(cs []string) []string { diff --git a/pkg/storage/stores/shipper/index/compactor/util_test.go b/pkg/storage/stores/shipper/index/compactor/util_test.go index 0a6b52038b18b..b6e2299ff76ed 100644 --- a/pkg/storage/stores/shipper/index/compactor/util_test.go +++ b/pkg/storage/stores/shipper/index/compactor/util_test.go @@ -5,7 +5,6 @@ import ( "fmt" "os" "path/filepath" - "sort" "testing" "time" @@ -174,15 +173,7 @@ func (t *testStore) GetChunks(userID string, from, through model.Time, metric la fetchedChunk := []chunk.Chunk{} for _, f := range fetchers { for _, cs := range chunks { - keys := make([]string, 0, len(cs)) - sort.Slice(chunks, func(i, j int) bool { - return schemaCfg.ExternalKey(cs[i].ChunkRef) < schemaCfg.ExternalKey(cs[j].ChunkRef) - }) - - for _, c := range cs { - keys = append(keys, schemaCfg.ExternalKey(c.ChunkRef)) - } - cks, err := f.FetchChunks(ctx, cs, keys) + cks, err := f.FetchChunks(ctx, cs) if err != nil { t.t.Fatal(err) }
loki
simplify the FetchChunks method and optimize the experimental l2 cache a little more (#10160)
86a1feb2c1542dd98efe639d16a024b8b8f307ce
2023-01-18 16:57:12
Mohamed-Amine Bouqsimi
operator: Add watch on the Alertmanager in OCP's user-workload-monitoring namespace (#8038)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index b75b8ae62f618..b32c6972dea87 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [8038](https://github.com/grafana/loki/pull/8038) **aminesnow**: Add watch on the Alertmanager in OCP's user-workload-monitoring namespace - [8173](https://github.com/grafana/loki/pull/8173) **periklis**: Remove custom webhook cert mounts for OLM-based deployment (OpenShift) - [8001](https://github.com/grafana/loki/pull/8001) **aminesnow**: Add API validation to Alertmanager header auth config - [8087](https://github.com/grafana/loki/pull/8087) **xperimental**: Fix status not updating when state of pods changes diff --git a/operator/controllers/loki/lokistack_controller.go b/operator/controllers/loki/lokistack_controller.go index c9dd7b58341ec..b6776842bbb49 100644 --- a/operator/controllers/loki/lokistack_controller.go +++ b/operator/controllers/loki/lokistack_controller.go @@ -9,6 +9,7 @@ import ( "github.com/grafana/loki/operator/controllers/loki/internal/management/state" "github.com/grafana/loki/operator/internal/external/k8s" "github.com/grafana/loki/operator/internal/handlers" + "github.com/grafana/loki/operator/internal/manifests/openshift" "github.com/grafana/loki/operator/internal/status" openshiftconfigv1 "github.com/openshift/api/config/v1" routev1 "github.com/openshift/api/route/v1" @@ -92,6 +93,15 @@ var ( return false }, }) + createUpdateOrDeletePred = builder.WithPredicates(predicate.Funcs{ + UpdateFunc: func(e event.UpdateEvent) bool { + return (e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()) || + cmp.Diff(e.ObjectOld.GetAnnotations(), e.ObjectNew.GetAnnotations()) != "" + }, + CreateFunc: func(e event.CreateEvent) bool { return true }, + DeleteFunc: func(e event.DeleteEvent) bool { return true }, + GenericFunc: func(e event.GenericEvent) bool { return false }, + }) ) // LokiStackReconciler reconciles a LokiStack object @@ -194,7 +204,8 @@ func (r *LokiStackReconciler) buildController(bld k8s.Builder) error { Owns(&rbacv1.ClusterRole{}, updateOrDeleteOnlyPred). Owns(&rbacv1.ClusterRoleBinding{}, updateOrDeleteOnlyPred). Owns(&rbacv1.Role{}, updateOrDeleteOnlyPred). - Owns(&rbacv1.RoleBinding{}, updateOrDeleteOnlyPred) + Owns(&rbacv1.RoleBinding{}, updateOrDeleteOnlyPred). + Watches(&source.Kind{Type: &corev1.Service{}}, r.enqueueForUserWorkloadAMService(), createUpdateOrDeletePred) if r.FeatureGates.LokiStackAlerts { bld = bld.Owns(&monitoringv1.PrometheusRule{}, updateOrDeleteOnlyPred) @@ -253,3 +264,34 @@ func statusDifferent(e event.UpdateEvent) bool { return false } } + +func (r *LokiStackReconciler) enqueueForUserWorkloadAMService() handler.EventHandler { + ctx := context.TODO() + return handler.EnqueueRequestsFromMapFunc(func(obj client.Object) []reconcile.Request { + lokiStacks := &lokiv1.LokiStackList{} + if err := r.Client.List(ctx, lokiStacks); err != nil { + r.Log.Error(err, "Error getting LokiStack resources in event handler") + return nil + } + var requests []reconcile.Request + + if obj.GetName() == openshift.MonitoringSVCOperated && obj.GetNamespace() == openshift.MonitoringUserwWrkloadNS { + + for _, stack := range lokiStacks.Items { + if stack.Spec.Tenants != nil && (stack.Spec.Tenants.Mode == lokiv1.OpenshiftLogging || + stack.Spec.Tenants.Mode == lokiv1.OpenshiftNetwork) { + requests = append(requests, reconcile.Request{ + NamespacedName: types.NamespacedName{ + Namespace: stack.Namespace, + Name: stack.Name, + }, + }) + } + } + + r.Log.Info("Enqueued requests for all LokiStacks because of UserWorkload Alertmanager Service resource change", "count", len(requests), "kind", obj.GetObjectKind()) + } + + return requests + }) +} diff --git a/operator/controllers/loki/lokistack_controller_test.go b/operator/controllers/loki/lokistack_controller_test.go index 1bd497c24d5dd..dccba39be4d58 100644 --- a/operator/controllers/loki/lokistack_controller_test.go +++ b/operator/controllers/loki/lokistack_controller_test.go @@ -57,6 +57,7 @@ func TestLokiStackController_RegistersCustomResourceForCreateOrUpdate(t *testing b.ForReturns(b) b.OwnsReturns(b) + b.WatchesReturns(b) err := c.buildController(b) require.NoError(t, err) @@ -202,8 +203,8 @@ func TestLokiStackController_RegisterWatchedResources(t *testing.T) { table := []test{ { src: &source.Kind{Type: &openshiftconfigv1.APIServer{}}, - index: 0, - watchesCallsCount: 1, + index: 1, + watchesCallsCount: 2, featureGates: configv1.FeatureGates{ OpenShift: configv1.OpenShiftFeatureGates{ ClusterTLSPolicy: true, @@ -213,8 +214,8 @@ func TestLokiStackController_RegisterWatchedResources(t *testing.T) { }, { src: &source.Kind{Type: &openshiftconfigv1.Proxy{}}, - index: 0, - watchesCallsCount: 1, + index: 1, + watchesCallsCount: 2, featureGates: configv1.FeatureGates{ OpenShift: configv1.OpenShiftFeatureGates{ ClusterProxy: true, @@ -222,6 +223,13 @@ func TestLokiStackController_RegisterWatchedResources(t *testing.T) { }, pred: updateOrDeleteOnlyPred, }, + { + src: &source.Kind{Type: &corev1.Service{}}, + index: 0, + watchesCallsCount: 1, + featureGates: configv1.FeatureGates{}, + pred: createUpdateOrDeletePred, + }, } for _, tst := range table { b := &k8sfakes.FakeBuilder{}
operator
Add watch on the Alertmanager in OCP's user-workload-monitoring namespace (#8038)
63e84b476a9a7b97a121847659172fadbb8a1eee
2024-09-12 20:58:14
Sven Grossmann
fix(aggregated-metrics): correctly create logfmt string (#14124)
false
diff --git a/pkg/logql/metrics.go b/pkg/logql/metrics.go index d06a8fbac7d2b..5b6422b815357 100644 --- a/pkg/logql/metrics.go +++ b/pkg/logql/metrics.go @@ -8,7 +8,6 @@ import ( "time" "github.com/c2h5oh/datasize" - "github.com/dustin/go-humanize" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" @@ -156,9 +155,9 @@ func RecordRangeAndInstantQueryMetrics( "status", status, "limit", p.Limit(), "returned_lines", returnedLines, - "throughput", humanizeBytes(uint64(stats.Summary.BytesProcessedPerSecond)), - "total_bytes", humanizeBytes(uint64(stats.Summary.TotalBytesProcessed)), - "total_bytes_structured_metadata", humanizeBytes(uint64(stats.Summary.TotalStructuredMetadataBytesProcessed)), + "throughput", util.HumanizeBytes(uint64(stats.Summary.BytesProcessedPerSecond)), + "total_bytes", util.HumanizeBytes(uint64(stats.Summary.TotalBytesProcessed)), + "total_bytes_structured_metadata", util.HumanizeBytes(uint64(stats.Summary.TotalStructuredMetadataBytesProcessed)), "lines_per_second", stats.Summary.LinesProcessedPerSecond, "total_lines", stats.Summary.TotalLinesProcessed, "post_filter_lines", stats.Summary.TotalPostFilterLines, @@ -197,11 +196,11 @@ func RecordRangeAndInstantQueryMetrics( // Total ingester reached for this query. "ingester_requests", stats.Ingester.GetTotalReached(), // Total bytes processed but was already in memory (found in the headchunk). Includes structured metadata bytes. - "ingester_chunk_head_bytes", humanizeBytes(uint64(stats.Ingester.Store.Chunk.GetHeadChunkBytes())), + "ingester_chunk_head_bytes", util.HumanizeBytes(uint64(stats.Ingester.Store.Chunk.GetHeadChunkBytes())), // Total bytes of compressed chunks (blocks) processed. - "ingester_chunk_compressed_bytes", humanizeBytes(uint64(stats.Ingester.Store.Chunk.GetCompressedBytes())), + "ingester_chunk_compressed_bytes", util.HumanizeBytes(uint64(stats.Ingester.Store.Chunk.GetCompressedBytes())), // Total bytes decompressed and processed from chunks. Includes structured metadata bytes. - "ingester_chunk_decompressed_bytes", humanizeBytes(uint64(stats.Ingester.Store.Chunk.GetDecompressedBytes())), + "ingester_chunk_decompressed_bytes", util.HumanizeBytes(uint64(stats.Ingester.Store.Chunk.GetDecompressedBytes())), // Total lines post filtering. "ingester_post_filter_lines", stats.Ingester.Store.Chunk.GetPostFilterLines(), // Time spent being blocked on congestion control. @@ -243,10 +242,6 @@ func RecordRangeAndInstantQueryMetrics( recordUsageStats(queryType, stats) } -func humanizeBytes(val uint64) string { - return strings.Replace(humanize.Bytes(val), " ", "", 1) -} - func RecordLabelQueryMetrics( ctx context.Context, log log.Logger, diff --git a/pkg/pattern/aggregation/push.go b/pkg/pattern/aggregation/push.go index 9aac2e3a5050d..649d71f92029c 100644 --- a/pkg/pattern/aggregation/push.go +++ b/pkg/pattern/aggregation/push.go @@ -11,7 +11,6 @@ import ( "sync" "time" - "github.com/dustin/go-humanize" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/golang/snappy" @@ -22,6 +21,7 @@ import ( "github.com/grafana/loki/v3/pkg/loghttp/push" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/syntax" + "github.com/grafana/loki/v3/pkg/util" "github.com/grafana/loki/v3/pkg/util/build" "github.com/grafana/dskit/backoff" @@ -312,9 +312,9 @@ func AggregatedMetricEntry( service string, lbls labels.Labels, ) string { - byteString := humanize.Bytes(totalBytes) + byteString := util.HumanizeBytes(totalBytes) base := fmt.Sprintf( - "ts=%d bytes=%s count=%d %s=%s", + "ts=%d bytes=%s count=%d %s=\"%s\"", ts.UnixNano(), byteString, totalCount, @@ -322,7 +322,7 @@ func AggregatedMetricEntry( ) for _, l := range lbls { - base += fmt.Sprintf(" %s=%s", l.Name, l.Value) + base += fmt.Sprintf(" %s=\"%s\"", l.Name, l.Value) } return base diff --git a/pkg/pattern/aggregation/push_test.go b/pkg/pattern/aggregation/push_test.go index 15f0336b5f7e8..149b54a977151 100644 --- a/pkg/pattern/aggregation/push_test.go +++ b/pkg/pattern/aggregation/push_test.go @@ -229,6 +229,9 @@ func Test_Push(t *testing.T) { stream2.Entries[2].Line, ) + // sanity check that bytes are logged in humanized form without whitespaces + assert.Contains(t, stream1.Entries[0].Line, "bytes=1B") + case <-time.After(5 * time.Second): t.Fatal("timeout") } diff --git a/pkg/util/metrics_helper.go b/pkg/util/metrics_helper.go index e4572b4e4a15c..7bf7d3029a260 100644 --- a/pkg/util/metrics_helper.go +++ b/pkg/util/metrics_helper.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" "math" + "strings" "sync" + humanize "github.com/dustin/go-humanize" "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" @@ -841,3 +843,8 @@ func RegisterCounterVec(registerer prometheus.Registerer, namespace, name, help } return vec } + +// HumanizeBytes returns a human readable string representation of the given byte value and removes all whitespaces. +func HumanizeBytes(val uint64) string { + return strings.Replace(humanize.Bytes(val), " ", "", 1) +} diff --git a/pkg/util/metrics_helper_test.go b/pkg/util/metrics_helper_test.go index 7ca74ab7b0225..09e80a2afa580 100644 --- a/pkg/util/metrics_helper_test.go +++ b/pkg/util/metrics_helper_test.go @@ -1158,3 +1158,18 @@ func verifyLabels(t *testing.T, m prometheus.Collector, filter map[string]string require.Equal(t, expectedLabels, result) } + +func TestHumanizeBytes(t *testing.T) { + tests := map[uint64]string{ + 1024: "1.0kB", + 1024 * 1000: "1.0MB", + 1024 * 1000 * 1000: "1.0GB", + 10: "10B", + } + + for bytes, humanizedBytes := range tests { + t.Run(fmt.Sprintf("%d", bytes), func(t *testing.T) { + require.Equal(t, humanizedBytes, HumanizeBytes(bytes)) + }) + } +}
fix
correctly create logfmt string (#14124)
896e138425ba3ea8915c6b6497fb927735bc37a9
2025-01-13 18:41:23
Robert Fratto
chore(dataobj): data object encoding and decoding (#15676)
false
diff --git a/pkg/dataobj/internal/encoding/dataset_streams.go b/pkg/dataobj/internal/encoding/dataset_streams.go new file mode 100644 index 0000000000000..5843cc4c2cd47 --- /dev/null +++ b/pkg/dataobj/internal/encoding/dataset_streams.go @@ -0,0 +1,152 @@ +package encoding + +import ( + "context" + "fmt" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/dataset" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/result" +) + +// StreamsDataset implements returns a [dataset.Dataset] from a +// [StreamsDecoder] for the given section. +func StreamsDataset(dec StreamsDecoder, sec *filemd.SectionInfo) dataset.Dataset { + return &streamsDataset{dec: dec, sec: sec} +} + +type streamsDataset struct { + dec StreamsDecoder + sec *filemd.SectionInfo +} + +func (ds *streamsDataset) ListColumns(ctx context.Context) result.Seq[dataset.Column] { + return result.Iter(func(yield func(dataset.Column) bool) error { + columns, err := ds.dec.Columns(ctx, ds.sec) + if err != nil { + return err + } + + for _, column := range columns { + if !yield(&streamsDatasetColumn{dec: ds.dec, desc: column}) { + return nil + } + } + + return err + }) + +} + +func (ds *streamsDataset) ListPages(ctx context.Context, columns []dataset.Column) result.Seq[dataset.Pages] { + // TODO(rfratto): Switch to batch retrieval instead of iterating over each column. + return result.Iter(func(yield func(dataset.Pages) bool) error { + for _, column := range columns { + pages, err := result.Collect(column.ListPages(ctx)) + if err != nil { + return err + } else if !yield(pages) { + return nil + } + } + + return nil + }) +} + +func (ds *streamsDataset) ReadPages(ctx context.Context, pages []dataset.Page) result.Seq[dataset.PageData] { + // TODO(rfratto): Switch to batch retrieval instead of iterating over each page. + return result.Iter(func(yield func(dataset.PageData) bool) error { + for _, page := range pages { + data, err := page.ReadPage(ctx) + if err != nil { + return err + } else if !yield(data) { + return nil + } + } + + return nil + }) +} + +type streamsDatasetColumn struct { + dec StreamsDecoder + desc *streamsmd.ColumnDesc + + info *dataset.ColumnInfo +} + +func (col *streamsDatasetColumn) ColumnInfo() *dataset.ColumnInfo { + if col.info != nil { + return col.info + } + + col.info = &dataset.ColumnInfo{ + Name: col.desc.Info.Name, + Type: col.desc.Info.ValueType, + Compression: col.desc.Info.Compression, + + RowsCount: int(col.desc.Info.RowsCount), + CompressedSize: int(col.desc.Info.CompressedSize), + UncompressedSize: int(col.desc.Info.UncompressedSize), + + Statistics: col.desc.Info.Statistics, + } + return col.info +} + +func (col *streamsDatasetColumn) ListPages(ctx context.Context) result.Seq[dataset.Page] { + return result.Iter(func(yield func(dataset.Page) bool) error { + pageSets, err := result.Collect(col.dec.Pages(ctx, []*streamsmd.ColumnDesc{col.desc})) + if err != nil { + return err + } else if len(pageSets) != 1 { + return fmt.Errorf("unexpected number of page sets: got=%d want=1", len(pageSets)) + } + + for _, page := range pageSets[0] { + if !yield(&streamsDatasetPage{dec: col.dec, desc: page}) { + return nil + } + } + + return nil + }) +} + +type streamsDatasetPage struct { + dec StreamsDecoder + desc *streamsmd.PageDesc + + info *dataset.PageInfo +} + +func (p *streamsDatasetPage) PageInfo() *dataset.PageInfo { + if p.info != nil { + return p.info + } + + p.info = &dataset.PageInfo{ + UncompressedSize: int(p.desc.Info.UncompressedSize), + CompressedSize: int(p.desc.Info.CompressedSize), + CRC32: p.desc.Info.Crc32, + RowCount: int(p.desc.Info.RowsCount), + + Encoding: p.desc.Info.Encoding, + Stats: p.desc.Info.Statistics, + } + return p.info +} + +func (p *streamsDatasetPage) ReadPage(ctx context.Context) (dataset.PageData, error) { + pages, err := result.Collect(p.dec.ReadPages(ctx, []*streamsmd.PageDesc{p.desc})) + if err != nil { + return nil, err + } else if len(pages) != 1 { + return nil, fmt.Errorf("unexpected number of pages: got=%d want=1", len(pages)) + } + + return pages[0], nil +} diff --git a/pkg/dataobj/internal/encoding/decoder.go b/pkg/dataobj/internal/encoding/decoder.go new file mode 100644 index 0000000000000..d6ed5a87e4dfb --- /dev/null +++ b/pkg/dataobj/internal/encoding/decoder.go @@ -0,0 +1,41 @@ +package encoding + +import ( + "context" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/dataset" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/result" +) + +// Decoders. To cleanly separate the APIs per section, section-specific +// Decoders should be created and returned by the top-level [Decoder] +// interface. +type ( + // A Decoder decodes a data object. + Decoder interface { + // Sections returns the list of sections within a data object. + Sections(ctx context.Context) ([]*filemd.SectionInfo, error) + + // StreamsDecoder returns a decoder for streams sections. + StreamsDecoder() StreamsDecoder + } + + // StreamsDecoder supports decoding data within a streams section. + StreamsDecoder interface { + // Columns describes the set of columns in the provided section. + Columns(ctx context.Context, section *filemd.SectionInfo) ([]*streamsmd.ColumnDesc, error) + + // Pages retrieves the set of pages for the provided columns. The order of + // page lists emitted by the sequence matches the order of columns + // provided: the first page list corresponds to the first column, and so + // on. + Pages(ctx context.Context, columns []*streamsmd.ColumnDesc) result.Seq[[]*streamsmd.PageDesc] + + // ReadPages reads the provided set of pages, iterating over their data + // matching the argument order. If an error is encountered while retrieving + // pages, an error is emitted and iteration stops. + ReadPages(ctx context.Context, pages []*streamsmd.PageDesc) result.Seq[dataset.PageData] + } +) diff --git a/pkg/dataobj/internal/encoding/decoder_metadata.go b/pkg/dataobj/internal/encoding/decoder_metadata.go new file mode 100644 index 0000000000000..c1c3011ac6612 --- /dev/null +++ b/pkg/dataobj/internal/encoding/decoder_metadata.go @@ -0,0 +1,83 @@ +package encoding + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + + "github.com/gogo/protobuf/proto" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/streamio" +) + +// decode* methods for metadata shared by Decoder implementations. + +// decodeFileMetadata decodes file metadata from r. +func decodeFileMetadata(r streamio.Reader) (*filemd.Metadata, error) { + gotVersion, err := streamio.ReadUvarint(r) + if err != nil { + return nil, fmt.Errorf("read file format version: %w", err) + } else if gotVersion != fileFormatVersion { + return nil, fmt.Errorf("unexpected file format version: got=%d want=%d", gotVersion, fileFormatVersion) + } + + var md filemd.Metadata + if err := decodeProto(r, &md); err != nil { + return nil, fmt.Errorf("file metadata: %w", err) + } + return &md, nil +} + +// decodeStreamsMetadata decodes stream section metadta from r. +func decodeStreamsMetadata(r streamio.Reader) (*streamsmd.Metadata, error) { + gotVersion, err := streamio.ReadUvarint(r) + if err != nil { + return nil, fmt.Errorf("read streams section format version: %w", err) + } else if gotVersion != streamsFormatVersion { + return nil, fmt.Errorf("unexpected streams section format version: got=%d want=%d", gotVersion, streamsFormatVersion) + } + + var md streamsmd.Metadata + if err := decodeProto(r, &md); err != nil { + return nil, fmt.Errorf("streams section metadata: %w", err) + } + return &md, nil +} + +// decodeStreamsColumnMetadata decodes stream column metadata from r. +func decodeStreamsColumnMetadata(r streamio.Reader) (*streamsmd.ColumnMetadata, error) { + var metadata streamsmd.ColumnMetadata + if err := decodeProto(r, &metadata); err != nil { + return nil, fmt.Errorf("streams column metadata: %w", err) + } + return &metadata, nil +} + +// decodeProto decodes a proto message from r and stores it in pb. Proto +// messages are expected to be encoded with their size, followed by the proto +// bytes. +func decodeProto(r streamio.Reader, pb proto.Message) error { + size, err := binary.ReadUvarint(r) + if err != nil { + return fmt.Errorf("read proto message size: %w", err) + } + + buf := bytesBufferPool.Get().(*bytes.Buffer) + buf.Reset() + defer bytesBufferPool.Put(buf) + + n, err := io.Copy(buf, io.LimitReader(r, int64(size))) + if err != nil { + return fmt.Errorf("read proto message: %w", err) + } else if uint64(n) != size { + return fmt.Errorf("read proto message: got=%d want=%d", n, size) + } + + if err := proto.Unmarshal(buf.Bytes(), pb); err != nil { + return fmt.Errorf("unmarshal proto message: %w", err) + } + return nil +} diff --git a/pkg/dataobj/internal/encoding/decoder_readseeker.go b/pkg/dataobj/internal/encoding/decoder_readseeker.go new file mode 100644 index 0000000000000..725273603eb63 --- /dev/null +++ b/pkg/dataobj/internal/encoding/decoder_readseeker.go @@ -0,0 +1,123 @@ +package encoding + +import ( + "bufio" + "context" + "encoding/binary" + "fmt" + "io" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/dataset" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/result" +) + +type readSeekerDecoder struct { + rs io.ReadSeeker +} + +// ReadSeekerDecoder decodes a data object from the provided [io.ReadSeeker]. +func ReadSeekerDecoder(rs io.ReadSeeker) Decoder { + return &readSeekerDecoder{rs: rs} +} + +func (dec *readSeekerDecoder) Sections(_ context.Context) ([]*filemd.SectionInfo, error) { + var metadataSize uint32 + if _, err := dec.rs.Seek(-8, io.SeekEnd); err != nil { + return nil, fmt.Errorf("seek to file metadata size: %w", err) + } else if err := binary.Read(dec.rs, binary.LittleEndian, &metadataSize); err != nil { + return nil, fmt.Errorf("reading file metadata size: %w", err) + } + + if _, err := dec.rs.Seek(-int64(metadataSize)-8, io.SeekEnd); err != nil { + return nil, fmt.Errorf("seek to file metadata: %w", err) + } + + r := bufio.NewReader(io.LimitReader(dec.rs, int64(metadataSize))) + + md, err := decodeFileMetadata(r) + if err != nil { + return nil, err + } + return md.Sections, nil +} + +func (dec *readSeekerDecoder) StreamsDecoder() StreamsDecoder { + return &readSeekerStreamsDecoder{rs: dec.rs} +} + +type readSeekerStreamsDecoder struct { + rs io.ReadSeeker +} + +func (dec *readSeekerStreamsDecoder) Columns(_ context.Context, section *filemd.SectionInfo) ([]*streamsmd.ColumnDesc, error) { + if section.Type != filemd.SECTION_TYPE_STREAMS { + return nil, fmt.Errorf("unexpected section type: got=%d want=%d", section.Type, filemd.SECTION_TYPE_STREAMS) + } + + if _, err := dec.rs.Seek(int64(section.MetadataOffset), io.SeekStart); err != nil { + return nil, fmt.Errorf("seek to streams metadata: %w", err) + } + r := bufio.NewReader(io.LimitReader(dec.rs, int64(section.MetadataSize))) + + md, err := decodeStreamsMetadata(r) + if err != nil { + return nil, err + } + return md.Columns, nil +} + +func (dec *readSeekerStreamsDecoder) Pages(ctx context.Context, columns []*streamsmd.ColumnDesc) result.Seq[[]*streamsmd.PageDesc] { + getPages := func(_ context.Context, column *streamsmd.ColumnDesc) ([]*streamsmd.PageDesc, error) { + if _, err := dec.rs.Seek(int64(column.Info.MetadataOffset), io.SeekStart); err != nil { + return nil, fmt.Errorf("seek to column metadata: %w", err) + } + r := bufio.NewReader(io.LimitReader(dec.rs, int64(column.Info.MetadataSize))) + + md, err := decodeStreamsColumnMetadata(r) + if err != nil { + return nil, err + } + return md.Pages, nil + } + + return result.Iter(func(yield func([]*streamsmd.PageDesc) bool) error { + for _, column := range columns { + pages, err := getPages(ctx, column) + if err != nil { + return err + } else if !yield(pages) { + return nil + } + } + + return nil + }) +} + +func (dec *readSeekerStreamsDecoder) ReadPages(ctx context.Context, pages []*streamsmd.PageDesc) result.Seq[dataset.PageData] { + getPageData := func(_ context.Context, page *streamsmd.PageDesc) (dataset.PageData, error) { + if _, err := dec.rs.Seek(int64(page.Info.DataOffset), io.SeekStart); err != nil { + return nil, err + } + data := make([]byte, page.Info.DataSize) + if _, err := io.ReadFull(dec.rs, data); err != nil { + return nil, fmt.Errorf("read page data: %w", err) + } + return dataset.PageData(data), nil + } + + return result.Iter(func(yield func(dataset.PageData) bool) error { + for _, page := range pages { + data, err := getPageData(ctx, page) + if err != nil { + return err + } else if !yield(data) { + return nil + } + } + + return nil + }) +} diff --git a/pkg/dataobj/internal/encoding/encoder.go b/pkg/dataobj/internal/encoding/encoder.go new file mode 100644 index 0000000000000..28a64524e9735 --- /dev/null +++ b/pkg/dataobj/internal/encoding/encoder.go @@ -0,0 +1,152 @@ +package encoding + +import ( + "bytes" + "encoding/binary" + "fmt" + "math" + + "github.com/gogo/protobuf/proto" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/streamio" +) + +// Encoder encodes a data object. Data objects are hierarchical, split into +// distinct sections that contain their own hierarchy. +// +// To support hierarchical encoding, a set of Open* methods are provided to +// open a child element. Only one child element may be open at a given time; +// call Commit or Discard on a child element to close it. +type Encoder struct { + w streamio.Writer + + startOffset int // Byte offset in the file where data starts after the header. + + sections []*filemd.SectionInfo + curSection *filemd.SectionInfo + + data *bytes.Buffer +} + +// NewEncoder creates a new Encoder which writes a data object to the provided +// writer. +func NewEncoder(w streamio.Writer) *Encoder { + buf := bytesBufferPool.Get().(*bytes.Buffer) + buf.Reset() + + return &Encoder{ + w: w, + + startOffset: len(magic), + + data: buf, + } +} + +// OpenStreams opens a [StreamsEncoder]. OpenSterams fails if there is another +// open section. +func (enc *Encoder) OpenStreams() (*StreamsEncoder, error) { + if enc.curSection != nil { + return nil, ErrElementExist + } + + // MetadtaOffset and MetadataSize aren't available until the section is + // closed. We temporarily set these fields to the maximum values so they're + // accounted for in the MetadataSize estimate. + enc.curSection = &filemd.SectionInfo{ + Type: filemd.SECTION_TYPE_STREAMS, + MetadataOffset: math.MaxUint32, + MetadataSize: math.MaxUint32, + } + + return newStreamsEncoder( + enc, + enc.startOffset+enc.data.Len(), + ), nil +} + +// MetadataSize returns an estimate of the current size of the metadata for the +// data object. MetadataSize does not include the size of data appended. The +// estimate includes the currently open element. +func (enc *Encoder) MetadataSize() int { return elementMetadataSize(enc) } + +func (enc *Encoder) metadata() proto.Message { + sections := enc.sections[:len(enc.sections):cap(enc.sections)] + if enc.curSection != nil { + sections = append(sections, enc.curSection) + } + return &filemd.Metadata{Sections: sections} +} + +// Flush flushes any buffered data to the underlying writer. After flushing, +// enc is reset. Flush fails if there is currently an open section. +func (enc *Encoder) Flush() error { + if enc.curSection != nil { + return ErrElementExist + } + + metadataBuffer := bytesBufferPool.Get().(*bytes.Buffer) + metadataBuffer.Reset() + defer bytesBufferPool.Put(metadataBuffer) + + // The file metadata should start with the version. + if err := streamio.WriteUvarint(metadataBuffer, fileFormatVersion); err != nil { + return err + } else if err := elementMetadataWrite(enc, metadataBuffer); err != nil { + return err + } + + // The overall structure is: + // + // header: + // [magic] + // body: + // [data] + // [metadata] + // tailer: + // [file metadata size (32 bits)] + // [magic] + // + // The file metadata size *must not* be varint since we need the last 8 bytes + // of the file to consistently retrieve the tailer. + + if _, err := enc.w.Write(magic); err != nil { + return fmt.Errorf("writing magic header: %w", err) + } else if _, err := enc.w.Write(enc.data.Bytes()); err != nil { + return fmt.Errorf("writing data: %w", err) + } else if _, err := enc.w.Write(metadataBuffer.Bytes()); err != nil { + return fmt.Errorf("writing metadata: %w", err) + } else if err := binary.Write(enc.w, binary.LittleEndian, uint32(metadataBuffer.Len())); err != nil { + return fmt.Errorf("writing metadata size: %w", err) + } else if _, err := enc.w.Write(magic); err != nil { + return fmt.Errorf("writing magic tailer: %w", err) + } + + enc.sections = nil + enc.data.Reset() + return nil +} + +func (enc *Encoder) append(data, metadata []byte) error { + if enc.curSection == nil { + return errElementNoExist + } + + if len(data) == 0 && len(metadata) == 0 { + // Section was discarded. + enc.curSection = nil + return nil + } + + enc.curSection.MetadataOffset = uint32(enc.startOffset + enc.data.Len() + len(data)) + enc.curSection.MetadataSize = uint32(len(metadata)) + + // bytes.Buffer.Write never fails. + _, _ = enc.data.Write(data) + _, _ = enc.data.Write(metadata) + + enc.sections = append(enc.sections, enc.curSection) + enc.curSection = nil + return nil +} diff --git a/pkg/dataobj/internal/encoding/encoder_helpers.go b/pkg/dataobj/internal/encoding/encoder_helpers.go new file mode 100644 index 0000000000000..87504eec811fa --- /dev/null +++ b/pkg/dataobj/internal/encoding/encoder_helpers.go @@ -0,0 +1,42 @@ +package encoding + +import ( + "io" + + "github.com/gogo/protobuf/proto" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/streamio" +) + +type element interface { + metadata() proto.Message +} + +func elementMetadataSize(e element) int { + return proto.Size(e.metadata()) +} + +func elementMetadataWrite(e element, w streamio.Writer) error { + buf := protoBufferPool.Get().(*proto.Buffer) + buf.Reset() + defer protoBufferPool.Put(buf) + + if err := buf.Marshal(e.metadata()); err != nil { + return err + } + + // Every protobuf message is always prepended with its size as a uvarint. + messageSize := len(buf.Bytes()) + if err := streamio.WriteUvarint(w, uint64(messageSize)); err != nil { + return err + } + + sz, err := w.Write(buf.Bytes()) + if err != nil { + return err + } else if sz != messageSize { + return io.ErrShortWrite + } + + return nil +} diff --git a/pkg/dataobj/internal/encoding/encoder_streams.go b/pkg/dataobj/internal/encoding/encoder_streams.go new file mode 100644 index 0000000000000..b02e5a90bd714 --- /dev/null +++ b/pkg/dataobj/internal/encoding/encoder_streams.go @@ -0,0 +1,259 @@ +package encoding + +import ( + "bytes" + "math" + + "github.com/gogo/protobuf/proto" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/dataset" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/datasetmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/streamio" +) + +// StreamsEncoder encodes an individual streams section in a data object. +// StreamsEncoder are created by [Encoder]s. +type StreamsEncoder struct { + parent *Encoder + + startOffset int // Byte offset in the file where the column starts. + closed bool // true if StreamsEncoder has been closed. + + data *bytes.Buffer + columns []*streamsmd.ColumnDesc // closed columns. + curColumn *streamsmd.ColumnDesc // curColumn is the currently open column. +} + +func newStreamsEncoder(parent *Encoder, offset int) *StreamsEncoder { + buf := bytesBufferPool.Get().(*bytes.Buffer) + buf.Reset() + + return &StreamsEncoder{ + parent: parent, + startOffset: offset, + + data: buf, + } +} + +// OpenColumn opens a new column in the streams section. OpenColumn fails if +// there is another open column or if the StreamsEncoder has been closed. +func (enc *StreamsEncoder) OpenColumn(columnType streamsmd.ColumnType, info *dataset.ColumnInfo) (*StreamsColumnEncoder, error) { + if enc.curColumn != nil { + return nil, ErrElementExist + } else if enc.closed { + return nil, ErrClosed + } + + // MetadataOffset and MetadataSize aren't available until the column is + // closed. We temporarily set these fields to the maximum values so they're + // accounted for in the MetadataSize estimate. + enc.curColumn = &streamsmd.ColumnDesc{ + Type: columnType, + Info: &datasetmd.ColumnInfo{ + Name: info.Name, + ValueType: info.Type, + RowsCount: uint32(info.RowsCount), + Compression: info.Compression, + UncompressedSize: uint32(info.UncompressedSize), + CompressedSize: uint32(info.CompressedSize), + Statistics: info.Statistics, + + MetadataOffset: math.MaxUint32, + MetadataSize: math.MaxUint32, + }, + } + + return newStreamsColumnEncoder( + enc, + enc.startOffset+enc.data.Len(), + ), nil +} + +// MetadataSize returns an estimate of the current size of the metadata for the +// stream. MetadataSize includes an estimate for the currently open element. +func (enc *StreamsEncoder) MetadataSize() int { return elementMetadataSize(enc) } + +func (enc *StreamsEncoder) metadata() proto.Message { + columns := enc.columns[:len(enc.columns):cap(enc.columns)] + if enc.curColumn != nil { + columns = append(columns, enc.curColumn) + } + return &streamsmd.Metadata{Columns: columns} +} + +// Commit closes the section, flushing all data to the parent element. After +// Commit is called, the StreamsEncoder can no longer be modified. +// +// Commit fails if there is an open column. +func (enc *StreamsEncoder) Commit() error { + if enc.closed { + return ErrClosed + } else if enc.curColumn != nil { + return ErrElementExist + } + + defer bytesBufferPool.Put(enc.data) + + if len(enc.columns) == 0 { + // No data was written; discard. + return enc.parent.append(nil, nil) + } + + metadataBuffer := bytesBufferPool.Get().(*bytes.Buffer) + metadataBuffer.Reset() + defer bytesBufferPool.Put(metadataBuffer) + + // The section metadata should start with its version. + if err := streamio.WriteUvarint(metadataBuffer, streamsFormatVersion); err != nil { + return err + } else if err := elementMetadataWrite(enc, metadataBuffer); err != nil { + return err + } + return enc.parent.append(enc.data.Bytes(), metadataBuffer.Bytes()) +} + +// Discard discards the section, discarding any data written to it. After +// Discard is called, the StreamsEncoder can no longer be modified. +// +// Discard fails if there is an open column. +func (enc *StreamsEncoder) Discard() error { + if enc.closed { + return ErrClosed + } else if enc.curColumn != nil { + return ErrElementExist + } + enc.closed = true + + defer bytesBufferPool.Put(enc.data) + + return enc.parent.append(nil, nil) +} + +// append adds data and metadata to enc. append must only be called from child +// elements on Close and Discard. Discard calls must pass nil for both data and +// metadata to denote a discard. +func (enc *StreamsEncoder) append(data, metadata []byte) error { + if enc.closed { + return ErrClosed + } else if enc.curColumn == nil { + return errElementNoExist + } + + if len(data) == 0 && len(metadata) == 0 { + // Column was discarded. + enc.curColumn = nil + return nil + } + + enc.curColumn.Info.MetadataOffset = uint32(enc.startOffset + enc.data.Len() + len(data)) + enc.curColumn.Info.MetadataSize = uint32(len(metadata)) + + // bytes.Buffer.Write never fails. + _, _ = enc.data.Write(data) + _, _ = enc.data.Write(metadata) + + enc.columns = append(enc.columns, enc.curColumn) + enc.curColumn = nil + return nil +} + +// StreamsColumnEncoder encodes an individual column in a streams section. +// StreamsColumnEncoder are created by [StreamsEncoder]. +type StreamsColumnEncoder struct { + parent *StreamsEncoder + + startOffset int // Byte offset in the file where the column starts. + closed bool // true if StreamsColumnEncoder has been closed. + + data *bytes.Buffer // All page data. + pages []*streamsmd.PageDesc +} + +func newStreamsColumnEncoder(parent *StreamsEncoder, offset int) *StreamsColumnEncoder { + buf := bytesBufferPool.Get().(*bytes.Buffer) + buf.Reset() + + return &StreamsColumnEncoder{ + parent: parent, + startOffset: offset, + + data: buf, + } +} + +// AppendPage appens a new [dataset.MemPage] to the column. AppendPage fails if +// the column has been closed. +func (enc *StreamsColumnEncoder) AppendPage(page *dataset.MemPage) error { + if enc.closed { + return ErrClosed + } + + // It's possible the caller can pass an incorrect value for UncompressedSize + // and CompressedSize, but those fields are purely for stats so we don't + // check it. + enc.pages = append(enc.pages, &streamsmd.PageDesc{ + Info: &datasetmd.PageInfo{ + UncompressedSize: uint32(page.Info.UncompressedSize), + CompressedSize: uint32(page.Info.CompressedSize), + Crc32: page.Info.CRC32, + RowsCount: uint32(page.Info.RowCount), + Encoding: page.Info.Encoding, + + DataOffset: uint32(enc.startOffset + enc.data.Len()), + DataSize: uint32(len(page.Data)), + + Statistics: page.Info.Stats, + }, + }) + + _, _ = enc.data.Write(page.Data) // bytes.Buffer.Write never fails. + return nil +} + +// MetadataSize returns an estimate of the current size of the metadata for the +// column. MetadataSize does not include the size of data appended. +func (enc *StreamsColumnEncoder) MetadataSize() int { return elementMetadataSize(enc) } + +func (enc *StreamsColumnEncoder) metadata() proto.Message { + return &streamsmd.ColumnMetadata{Pages: enc.pages} +} + +// Commit closes the column, flushing all data to the parent element. After +// Commit is called, the StreamsColumnEncoder can no longer be modified. +func (enc *StreamsColumnEncoder) Commit() error { + if enc.closed { + return ErrClosed + } + enc.closed = true + + defer bytesBufferPool.Put(enc.data) + + if len(enc.pages) == 0 { + // No data was written; discard. + return enc.parent.append(nil, nil) + } + + metadataBuffer := bytesBufferPool.Get().(*bytes.Buffer) + metadataBuffer.Reset() + defer bytesBufferPool.Put(metadataBuffer) + + if err := elementMetadataWrite(enc, metadataBuffer); err != nil { + return err + } + return enc.parent.append(enc.data.Bytes(), metadataBuffer.Bytes()) +} + +// Discard discards the column, discarding any data written to it. After +// Discard is called, the StreamsColumnEncoder can no longer be modified. +func (enc *StreamsColumnEncoder) Discard() error { + if enc.closed { + return ErrClosed + } + enc.closed = true + + defer bytesBufferPool.Put(enc.data) + + return enc.parent.append(nil, nil) // Notify parent of discard. +} diff --git a/pkg/dataobj/internal/encoding/encoding.go b/pkg/dataobj/internal/encoding/encoding.go new file mode 100644 index 0000000000000..8b229970a8aea --- /dev/null +++ b/pkg/dataobj/internal/encoding/encoding.go @@ -0,0 +1,23 @@ +// Package encoding provides utilities for encoding and decoding data objects. +package encoding + +import "errors" + +var ( + magic = []byte("THOR") +) + +const ( + fileFormatVersion = 0x1 + streamsFormatVersion = 0x1 +) + +var ( + ErrElementExist = errors.New("open element already exists") + ErrClosed = errors.New("element is closed") + + // errElementNoExist is used when a child element tries to notify its parent + // of it closing but the parent doesn't have a child open. This would + // indicate a bug in the encoder so it's not exposed to callers. + errElementNoExist = errors.New("open element does not exist") +) diff --git a/pkg/dataobj/internal/encoding/encoding_test.go b/pkg/dataobj/internal/encoding/encoding_test.go new file mode 100644 index 0000000000000..f5f7400e986b9 --- /dev/null +++ b/pkg/dataobj/internal/encoding/encoding_test.go @@ -0,0 +1,109 @@ +package encoding_test + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/dataset" + "github.com/grafana/loki/v3/pkg/dataobj/internal/encoding" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/datasetmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd" + "github.com/grafana/loki/v3/pkg/dataobj/internal/result" +) + +func Test(t *testing.T) { + type Country struct { + Name string + Capital string + } + + countries := []Country{ + {"India", "New Delhi"}, + {"USA", "Washington D.C."}, + {"UK", "London"}, + {"France", "Paris"}, + {"Germany", "Berlin"}, + } + + var buf bytes.Buffer + + t.Run("Encode", func(t *testing.T) { + nameBuilder, err := dataset.NewColumnBuilder("name", dataset.BuilderOptions{ + Value: datasetmd.VALUE_TYPE_STRING, + Encoding: datasetmd.ENCODING_TYPE_PLAIN, + Compression: datasetmd.COMPRESSION_TYPE_NONE, + }) + require.NoError(t, err) + + capitalBuilder, err := dataset.NewColumnBuilder("capital", dataset.BuilderOptions{ + Value: datasetmd.VALUE_TYPE_STRING, + Encoding: datasetmd.ENCODING_TYPE_PLAIN, + Compression: datasetmd.COMPRESSION_TYPE_NONE, + }) + require.NoError(t, err) + + for i, c := range countries { + require.NoError(t, nameBuilder.Append(i, dataset.StringValue(c.Name))) + require.NoError(t, capitalBuilder.Append(i, dataset.StringValue(c.Capital))) + } + + nameColumn, err := nameBuilder.Flush() + require.NoError(t, err) + capitalColumn, err := capitalBuilder.Flush() + require.NoError(t, err) + + enc := encoding.NewEncoder(&buf) + streamsEnc, err := enc.OpenStreams() + require.NoError(t, err) + + colEnc, err := streamsEnc.OpenColumn(streamsmd.COLUMN_TYPE_LABEL, &nameColumn.Info) + require.NoError(t, err) + for _, page := range nameColumn.Pages { + require.NoError(t, colEnc.AppendPage(page)) + } + require.NoError(t, colEnc.Commit()) + + colEnc, err = streamsEnc.OpenColumn(streamsmd.COLUMN_TYPE_LABEL, &capitalColumn.Info) + require.NoError(t, err) + for _, page := range capitalColumn.Pages { + require.NoError(t, colEnc.AppendPage(page)) + } + require.NoError(t, colEnc.Commit()) + + require.NoError(t, streamsEnc.Commit()) + require.NoError(t, enc.Flush()) + }) + + t.Run("Decode", func(t *testing.T) { + dec := encoding.ReadSeekerDecoder(bytes.NewReader(buf.Bytes())) + sections, err := dec.Sections(context.TODO()) + require.NoError(t, err) + require.Len(t, sections, 1) + require.Equal(t, filemd.SECTION_TYPE_STREAMS, sections[0].Type) + + dset := encoding.StreamsDataset(dec.StreamsDecoder(), sections[0]) + + columns, err := result.Collect(dset.ListColumns(context.Background())) + require.NoError(t, err) + + var actual []Country + + for result := range dataset.Iter(context.Background(), columns) { + row, err := result.Value() + require.NoError(t, err) + require.Len(t, row.Values, 2) + require.Equal(t, len(actual), row.Index) + + actual = append(actual, Country{ + Name: row.Values[0].String(), + Capital: row.Values[1].String(), + }) + } + + require.Equal(t, countries, actual) + }) +} diff --git a/pkg/dataobj/internal/encoding/pools.go b/pkg/dataobj/internal/encoding/pools.go new file mode 100644 index 0000000000000..5edf16eb6acdc --- /dev/null +++ b/pkg/dataobj/internal/encoding/pools.go @@ -0,0 +1,20 @@ +package encoding + +import ( + "bytes" + "sync" + + "github.com/gogo/protobuf/proto" +) + +var bytesBufferPool = sync.Pool{ + New: func() any { + return new(bytes.Buffer) + }, +} + +var protoBufferPool = sync.Pool{ + New: func() any { + return new(proto.Buffer) + }, +} diff --git a/pkg/dataobj/internal/metadata/datasetmd/datasetmd.pb.go b/pkg/dataobj/internal/metadata/datasetmd/datasetmd.pb.go index 4121ca928c598..fcbbefbebef32 100644 --- a/pkg/dataobj/internal/metadata/datasetmd/datasetmd.pb.go +++ b/pkg/dataobj/internal/metadata/datasetmd/datasetmd.pb.go @@ -58,6 +58,39 @@ func (ValueType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_7ab9d5b21b743868, []int{0} } +// CompressionType represents the valid compression types that can be used for +// compressing values in a page. +type CompressionType int32 + +const ( + // Invalid compression type. + COMPRESSION_TYPE_UNSPECIFIED CompressionType = 0 + // No compression. + COMPRESSION_TYPE_NONE CompressionType = 1 + // Snappy compression. + COMPRESSION_TYPE_SNAPPY CompressionType = 2 + // Zstd compression. + COMPRESSION_TYPE_ZSTD CompressionType = 3 +) + +var CompressionType_name = map[int32]string{ + 0: "COMPRESSION_TYPE_UNSPECIFIED", + 1: "COMPRESSION_TYPE_NONE", + 2: "COMPRESSION_TYPE_SNAPPY", + 3: "COMPRESSION_TYPE_ZSTD", +} + +var CompressionType_value = map[string]int32{ + "COMPRESSION_TYPE_UNSPECIFIED": 0, + "COMPRESSION_TYPE_NONE": 1, + "COMPRESSION_TYPE_SNAPPY": 2, + "COMPRESSION_TYPE_ZSTD": 3, +} + +func (CompressionType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_7ab9d5b21b743868, []int{1} +} + // EncodingType represents the valid types that a sequence of values which a // column can be encoded with. type EncodingType int32 @@ -90,40 +123,125 @@ var EncodingType_value = map[string]int32{ } func (EncodingType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_7ab9d5b21b743868, []int{1} + return fileDescriptor_7ab9d5b21b743868, []int{2} } -// CompressionType represents the valid compression types that can be used for -// compressing values in a page. -type CompressionType int32 +// ColumnInfo describes an individual column within a data set. +type ColumnInfo struct { + // Optional name of the column. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Type of values stored within the column. + ValueType ValueType `protobuf:"varint,2,opt,name=value_type,json=valueType,proto3,enum=dataobj.metadata.dataset.v1.ValueType" json:"value_type,omitempty"` + // Total number of rows in the entire column. + RowsCount uint32 `protobuf:"varint,3,opt,name=rows_count,json=rowsCount,proto3" json:"rows_count,omitempty"` + // Compression type used for all pages. + Compression CompressionType `protobuf:"varint,4,opt,name=compression,proto3,enum=dataobj.metadata.dataset.v1.CompressionType" json:"compression,omitempty"` + // Total uncompressed size of all pages in the column. + UncompressedSize uint32 `protobuf:"varint,5,opt,name=uncompressed_size,json=uncompressedSize,proto3" json:"uncompressed_size,omitempty"` + // Total compressed size of all pages in the column. Compressed size may + // match uncompressed size if no compression is used. + CompressedSize uint32 `protobuf:"varint,6,opt,name=compressed_size,json=compressedSize,proto3" json:"compressed_size,omitempty"` + // Byte offset from the start of the data object to the column's metadata. + MetadataOffset uint32 `protobuf:"varint,7,opt,name=metadata_offset,json=metadataOffset,proto3" json:"metadata_offset,omitempty"` + // Size of the column's metadata in bytes. + MetadataSize uint32 `protobuf:"varint,8,opt,name=metadata_size,json=metadataSize,proto3" json:"metadata_size,omitempty"` + // Statistics for the column. + Statistics *Statistics `protobuf:"bytes,9,opt,name=statistics,proto3" json:"statistics,omitempty"` +} -const ( - // Invalid compression type. - COMPRESSION_TYPE_UNSPECIFIED CompressionType = 0 - // No compression. - COMPRESSION_TYPE_NONE CompressionType = 1 - // Snappy compression. - COMPRESSION_TYPE_SNAPPY CompressionType = 2 - // Zstd compression. - COMPRESSION_TYPE_ZSTD CompressionType = 3 -) +func (m *ColumnInfo) Reset() { *m = ColumnInfo{} } +func (*ColumnInfo) ProtoMessage() {} +func (*ColumnInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_7ab9d5b21b743868, []int{0} +} +func (m *ColumnInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ColumnInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ColumnInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ColumnInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ColumnInfo.Merge(m, src) +} +func (m *ColumnInfo) XXX_Size() int { + return m.Size() +} +func (m *ColumnInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ColumnInfo.DiscardUnknown(m) +} -var CompressionType_name = map[int32]string{ - 0: "COMPRESSION_TYPE_UNSPECIFIED", - 1: "COMPRESSION_TYPE_NONE", - 2: "COMPRESSION_TYPE_SNAPPY", - 3: "COMPRESSION_TYPE_ZSTD", +var xxx_messageInfo_ColumnInfo proto.InternalMessageInfo + +func (m *ColumnInfo) GetName() string { + if m != nil { + return m.Name + } + return "" } -var CompressionType_value = map[string]int32{ - "COMPRESSION_TYPE_UNSPECIFIED": 0, - "COMPRESSION_TYPE_NONE": 1, - "COMPRESSION_TYPE_SNAPPY": 2, - "COMPRESSION_TYPE_ZSTD": 3, +func (m *ColumnInfo) GetValueType() ValueType { + if m != nil { + return m.ValueType + } + return VALUE_TYPE_UNSPECIFIED } -func (CompressionType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_7ab9d5b21b743868, []int{2} +func (m *ColumnInfo) GetRowsCount() uint32 { + if m != nil { + return m.RowsCount + } + return 0 +} + +func (m *ColumnInfo) GetCompression() CompressionType { + if m != nil { + return m.Compression + } + return COMPRESSION_TYPE_UNSPECIFIED +} + +func (m *ColumnInfo) GetUncompressedSize() uint32 { + if m != nil { + return m.UncompressedSize + } + return 0 +} + +func (m *ColumnInfo) GetCompressedSize() uint32 { + if m != nil { + return m.CompressedSize + } + return 0 +} + +func (m *ColumnInfo) GetMetadataOffset() uint32 { + if m != nil { + return m.MetadataOffset + } + return 0 +} + +func (m *ColumnInfo) GetMetadataSize() uint32 { + if m != nil { + return m.MetadataSize + } + return 0 +} + +func (m *ColumnInfo) GetStatistics() *Statistics { + if m != nil { + return m.Statistics + } + return nil } // Statistics about a column or a page. All statistics are optional and are @@ -138,7 +256,7 @@ type Statistics struct { func (m *Statistics) Reset() { *m = Statistics{} } func (*Statistics) ProtoMessage() {} func (*Statistics) Descriptor() ([]byte, []int) { - return fileDescriptor_7ab9d5b21b743868, []int{0} + return fileDescriptor_7ab9d5b21b743868, []int{1} } func (m *Statistics) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -181,11 +299,122 @@ func (m *Statistics) GetMaxValue() []byte { return nil } +// Page describes an individual page within a column. +type PageInfo struct { + // Uncompressed size of the page within the data object. + UncompressedSize uint32 `protobuf:"varint,1,opt,name=uncompressed_size,json=uncompressedSize,proto3" json:"uncompressed_size,omitempty"` + // Compressed size of the page within the data object. Compression size + // will match uncompressed size if no compression is used. + CompressedSize uint32 `protobuf:"varint,2,opt,name=compressed_size,json=compressedSize,proto3" json:"compressed_size,omitempty"` + // CRC32 checksum of the page data. + Crc32 uint32 `protobuf:"varint,3,opt,name=crc32,proto3" json:"crc32,omitempty"` + // Number of rows in the page. + RowsCount uint32 `protobuf:"varint,4,opt,name=rows_count,json=rowsCount,proto3" json:"rows_count,omitempty"` + // Encoding type used for the page. + Encoding EncodingType `protobuf:"varint,5,opt,name=encoding,proto3,enum=dataobj.metadata.dataset.v1.EncodingType" json:"encoding,omitempty"` + // Byte offset from the start of the data object to the page's data. + DataOffset uint32 `protobuf:"varint,6,opt,name=data_offset,json=dataOffset,proto3" json:"data_offset,omitempty"` + // Size of the page's data in bytes. + DataSize uint32 `protobuf:"varint,7,opt,name=data_size,json=dataSize,proto3" json:"data_size,omitempty"` + // Optional statistics for the page. + Statistics *Statistics `protobuf:"bytes,8,opt,name=statistics,proto3" json:"statistics,omitempty"` +} + +func (m *PageInfo) Reset() { *m = PageInfo{} } +func (*PageInfo) ProtoMessage() {} +func (*PageInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_7ab9d5b21b743868, []int{2} +} +func (m *PageInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PageInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PageInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PageInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_PageInfo.Merge(m, src) +} +func (m *PageInfo) XXX_Size() int { + return m.Size() +} +func (m *PageInfo) XXX_DiscardUnknown() { + xxx_messageInfo_PageInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_PageInfo proto.InternalMessageInfo + +func (m *PageInfo) GetUncompressedSize() uint32 { + if m != nil { + return m.UncompressedSize + } + return 0 +} + +func (m *PageInfo) GetCompressedSize() uint32 { + if m != nil { + return m.CompressedSize + } + return 0 +} + +func (m *PageInfo) GetCrc32() uint32 { + if m != nil { + return m.Crc32 + } + return 0 +} + +func (m *PageInfo) GetRowsCount() uint32 { + if m != nil { + return m.RowsCount + } + return 0 +} + +func (m *PageInfo) GetEncoding() EncodingType { + if m != nil { + return m.Encoding + } + return ENCODING_TYPE_UNSPECIFIED +} + +func (m *PageInfo) GetDataOffset() uint32 { + if m != nil { + return m.DataOffset + } + return 0 +} + +func (m *PageInfo) GetDataSize() uint32 { + if m != nil { + return m.DataSize + } + return 0 +} + +func (m *PageInfo) GetStatistics() *Statistics { + if m != nil { + return m.Statistics + } + return nil +} + func init() { proto.RegisterEnum("dataobj.metadata.dataset.v1.ValueType", ValueType_name, ValueType_value) - proto.RegisterEnum("dataobj.metadata.dataset.v1.EncodingType", EncodingType_name, EncodingType_value) proto.RegisterEnum("dataobj.metadata.dataset.v1.CompressionType", CompressionType_name, CompressionType_value) + proto.RegisterEnum("dataobj.metadata.dataset.v1.EncodingType", EncodingType_name, EncodingType_value) + proto.RegisterType((*ColumnInfo)(nil), "dataobj.metadata.dataset.v1.ColumnInfo") proto.RegisterType((*Statistics)(nil), "dataobj.metadata.dataset.v1.Statistics") + proto.RegisterType((*PageInfo)(nil), "dataobj.metadata.dataset.v1.PageInfo") } func init() { @@ -193,34 +422,50 @@ func init() { } var fileDescriptor_7ab9d5b21b743868 = []byte{ - // 420 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0x31, 0x6f, 0xd3, 0x40, - 0x1c, 0xc5, 0x7d, 0x89, 0x84, 0xe8, 0x5f, 0x95, 0x38, 0x4c, 0x4b, 0x5b, 0x02, 0xa7, 0x8a, 0x09, - 0x65, 0xb0, 0x85, 0x8a, 0x60, 0x76, 0x92, 0x6b, 0x75, 0x52, 0x7a, 0xb1, 0x62, 0xb7, 0x52, 0xbb, - 0x44, 0x97, 0xc4, 0x84, 0x23, 0xf1, 0x9d, 0x65, 0x5f, 0xa3, 0x74, 0x63, 0x62, 0xe6, 0x63, 0xf0, - 0x51, 0x18, 0x33, 0x76, 0x24, 0xce, 0xc2, 0xd8, 0x8f, 0x80, 0x6a, 0x8c, 0x68, 0x48, 0x86, 0x6e, - 0xff, 0x7b, 0xbf, 0xf7, 0xf4, 0x6e, 0x78, 0xf0, 0x21, 0x19, 0x8f, 0xdc, 0xa1, 0x30, 0x42, 0xf7, - 0x3f, 0xbb, 0x52, 0x99, 0x28, 0x55, 0x62, 0xe2, 0xc6, 0x91, 0x11, 0x77, 0x62, 0x41, 0xb2, 0xc8, - 0xc4, 0xc3, 0x7f, 0x97, 0x93, 0xa4, 0xda, 0x68, 0xbb, 0x56, 0x86, 0x9c, 0xbf, 0x5e, 0xa7, 0x74, - 0x38, 0xd3, 0xb7, 0xaf, 0x8f, 0x01, 0x02, 0x23, 0x8c, 0xcc, 0x8c, 0x1c, 0x64, 0x76, 0x0d, 0xb6, - 0x62, 0xa9, 0x7a, 0x53, 0x31, 0xb9, 0x8a, 0xf6, 0xd1, 0x21, 0x7a, 0xb3, 0xdd, 0x7d, 0x1c, 0x4b, - 0x75, 0x7e, 0xf7, 0x2e, 0xa0, 0x98, 0x95, 0xb0, 0x52, 0x42, 0x31, 0x2b, 0x60, 0x7d, 0x0c, 0x5b, - 0xc5, 0x11, 0x5e, 0x27, 0x91, 0xfd, 0x02, 0x9e, 0x9f, 0x7b, 0xed, 0x33, 0xda, 0x0b, 0x2f, 0x7c, - 0xda, 0x3b, 0xe3, 0x81, 0x4f, 0x9b, 0xec, 0x98, 0xd1, 0x16, 0xb6, 0xec, 0x1d, 0xc0, 0xf7, 0x18, - 0xe3, 0xe1, 0xfb, 0x77, 0x18, 0xd9, 0xbb, 0xf0, 0xf4, 0x7e, 0xe2, 0x8f, 0x5c, 0xf9, 0x4f, 0x0e, - 0xc2, 0x2e, 0xe3, 0x27, 0xb8, 0x5a, 0xbf, 0x86, 0x6d, 0xaa, 0x06, 0x7a, 0x28, 0xd5, 0xa8, 0xe8, - 0x7b, 0x05, 0x07, 0x94, 0x37, 0x3b, 0x2d, 0xc6, 0x4f, 0x36, 0x55, 0xee, 0xc1, 0xb3, 0x55, 0xec, - 0xb7, 0x3d, 0xc6, 0x31, 0x5a, 0x07, 0x2d, 0xda, 0x0e, 0x3d, 0x5c, 0xb1, 0xf7, 0x61, 0x67, 0x15, - 0x34, 0x58, 0x78, 0xea, 0xf9, 0xb8, 0x5a, 0xff, 0x8a, 0xe0, 0x49, 0x53, 0xc7, 0x49, 0x1a, 0x65, - 0x99, 0xd4, 0xaa, 0xa8, 0x3f, 0x84, 0x97, 0xcd, 0xce, 0xa9, 0xdf, 0xa5, 0x41, 0xc0, 0x3a, 0x7c, - 0xd3, 0x0f, 0x0e, 0x60, 0x77, 0xcd, 0xc1, 0x3b, 0x9c, 0x62, 0x64, 0xd7, 0x60, 0x6f, 0x0d, 0x05, - 0xdc, 0xf3, 0xfd, 0x0b, 0x5c, 0xd9, 0x98, 0xbb, 0x0c, 0xc2, 0x16, 0xae, 0x36, 0x66, 0xf3, 0x05, - 0xb1, 0x6e, 0x16, 0xc4, 0xba, 0x5d, 0x10, 0xf4, 0x25, 0x27, 0xe8, 0x7b, 0x4e, 0xd0, 0x8f, 0x9c, - 0xa0, 0x79, 0x4e, 0xd0, 0xcf, 0x9c, 0xa0, 0x5f, 0x39, 0xb1, 0x6e, 0x73, 0x82, 0xbe, 0x2d, 0x89, - 0x35, 0x5f, 0x12, 0xeb, 0x66, 0x49, 0xac, 0xcb, 0xc6, 0x48, 0x9a, 0x4f, 0x57, 0x7d, 0x67, 0xa0, - 0x63, 0x77, 0x94, 0x8a, 0x8f, 0x42, 0x09, 0x77, 0xa2, 0xc7, 0xd2, 0x9d, 0x1e, 0xb9, 0x0f, 0xdc, - 0x57, 0xff, 0x51, 0x31, 0xab, 0xa3, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x79, 0x22, 0x11, 0xce, - 0x91, 0x02, 0x00, 0x00, + // 679 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4f, 0x4f, 0xdb, 0x4e, + 0x10, 0xcd, 0x26, 0xc0, 0x2f, 0x19, 0xfe, 0x99, 0xfd, 0x41, 0x31, 0x4d, 0x71, 0x23, 0x2a, 0x95, + 0x94, 0x56, 0xb6, 0x1a, 0xaa, 0xf6, 0x1c, 0x12, 0x83, 0x2c, 0x81, 0x63, 0xd9, 0x06, 0x09, 0x2e, + 0x96, 0x71, 0x36, 0xa9, 0x4b, 0x6c, 0x47, 0xb1, 0x93, 0x02, 0xa7, 0x9e, 0x7a, 0xee, 0xc7, 0xe8, + 0xf7, 0xe8, 0xa5, 0x47, 0x8e, 0x1c, 0x8b, 0x73, 0xe9, 0x91, 0x8f, 0x50, 0x65, 0xf3, 0xcf, 0x24, + 0x69, 0x84, 0x7a, 0x1b, 0xbf, 0xf7, 0x66, 0x66, 0x3d, 0x6f, 0x76, 0xe1, 0x43, 0xfd, 0xa2, 0x2a, + 0x94, 0xcd, 0xc0, 0xf4, 0xce, 0x3f, 0x09, 0xb6, 0x1b, 0x90, 0x86, 0x6b, 0xd6, 0x04, 0x87, 0x04, + 0x66, 0x07, 0xa4, 0x8c, 0x4f, 0x02, 0xa7, 0x3c, 0x8c, 0xf8, 0x7a, 0xc3, 0x0b, 0x3c, 0x9c, 0xee, + 0x25, 0xf1, 0x7d, 0x2d, 0xdf, 0x53, 0xf0, 0xad, 0xb7, 0x5b, 0x3f, 0x12, 0x00, 0x05, 0xaf, 0xd6, + 0x74, 0x5c, 0xc9, 0xad, 0x78, 0x18, 0xc3, 0x8c, 0x6b, 0x3a, 0x84, 0x45, 0x19, 0x94, 0x4d, 0xa9, + 0x34, 0xc6, 0x22, 0x40, 0xcb, 0xac, 0x35, 0x89, 0x11, 0x5c, 0xd5, 0x09, 0x1b, 0xcf, 0xa0, 0xec, + 0x52, 0xee, 0x25, 0x3f, 0xa5, 0x28, 0x7f, 0xd2, 0x91, 0xeb, 0x57, 0x75, 0xa2, 0xa6, 0x5a, 0xfd, + 0x10, 0x6f, 0x02, 0x34, 0xbc, 0xcf, 0xbe, 0x61, 0x79, 0x4d, 0x37, 0x60, 0x13, 0x19, 0x94, 0x5d, + 0x54, 0x53, 0x1d, 0xa4, 0xd0, 0x01, 0xb0, 0x0c, 0xf3, 0x96, 0xe7, 0xd4, 0x1b, 0xc4, 0xf7, 0x6d, + 0xcf, 0x65, 0x67, 0x68, 0x9b, 0x37, 0x53, 0xdb, 0x14, 0x86, 0x7a, 0xda, 0x2c, 0x5a, 0x00, 0xbf, + 0x86, 0x95, 0xa6, 0xdb, 0x07, 0x48, 0xd9, 0xf0, 0xed, 0x6b, 0xc2, 0xce, 0xd2, 0xae, 0x4c, 0x94, + 0xd0, 0xec, 0x6b, 0x82, 0xb7, 0x61, 0x79, 0x54, 0x3a, 0x47, 0xa5, 0x4b, 0xe3, 0xc2, 0xfe, 0x49, + 0x0c, 0xaf, 0x52, 0xf1, 0x49, 0xc0, 0xfe, 0xd7, 0x15, 0xf6, 0xe1, 0x12, 0x45, 0xf1, 0x0b, 0x58, + 0x1c, 0x08, 0x69, 0xbd, 0x24, 0x95, 0x2d, 0xf4, 0x41, 0x5a, 0xed, 0x00, 0xc0, 0x0f, 0xcc, 0xc0, + 0xf6, 0x03, 0xdb, 0xf2, 0xd9, 0x54, 0x06, 0x65, 0xe7, 0x73, 0xdb, 0x53, 0x7f, 0x59, 0x1b, 0xc8, + 0xd5, 0x48, 0xea, 0xd6, 0x3e, 0xc0, 0x90, 0xc1, 0x69, 0x48, 0x39, 0xb6, 0x6b, 0xd0, 0xd1, 0x53, + 0x27, 0x17, 0xd4, 0xa4, 0x63, 0xbb, 0xd4, 0x15, 0x4a, 0x9a, 0x97, 0x3d, 0x32, 0xde, 0x23, 0xcd, + 0x4b, 0x4a, 0x6e, 0xb5, 0xe3, 0x90, 0x54, 0xcc, 0x2a, 0xa1, 0xbb, 0x30, 0x71, 0x82, 0xe8, 0xf1, + 0x13, 0x8c, 0x4f, 0x9c, 0xe0, 0x2a, 0xcc, 0x5a, 0x0d, 0x6b, 0x37, 0xd7, 0xdb, 0x80, 0xee, 0xc7, + 0xc8, 0x72, 0xcc, 0x8c, 0x2e, 0x87, 0x08, 0x49, 0xe2, 0x5a, 0x5e, 0xd9, 0x76, 0xab, 0xd4, 0xc3, + 0xa5, 0xdc, 0xab, 0xa9, 0x63, 0x12, 0x7b, 0x62, 0xba, 0x16, 0x83, 0x54, 0xfc, 0x1c, 0xe6, 0xa3, + 0xce, 0x75, 0x2d, 0x86, 0x88, 0x6b, 0x69, 0x48, 0x0d, 0x1d, 0xeb, 0x1a, 0x9b, 0xfc, 0x8b, 0x5b, + 0xc9, 0x7f, 0x76, 0x6b, 0xe7, 0x02, 0x52, 0x83, 0x1b, 0x82, 0x9f, 0xc2, 0x93, 0x93, 0xfc, 0xe1, + 0xb1, 0x68, 0xe8, 0xa7, 0x8a, 0x68, 0x1c, 0xcb, 0x9a, 0x22, 0x16, 0xa4, 0x7d, 0x49, 0x2c, 0x32, + 0x31, 0xbc, 0x0a, 0x4c, 0x84, 0x93, 0x64, 0xfd, 0xfd, 0x3b, 0x06, 0xe1, 0x35, 0x58, 0x89, 0x66, + 0x74, 0xe1, 0xf8, 0x08, 0xac, 0xe9, 0xaa, 0x24, 0x1f, 0x30, 0x89, 0x9d, 0xaf, 0x08, 0x96, 0x47, + 0x2e, 0x0a, 0xce, 0xc0, 0xb3, 0x42, 0xe9, 0x48, 0x51, 0x45, 0x4d, 0x93, 0x4a, 0xf2, 0xa4, 0xce, + 0x1b, 0xb0, 0x36, 0xa6, 0x90, 0x4b, 0xb2, 0xc8, 0x20, 0x9c, 0x86, 0xf5, 0x31, 0x4a, 0x93, 0xf3, + 0x8a, 0x72, 0xca, 0xc4, 0x27, 0xe6, 0x9d, 0x69, 0x7a, 0x91, 0x49, 0xec, 0x5c, 0xc1, 0x42, 0xd4, + 0x16, 0xbc, 0x09, 0x1b, 0xa2, 0x5c, 0x28, 0x15, 0x25, 0xf9, 0x60, 0xd2, 0x09, 0xd6, 0xe1, 0xff, + 0x87, 0xb4, 0x72, 0x98, 0x97, 0x64, 0x06, 0x8d, 0x13, 0x45, 0xf1, 0x50, 0xcf, 0x33, 0x71, 0xcc, + 0xc2, 0xea, 0x43, 0x62, 0x4f, 0xd2, 0x8f, 0xf2, 0x0a, 0x93, 0xd8, 0xbb, 0xbc, 0xb9, 0xe3, 0x62, + 0xb7, 0x77, 0x5c, 0xec, 0xfe, 0x8e, 0x43, 0x5f, 0x42, 0x0e, 0x7d, 0x0f, 0x39, 0xf4, 0x33, 0xe4, + 0xd0, 0x4d, 0xc8, 0xa1, 0x5f, 0x21, 0x87, 0x7e, 0x87, 0x5c, 0xec, 0x3e, 0xe4, 0xd0, 0xb7, 0x36, + 0x17, 0xbb, 0x69, 0x73, 0xb1, 0xdb, 0x36, 0x17, 0x3b, 0xdb, 0xab, 0xda, 0xc1, 0xc7, 0xe6, 0x39, + 0x6f, 0x79, 0x8e, 0x50, 0x6d, 0x98, 0x15, 0xd3, 0x35, 0x85, 0x9a, 0x77, 0x61, 0x0b, 0xad, 0x5d, + 0xe1, 0x91, 0x6f, 0xf1, 0xf9, 0x1c, 0x7d, 0x82, 0x77, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0x5f, + 0xec, 0x7c, 0x9f, 0xbd, 0x05, 0x00, 0x00, } func (x ValueType) String() string { @@ -230,20 +475,68 @@ func (x ValueType) String() string { } return strconv.Itoa(int(x)) } -func (x EncodingType) String() string { - s, ok := EncodingType_name[int32(x)] +func (x CompressionType) String() string { + s, ok := CompressionType_name[int32(x)] if ok { return s } return strconv.Itoa(int(x)) } -func (x CompressionType) String() string { - s, ok := CompressionType_name[int32(x)] +func (x EncodingType) String() string { + s, ok := EncodingType_name[int32(x)] if ok { return s } return strconv.Itoa(int(x)) } +func (this *ColumnInfo) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ColumnInfo) + if !ok { + that2, ok := that.(ColumnInfo) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if this.ValueType != that1.ValueType { + return false + } + if this.RowsCount != that1.RowsCount { + return false + } + if this.Compression != that1.Compression { + return false + } + if this.UncompressedSize != that1.UncompressedSize { + return false + } + if this.CompressedSize != that1.CompressedSize { + return false + } + if this.MetadataOffset != that1.MetadataOffset { + return false + } + if this.MetadataSize != that1.MetadataSize { + return false + } + if !this.Statistics.Equal(that1.Statistics) { + return false + } + return true +} func (this *Statistics) Equal(that interface{}) bool { if that == nil { return this == nil @@ -271,6 +564,71 @@ func (this *Statistics) Equal(that interface{}) bool { } return true } +func (this *PageInfo) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PageInfo) + if !ok { + that2, ok := that.(PageInfo) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.UncompressedSize != that1.UncompressedSize { + return false + } + if this.CompressedSize != that1.CompressedSize { + return false + } + if this.Crc32 != that1.Crc32 { + return false + } + if this.RowsCount != that1.RowsCount { + return false + } + if this.Encoding != that1.Encoding { + return false + } + if this.DataOffset != that1.DataOffset { + return false + } + if this.DataSize != that1.DataSize { + return false + } + if !this.Statistics.Equal(that1.Statistics) { + return false + } + return true +} +func (this *ColumnInfo) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 13) + s = append(s, "&datasetmd.ColumnInfo{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + s = append(s, "ValueType: "+fmt.Sprintf("%#v", this.ValueType)+",\n") + s = append(s, "RowsCount: "+fmt.Sprintf("%#v", this.RowsCount)+",\n") + s = append(s, "Compression: "+fmt.Sprintf("%#v", this.Compression)+",\n") + s = append(s, "UncompressedSize: "+fmt.Sprintf("%#v", this.UncompressedSize)+",\n") + s = append(s, "CompressedSize: "+fmt.Sprintf("%#v", this.CompressedSize)+",\n") + s = append(s, "MetadataOffset: "+fmt.Sprintf("%#v", this.MetadataOffset)+",\n") + s = append(s, "MetadataSize: "+fmt.Sprintf("%#v", this.MetadataSize)+",\n") + if this.Statistics != nil { + s = append(s, "Statistics: "+fmt.Sprintf("%#v", this.Statistics)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} func (this *Statistics) GoString() string { if this == nil { return "nil" @@ -282,7 +640,26 @@ func (this *Statistics) GoString() string { s = append(s, "}") return strings.Join(s, "") } -func valueToGoStringDatasetmd(v interface{}, typ string) string { +func (this *PageInfo) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 12) + s = append(s, "&datasetmd.PageInfo{") + s = append(s, "UncompressedSize: "+fmt.Sprintf("%#v", this.UncompressedSize)+",\n") + s = append(s, "CompressedSize: "+fmt.Sprintf("%#v", this.CompressedSize)+",\n") + s = append(s, "Crc32: "+fmt.Sprintf("%#v", this.Crc32)+",\n") + s = append(s, "RowsCount: "+fmt.Sprintf("%#v", this.RowsCount)+",\n") + s = append(s, "Encoding: "+fmt.Sprintf("%#v", this.Encoding)+",\n") + s = append(s, "DataOffset: "+fmt.Sprintf("%#v", this.DataOffset)+",\n") + s = append(s, "DataSize: "+fmt.Sprintf("%#v", this.DataSize)+",\n") + if this.Statistics != nil { + s = append(s, "Statistics: "+fmt.Sprintf("%#v", this.Statistics)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringDatasetmd(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" @@ -290,6 +667,83 @@ func valueToGoStringDatasetmd(v interface{}, typ string) string { pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } +func (m *ColumnInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ColumnInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ColumnInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Statistics != nil { + { + size, err := m.Statistics.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintDatasetmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + if m.MetadataSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.MetadataSize)) + i-- + dAtA[i] = 0x40 + } + if m.MetadataOffset != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.MetadataOffset)) + i-- + dAtA[i] = 0x38 + } + if m.CompressedSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.CompressedSize)) + i-- + dAtA[i] = 0x30 + } + if m.UncompressedSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.UncompressedSize)) + i-- + dAtA[i] = 0x28 + } + if m.Compression != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.Compression)) + i-- + dAtA[i] = 0x20 + } + if m.RowsCount != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.RowsCount)) + i-- + dAtA[i] = 0x18 + } + if m.ValueType != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.ValueType)) + i-- + dAtA[i] = 0x10 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintDatasetmd(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + func (m *Statistics) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -327,6 +781,76 @@ func (m *Statistics) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *PageInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PageInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PageInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Statistics != nil { + { + size, err := m.Statistics.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintDatasetmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + if m.DataSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.DataSize)) + i-- + dAtA[i] = 0x38 + } + if m.DataOffset != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.DataOffset)) + i-- + dAtA[i] = 0x30 + } + if m.Encoding != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.Encoding)) + i-- + dAtA[i] = 0x28 + } + if m.RowsCount != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.RowsCount)) + i-- + dAtA[i] = 0x20 + } + if m.Crc32 != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.Crc32)) + i-- + dAtA[i] = 0x18 + } + if m.CompressedSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.CompressedSize)) + i-- + dAtA[i] = 0x10 + } + if m.UncompressedSize != 0 { + i = encodeVarintDatasetmd(dAtA, i, uint64(m.UncompressedSize)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintDatasetmd(dAtA []byte, offset int, v uint64) int { offset -= sovDatasetmd(v) base := offset @@ -338,6 +862,44 @@ func encodeVarintDatasetmd(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } +func (m *ColumnInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovDatasetmd(uint64(l)) + } + if m.ValueType != 0 { + n += 1 + sovDatasetmd(uint64(m.ValueType)) + } + if m.RowsCount != 0 { + n += 1 + sovDatasetmd(uint64(m.RowsCount)) + } + if m.Compression != 0 { + n += 1 + sovDatasetmd(uint64(m.Compression)) + } + if m.UncompressedSize != 0 { + n += 1 + sovDatasetmd(uint64(m.UncompressedSize)) + } + if m.CompressedSize != 0 { + n += 1 + sovDatasetmd(uint64(m.CompressedSize)) + } + if m.MetadataOffset != 0 { + n += 1 + sovDatasetmd(uint64(m.MetadataOffset)) + } + if m.MetadataSize != 0 { + n += 1 + sovDatasetmd(uint64(m.MetadataSize)) + } + if m.Statistics != nil { + l = m.Statistics.Size() + n += 1 + l + sovDatasetmd(uint64(l)) + } + return n +} + func (m *Statistics) Size() (n int) { if m == nil { return 0 @@ -355,12 +917,64 @@ func (m *Statistics) Size() (n int) { return n } +func (m *PageInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.UncompressedSize != 0 { + n += 1 + sovDatasetmd(uint64(m.UncompressedSize)) + } + if m.CompressedSize != 0 { + n += 1 + sovDatasetmd(uint64(m.CompressedSize)) + } + if m.Crc32 != 0 { + n += 1 + sovDatasetmd(uint64(m.Crc32)) + } + if m.RowsCount != 0 { + n += 1 + sovDatasetmd(uint64(m.RowsCount)) + } + if m.Encoding != 0 { + n += 1 + sovDatasetmd(uint64(m.Encoding)) + } + if m.DataOffset != 0 { + n += 1 + sovDatasetmd(uint64(m.DataOffset)) + } + if m.DataSize != 0 { + n += 1 + sovDatasetmd(uint64(m.DataSize)) + } + if m.Statistics != nil { + l = m.Statistics.Size() + n += 1 + l + sovDatasetmd(uint64(l)) + } + return n +} + func sovDatasetmd(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozDatasetmd(x uint64) (n int) { return sovDatasetmd(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *ColumnInfo) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ColumnInfo{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ValueType:` + fmt.Sprintf("%v", this.ValueType) + `,`, + `RowsCount:` + fmt.Sprintf("%v", this.RowsCount) + `,`, + `Compression:` + fmt.Sprintf("%v", this.Compression) + `,`, + `UncompressedSize:` + fmt.Sprintf("%v", this.UncompressedSize) + `,`, + `CompressedSize:` + fmt.Sprintf("%v", this.CompressedSize) + `,`, + `MetadataOffset:` + fmt.Sprintf("%v", this.MetadataOffset) + `,`, + `MetadataSize:` + fmt.Sprintf("%v", this.MetadataSize) + `,`, + `Statistics:` + strings.Replace(this.Statistics.String(), "Statistics", "Statistics", 1) + `,`, + `}`, + }, "") + return s +} func (this *Statistics) String() string { if this == nil { return "nil" @@ -372,6 +986,23 @@ func (this *Statistics) String() string { }, "") return s } +func (this *PageInfo) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PageInfo{`, + `UncompressedSize:` + fmt.Sprintf("%v", this.UncompressedSize) + `,`, + `CompressedSize:` + fmt.Sprintf("%v", this.CompressedSize) + `,`, + `Crc32:` + fmt.Sprintf("%v", this.Crc32) + `,`, + `RowsCount:` + fmt.Sprintf("%v", this.RowsCount) + `,`, + `Encoding:` + fmt.Sprintf("%v", this.Encoding) + `,`, + `DataOffset:` + fmt.Sprintf("%v", this.DataOffset) + `,`, + `DataSize:` + fmt.Sprintf("%v", this.DataSize) + `,`, + `Statistics:` + strings.Replace(this.Statistics.String(), "Statistics", "Statistics", 1) + `,`, + `}`, + }, "") + return s +} func valueToStringDatasetmd(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { @@ -380,7 +1011,7 @@ func valueToStringDatasetmd(v interface{}) string { pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } -func (m *Statistics) Unmarshal(dAtA []byte) error { +func (m *ColumnInfo) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -403,17 +1034,17 @@ func (m *Statistics) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Statistics: wiretype end group for non-group") + return fmt.Errorf("proto: ColumnInfo: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Statistics: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ColumnInfo: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinValue", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowDatasetmd @@ -423,31 +1054,29 @@ func (m *Statistics) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthDatasetmd } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthDatasetmd } if postIndex > l { return io.ErrUnexpectedEOF } - m.MinValue = append(m.MinValue[:0], dAtA[iNdEx:postIndex]...) - if m.MinValue == nil { - m.MinValue = []byte{} - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxValue", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValueType", wireType) } - var byteLen int + m.ValueType = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowDatasetmd @@ -457,24 +1086,502 @@ func (m *Statistics) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + m.ValueType |= ValueType(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { - return ErrInvalidLengthDatasetmd + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RowsCount", wireType) } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthDatasetmd + m.RowsCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RowsCount |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } } - if postIndex > l { - return io.ErrUnexpectedEOF + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Compression", wireType) } - m.MaxValue = append(m.MaxValue[:0], dAtA[iNdEx:postIndex]...) - if m.MaxValue == nil { - m.MaxValue = []byte{} + m.Compression = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Compression |= CompressionType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field UncompressedSize", wireType) + } + m.UncompressedSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.UncompressedSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CompressedSize", wireType) + } + m.CompressedSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CompressedSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MetadataOffset", wireType) + } + m.MetadataOffset = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MetadataOffset |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MetadataSize", wireType) + } + m.MetadataSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MetadataSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Statistics", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthDatasetmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthDatasetmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Statistics == nil { + m.Statistics = &Statistics{} + } + if err := m.Statistics.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipDatasetmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthDatasetmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthDatasetmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Statistics) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Statistics: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Statistics: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MinValue", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthDatasetmd + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthDatasetmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MinValue = append(m.MinValue[:0], dAtA[iNdEx:postIndex]...) + if m.MinValue == nil { + m.MinValue = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxValue", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthDatasetmd + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthDatasetmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MaxValue = append(m.MaxValue[:0], dAtA[iNdEx:postIndex]...) + if m.MaxValue == nil { + m.MaxValue = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipDatasetmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthDatasetmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthDatasetmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PageInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PageInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PageInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field UncompressedSize", wireType) + } + m.UncompressedSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.UncompressedSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CompressedSize", wireType) + } + m.CompressedSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CompressedSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Crc32", wireType) + } + m.Crc32 = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Crc32 |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RowsCount", wireType) + } + m.RowsCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RowsCount |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Encoding", wireType) + } + m.Encoding = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Encoding |= EncodingType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DataOffset", wireType) + } + m.DataOffset = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DataOffset |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DataSize", wireType) + } + m.DataSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DataSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Statistics", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowDatasetmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthDatasetmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthDatasetmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Statistics == nil { + m.Statistics = &Statistics{} + } + if err := m.Statistics.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } iNdEx = postIndex default: diff --git a/pkg/dataobj/internal/metadata/datasetmd/datasetmd.proto b/pkg/dataobj/internal/metadata/datasetmd/datasetmd.proto index e396f9a627f49..f6b827838eb03 100644 --- a/pkg/dataobj/internal/metadata/datasetmd/datasetmd.proto +++ b/pkg/dataobj/internal/metadata/datasetmd/datasetmd.proto @@ -5,6 +5,37 @@ package dataobj.metadata.dataset.v1; option go_package = "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/datasetmd"; +// ColumnInfo describes an individual column within a data set. +message ColumnInfo { + // Optional name of the column. + string name = 1; + + // Type of values stored within the column. + ValueType value_type = 2; + + // Total number of rows in the entire column. + uint32 rows_count = 3; + + // Compression type used for all pages. + CompressionType compression = 4; + + // Total uncompressed size of all pages in the column. + uint32 uncompressed_size = 5; + + // Total compressed size of all pages in the column. Compressed size may + // match uncompressed size if no compression is used. + uint32 compressed_size = 6; + + // Byte offset from the start of the data object to the column's metadata. + uint32 metadata_offset = 7; + + // Size of the column's metadata in bytes. + uint32 metadata_size = 8; + + // Statistics for the column. + Statistics statistics = 9; +} + // ValueType represents the valid types that values within a column can have. enum ValueType { // Invalid value type. @@ -20,24 +51,6 @@ enum ValueType { VALUE_TYPE_STRING = 3; } -// EncodingType represents the valid types that a sequence of values which a -// column can be encoded with. -enum EncodingType { - // Invalid encoding type. - ENCODING_TYPE_UNSPECIFIED = 0; - - // Plain encoding; data is stored as-is. - ENCODING_TYPE_PLAIN = 1; - - // Delta encoding. The first value within the page is stored as-is, and - // subsequent values are stored as the delta from the previous value. - ENCODING_TYPE_DELTA = 2; - - // Bitmap encoding. Bitmaps effiently store repeating sequences of unsigned - // integers using a combination of run-length encoding and bitpacking. - ENCODING_TYPE_BITMAP = 3; -} - // CompressionType represents the valid compression types that can be used for // compressing values in a page. enum CompressionType { @@ -63,3 +76,49 @@ message Statistics { // Maximum value. bytes max_value = 2; } + +// Page describes an individual page within a column. +message PageInfo { + // Uncompressed size of the page within the data object. + uint32 uncompressed_size = 1; + + // Compressed size of the page within the data object. Compression size + // will match uncompressed size if no compression is used. + uint32 compressed_size = 2; + + // CRC32 checksum of the page data. + uint32 crc32 = 3; + + // Number of rows in the page. + uint32 rows_count = 4; + + // Encoding type used for the page. + EncodingType encoding = 5; + + // Byte offset from the start of the data object to the page's data. + uint32 data_offset = 6; + + // Size of the page's data in bytes. + uint32 data_size = 7; + + // Optional statistics for the page. + Statistics statistics = 8; +} + +// EncodingType represents the valid types that a sequence of values which a +// column can be encoded with. +enum EncodingType { + // Invalid encoding type. + ENCODING_TYPE_UNSPECIFIED = 0; + + // Plain encoding; data is stored as-is. + ENCODING_TYPE_PLAIN = 1; + + // Delta encoding. The first value within the page is stored as-is, and + // subsequent values are stored as the delta from the previous value. + ENCODING_TYPE_DELTA = 2; + + // Bitmap encoding. Bitmaps effiently store repeating sequences of unsigned + // integers using a combination of run-length encoding and bitpacking. + ENCODING_TYPE_BITMAP = 3; +} diff --git a/pkg/dataobj/internal/metadata/filemd/filemd.pb.go b/pkg/dataobj/internal/metadata/filemd/filemd.pb.go new file mode 100644 index 0000000000000..b3b65c6563e8e --- /dev/null +++ b/pkg/dataobj/internal/metadata/filemd/filemd.pb.go @@ -0,0 +1,761 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pkg/dataobj/internal/metadata/filemd/filemd.proto + +package filemd + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" + reflect "reflect" + strconv "strconv" + strings "strings" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type SectionType int32 + +const ( + // SECTION_TYPE_UNSPECIFIED is an invalid section type. + SECTION_TYPE_UNSPECIFIED SectionType = 0 + // SECTION_TYPE_STREAMS is a section containing references to streams that + // exist within the data object. SECTION_TYPE_STREAMS does not contain any + // actual log data. + SECTION_TYPE_STREAMS SectionType = 1 +) + +var SectionType_name = map[int32]string{ + 0: "SECTION_TYPE_UNSPECIFIED", + 1: "SECTION_TYPE_STREAMS", +} + +var SectionType_value = map[string]int32{ + "SECTION_TYPE_UNSPECIFIED": 0, + "SECTION_TYPE_STREAMS": 1, +} + +func (SectionType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_be80f52d1e05bad9, []int{0} +} + +// Metadata for the overall data object. +type Metadata struct { + // Sections within the data object. + Sections []*SectionInfo `protobuf:"bytes,1,rep,name=sections,proto3" json:"sections,omitempty"` +} + +func (m *Metadata) Reset() { *m = Metadata{} } +func (*Metadata) ProtoMessage() {} +func (*Metadata) Descriptor() ([]byte, []int) { + return fileDescriptor_be80f52d1e05bad9, []int{0} +} +func (m *Metadata) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Metadata.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Metadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_Metadata.Merge(m, src) +} +func (m *Metadata) XXX_Size() int { + return m.Size() +} +func (m *Metadata) XXX_DiscardUnknown() { + xxx_messageInfo_Metadata.DiscardUnknown(m) +} + +var xxx_messageInfo_Metadata proto.InternalMessageInfo + +func (m *Metadata) GetSections() []*SectionInfo { + if m != nil { + return m.Sections + } + return nil +} + +// SectionInfo describes a section within the data object. +type SectionInfo struct { + // Type of the section within the data object. + Type SectionType `protobuf:"varint,1,opt,name=type,proto3,enum=dataobj.metadata.file.v1.SectionType" json:"type,omitempty"` + // Byte offset of the section's metadata from the start of the data object. + MetadataOffset uint32 `protobuf:"varint,2,opt,name=metadata_offset,json=metadataOffset,proto3" json:"metadata_offset,omitempty"` + // Size of the section's metadata in bytes. + MetadataSize uint32 `protobuf:"varint,3,opt,name=metadata_size,json=metadataSize,proto3" json:"metadata_size,omitempty"` +} + +func (m *SectionInfo) Reset() { *m = SectionInfo{} } +func (*SectionInfo) ProtoMessage() {} +func (*SectionInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_be80f52d1e05bad9, []int{1} +} +func (m *SectionInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SectionInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SectionInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SectionInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_SectionInfo.Merge(m, src) +} +func (m *SectionInfo) XXX_Size() int { + return m.Size() +} +func (m *SectionInfo) XXX_DiscardUnknown() { + xxx_messageInfo_SectionInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_SectionInfo proto.InternalMessageInfo + +func (m *SectionInfo) GetType() SectionType { + if m != nil { + return m.Type + } + return SECTION_TYPE_UNSPECIFIED +} + +func (m *SectionInfo) GetMetadataOffset() uint32 { + if m != nil { + return m.MetadataOffset + } + return 0 +} + +func (m *SectionInfo) GetMetadataSize() uint32 { + if m != nil { + return m.MetadataSize + } + return 0 +} + +func init() { + proto.RegisterEnum("dataobj.metadata.file.v1.SectionType", SectionType_name, SectionType_value) + proto.RegisterType((*Metadata)(nil), "dataobj.metadata.file.v1.Metadata") + proto.RegisterType((*SectionInfo)(nil), "dataobj.metadata.file.v1.SectionInfo") +} + +func init() { + proto.RegisterFile("pkg/dataobj/internal/metadata/filemd/filemd.proto", fileDescriptor_be80f52d1e05bad9) +} + +var fileDescriptor_be80f52d1e05bad9 = []byte{ + // 344 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2c, 0xc8, 0x4e, 0xd7, + 0x4f, 0x49, 0x2c, 0x49, 0xcc, 0x4f, 0xca, 0xd2, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, + 0xd1, 0xcf, 0x4d, 0x2d, 0x49, 0x04, 0x09, 0xea, 0xa7, 0x65, 0xe6, 0xa4, 0xe6, 0xa6, 0x40, 0x29, + 0xbd, 0x82, 0xa2, 0xfc, 0x92, 0x7c, 0x21, 0x09, 0xa8, 0x72, 0x3d, 0x98, 0x2a, 0x3d, 0x90, 0xb4, + 0x5e, 0x99, 0xa1, 0x92, 0x2f, 0x17, 0x87, 0x2f, 0x54, 0x4c, 0xc8, 0x91, 0x8b, 0xa3, 0x38, 0x35, + 0xb9, 0x24, 0x33, 0x3f, 0xaf, 0x58, 0x82, 0x51, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x55, 0x0f, 0x97, + 0x46, 0xbd, 0x60, 0x88, 0x4a, 0xcf, 0xbc, 0xb4, 0xfc, 0x20, 0xb8, 0x36, 0xa5, 0x69, 0x8c, 0x5c, + 0xdc, 0x48, 0x32, 0x42, 0x96, 0x5c, 0x2c, 0x25, 0x95, 0x05, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, + 0x7c, 0x44, 0x18, 0x17, 0x52, 0x59, 0x90, 0x1a, 0x04, 0xd6, 0x22, 0xa4, 0xce, 0xc5, 0x0f, 0x53, + 0x15, 0x9f, 0x9f, 0x96, 0x56, 0x9c, 0x5a, 0x22, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x1b, 0xc4, 0x07, + 0x13, 0xf6, 0x07, 0x8b, 0x0a, 0x29, 0x73, 0xf1, 0xc2, 0x15, 0x16, 0x67, 0x56, 0xa5, 0x4a, 0x30, + 0x83, 0x95, 0xf1, 0xc0, 0x04, 0x83, 0x33, 0xab, 0x52, 0xb5, 0x5c, 0xe1, 0xee, 0x02, 0x59, 0x21, + 0x24, 0xc3, 0x25, 0x11, 0xec, 0xea, 0x1c, 0xe2, 0xe9, 0xef, 0x17, 0x1f, 0x12, 0x19, 0xe0, 0x1a, + 0x1f, 0xea, 0x17, 0x1c, 0xe0, 0xea, 0xec, 0xe9, 0xe6, 0xe9, 0xea, 0x22, 0xc0, 0x20, 0x24, 0xc1, + 0x25, 0x82, 0x22, 0x1b, 0x1c, 0x12, 0xe4, 0xea, 0xe8, 0x1b, 0x2c, 0xc0, 0xe8, 0x54, 0x7a, 0xe1, + 0xa1, 0x1c, 0xc3, 0x8d, 0x87, 0x72, 0x0c, 0x1f, 0x1e, 0xca, 0x31, 0x36, 0x3c, 0x92, 0x63, 0x5c, + 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, + 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, + 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x3e, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, + 0x3f, 0x57, 0x3f, 0xbd, 0x28, 0x31, 0x2d, 0x31, 0x2f, 0x51, 0x3f, 0x27, 0x3f, 0x3b, 0x53, 0xbf, + 0xcc, 0x58, 0x9f, 0x98, 0xc8, 0x4c, 0x62, 0x03, 0x47, 0xa3, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, + 0xc3, 0x39, 0x5a, 0x9d, 0xfb, 0x01, 0x00, 0x00, +} + +func (x SectionType) String() string { + s, ok := SectionType_name[int32(x)] + if ok { + return s + } + return strconv.Itoa(int(x)) +} +func (this *Metadata) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Metadata) + if !ok { + that2, ok := that.(Metadata) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.Sections) != len(that1.Sections) { + return false + } + for i := range this.Sections { + if !this.Sections[i].Equal(that1.Sections[i]) { + return false + } + } + return true +} +func (this *SectionInfo) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*SectionInfo) + if !ok { + that2, ok := that.(SectionInfo) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Type != that1.Type { + return false + } + if this.MetadataOffset != that1.MetadataOffset { + return false + } + if this.MetadataSize != that1.MetadataSize { + return false + } + return true +} +func (this *Metadata) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 5) + s = append(s, "&filemd.Metadata{") + if this.Sections != nil { + s = append(s, "Sections: "+fmt.Sprintf("%#v", this.Sections)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *SectionInfo) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 7) + s = append(s, "&filemd.SectionInfo{") + s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") + s = append(s, "MetadataOffset: "+fmt.Sprintf("%#v", this.MetadataOffset)+",\n") + s = append(s, "MetadataSize: "+fmt.Sprintf("%#v", this.MetadataSize)+",\n") + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringFilemd(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func (m *Metadata) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Metadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Metadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Sections) > 0 { + for iNdEx := len(m.Sections) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Sections[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintFilemd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *SectionInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SectionInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SectionInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MetadataSize != 0 { + i = encodeVarintFilemd(dAtA, i, uint64(m.MetadataSize)) + i-- + dAtA[i] = 0x18 + } + if m.MetadataOffset != 0 { + i = encodeVarintFilemd(dAtA, i, uint64(m.MetadataOffset)) + i-- + dAtA[i] = 0x10 + } + if m.Type != 0 { + i = encodeVarintFilemd(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintFilemd(dAtA []byte, offset int, v uint64) int { + offset -= sovFilemd(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Metadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Sections) > 0 { + for _, e := range m.Sections { + l = e.Size() + n += 1 + l + sovFilemd(uint64(l)) + } + } + return n +} + +func (m *SectionInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Type != 0 { + n += 1 + sovFilemd(uint64(m.Type)) + } + if m.MetadataOffset != 0 { + n += 1 + sovFilemd(uint64(m.MetadataOffset)) + } + if m.MetadataSize != 0 { + n += 1 + sovFilemd(uint64(m.MetadataSize)) + } + return n +} + +func sovFilemd(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozFilemd(x uint64) (n int) { + return sovFilemd(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *Metadata) String() string { + if this == nil { + return "nil" + } + repeatedStringForSections := "[]*SectionInfo{" + for _, f := range this.Sections { + repeatedStringForSections += strings.Replace(f.String(), "SectionInfo", "SectionInfo", 1) + "," + } + repeatedStringForSections += "}" + s := strings.Join([]string{`&Metadata{`, + `Sections:` + repeatedStringForSections + `,`, + `}`, + }, "") + return s +} +func (this *SectionInfo) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SectionInfo{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `MetadataOffset:` + fmt.Sprintf("%v", this.MetadataOffset) + `,`, + `MetadataSize:` + fmt.Sprintf("%v", this.MetadataSize) + `,`, + `}`, + }, "") + return s +} +func valueToStringFilemd(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *Metadata) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Metadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Metadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sections", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthFilemd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthFilemd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sections = append(m.Sections, &SectionInfo{}) + if err := m.Sections[len(m.Sections)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipFilemd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthFilemd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthFilemd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SectionInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SectionInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SectionInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= SectionType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MetadataOffset", wireType) + } + m.MetadataOffset = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MetadataOffset |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MetadataSize", wireType) + } + m.MetadataSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFilemd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MetadataSize |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFilemd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthFilemd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthFilemd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipFilemd(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFilemd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFilemd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFilemd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthFilemd + } + iNdEx += length + if iNdEx < 0 { + return 0, ErrInvalidLengthFilemd + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFilemd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipFilemd(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + if iNdEx < 0 { + return 0, ErrInvalidLengthFilemd + } + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthFilemd = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowFilemd = fmt.Errorf("proto: integer overflow") +) diff --git a/pkg/dataobj/internal/metadata/filemd/filemd.proto b/pkg/dataobj/internal/metadata/filemd/filemd.proto new file mode 100644 index 0000000000000..e32159e30cfb9 --- /dev/null +++ b/pkg/dataobj/internal/metadata/filemd/filemd.proto @@ -0,0 +1,39 @@ +// filemd.proto holds file-level metadata for a data object. Data objects are +// split into multiple distinct "sections," each of which contains independent +// data related to storing logs. +// +// Each section has its own metadata; the file-level metadata points to the +// metadata of each section stored within the data object. +syntax = "proto3"; + +package dataobj.metadata.file.v1; + +option go_package = "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/filemd"; + +// Metadata for the overall data object. +message Metadata { + // Sections within the data object. + repeated SectionInfo sections = 1; +} + +// SectionInfo describes a section within the data object. +message SectionInfo { + // Type of the section within the data object. + SectionType type = 1; + + // Byte offset of the section's metadata from the start of the data object. + uint32 metadata_offset = 2; + + // Size of the section's metadata in bytes. + uint32 metadata_size = 3; +} + +enum SectionType { + // SECTION_TYPE_UNSPECIFIED is an invalid section type. + SECTION_TYPE_UNSPECIFIED = 0; + + // SECTION_TYPE_STREAMS is a section containing references to streams that + // exist within the data object. SECTION_TYPE_STREAMS does not contain any + // actual log data. + SECTION_TYPE_STREAMS = 1; +} diff --git a/pkg/dataobj/internal/metadata/streamsmd/streamsmd.pb.go b/pkg/dataobj/internal/metadata/streamsmd/streamsmd.pb.go new file mode 100644 index 0000000000000..0415d2e93ca0e --- /dev/null +++ b/pkg/dataobj/internal/metadata/streamsmd/streamsmd.pb.go @@ -0,0 +1,1242 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: pkg/dataobj/internal/metadata/streamsmd/streamsmd.proto + +package streamsmd + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/proto" + datasetmd "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/datasetmd" + io "io" + math "math" + math_bits "math/bits" + reflect "reflect" + strconv "strconv" + strings "strings" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// ColumnType represents the valid types that a stream's column can have. +type ColumnType int32 + +const ( + // Invalid column type. + COLUMN_TYPE_UNSPECIFIED ColumnType = 0 + // COLUMN_TYPE_STREAM_ID is a column containing the stream ID. Stream IDs are + // unique across the entire data object. + COLUMN_TYPE_STREAM_ID ColumnType = 1 + // COLUMN_TYPE_MIN_TIMESTAMP is a column containing the minimum timestamp of + // a stream. + COLUMN_TYPE_MIN_TIMESTAMP ColumnType = 2 + // COLUMN_TYPE_MAX_TIMESTAMP is a column containing the maximum timestamp of + // a stream. + COLUMN_TYPE_MAX_TIMESTAMP ColumnType = 3 + // COLUMN_TYPE_LABEL is a column containing a label. + COLUMN_TYPE_LABEL ColumnType = 4 + // COLUMN_TYPE_ROWS is a column indicating the number of rows for a stream. + COLUMN_TYPE_ROWS ColumnType = 5 +) + +var ColumnType_name = map[int32]string{ + 0: "COLUMN_TYPE_UNSPECIFIED", + 1: "COLUMN_TYPE_STREAM_ID", + 2: "COLUMN_TYPE_MIN_TIMESTAMP", + 3: "COLUMN_TYPE_MAX_TIMESTAMP", + 4: "COLUMN_TYPE_LABEL", + 5: "COLUMN_TYPE_ROWS", +} + +var ColumnType_value = map[string]int32{ + "COLUMN_TYPE_UNSPECIFIED": 0, + "COLUMN_TYPE_STREAM_ID": 1, + "COLUMN_TYPE_MIN_TIMESTAMP": 2, + "COLUMN_TYPE_MAX_TIMESTAMP": 3, + "COLUMN_TYPE_LABEL": 4, + "COLUMN_TYPE_ROWS": 5, +} + +func (ColumnType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_7b94842ca2f0bf8d, []int{0} +} + +// Metadata describes the metadata for the streams section. +type Metadata struct { + // Columns within the stream. + Columns []*ColumnDesc `protobuf:"bytes,1,rep,name=columns,proto3" json:"columns,omitempty"` +} + +func (m *Metadata) Reset() { *m = Metadata{} } +func (*Metadata) ProtoMessage() {} +func (*Metadata) Descriptor() ([]byte, []int) { + return fileDescriptor_7b94842ca2f0bf8d, []int{0} +} +func (m *Metadata) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Metadata.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Metadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_Metadata.Merge(m, src) +} +func (m *Metadata) XXX_Size() int { + return m.Size() +} +func (m *Metadata) XXX_DiscardUnknown() { + xxx_messageInfo_Metadata.DiscardUnknown(m) +} + +var xxx_messageInfo_Metadata proto.InternalMessageInfo + +func (m *Metadata) GetColumns() []*ColumnDesc { + if m != nil { + return m.Columns + } + return nil +} + +// ColumnDesc describes an individual column within the streams table. +type ColumnDesc struct { + // Information about the column. + Info *datasetmd.ColumnInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` + // Column type. + Type ColumnType `protobuf:"varint,2,opt,name=type,proto3,enum=dataobj.metadata.streams.v1.ColumnType" json:"type,omitempty"` +} + +func (m *ColumnDesc) Reset() { *m = ColumnDesc{} } +func (*ColumnDesc) ProtoMessage() {} +func (*ColumnDesc) Descriptor() ([]byte, []int) { + return fileDescriptor_7b94842ca2f0bf8d, []int{1} +} +func (m *ColumnDesc) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ColumnDesc) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ColumnDesc.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ColumnDesc) XXX_Merge(src proto.Message) { + xxx_messageInfo_ColumnDesc.Merge(m, src) +} +func (m *ColumnDesc) XXX_Size() int { + return m.Size() +} +func (m *ColumnDesc) XXX_DiscardUnknown() { + xxx_messageInfo_ColumnDesc.DiscardUnknown(m) +} + +var xxx_messageInfo_ColumnDesc proto.InternalMessageInfo + +func (m *ColumnDesc) GetInfo() *datasetmd.ColumnInfo { + if m != nil { + return m.Info + } + return nil +} + +func (m *ColumnDesc) GetType() ColumnType { + if m != nil { + return m.Type + } + return COLUMN_TYPE_UNSPECIFIED +} + +// ColumnMetadata describes the metadata for a column. +type ColumnMetadata struct { + // Pages within the column. + Pages []*PageDesc `protobuf:"bytes,1,rep,name=pages,proto3" json:"pages,omitempty"` +} + +func (m *ColumnMetadata) Reset() { *m = ColumnMetadata{} } +func (*ColumnMetadata) ProtoMessage() {} +func (*ColumnMetadata) Descriptor() ([]byte, []int) { + return fileDescriptor_7b94842ca2f0bf8d, []int{2} +} +func (m *ColumnMetadata) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ColumnMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ColumnMetadata.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ColumnMetadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_ColumnMetadata.Merge(m, src) +} +func (m *ColumnMetadata) XXX_Size() int { + return m.Size() +} +func (m *ColumnMetadata) XXX_DiscardUnknown() { + xxx_messageInfo_ColumnMetadata.DiscardUnknown(m) +} + +var xxx_messageInfo_ColumnMetadata proto.InternalMessageInfo + +func (m *ColumnMetadata) GetPages() []*PageDesc { + if m != nil { + return m.Pages + } + return nil +} + +// PageDesc describes an individual page within a column. +type PageDesc struct { + // Information about the page. + Info *datasetmd.PageInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` +} + +func (m *PageDesc) Reset() { *m = PageDesc{} } +func (*PageDesc) ProtoMessage() {} +func (*PageDesc) Descriptor() ([]byte, []int) { + return fileDescriptor_7b94842ca2f0bf8d, []int{3} +} +func (m *PageDesc) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PageDesc) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PageDesc.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PageDesc) XXX_Merge(src proto.Message) { + xxx_messageInfo_PageDesc.Merge(m, src) +} +func (m *PageDesc) XXX_Size() int { + return m.Size() +} +func (m *PageDesc) XXX_DiscardUnknown() { + xxx_messageInfo_PageDesc.DiscardUnknown(m) +} + +var xxx_messageInfo_PageDesc proto.InternalMessageInfo + +func (m *PageDesc) GetInfo() *datasetmd.PageInfo { + if m != nil { + return m.Info + } + return nil +} + +func init() { + proto.RegisterEnum("dataobj.metadata.streams.v1.ColumnType", ColumnType_name, ColumnType_value) + proto.RegisterType((*Metadata)(nil), "dataobj.metadata.streams.v1.Metadata") + proto.RegisterType((*ColumnDesc)(nil), "dataobj.metadata.streams.v1.ColumnDesc") + proto.RegisterType((*ColumnMetadata)(nil), "dataobj.metadata.streams.v1.ColumnMetadata") + proto.RegisterType((*PageDesc)(nil), "dataobj.metadata.streams.v1.PageDesc") +} + +func init() { + proto.RegisterFile("pkg/dataobj/internal/metadata/streamsmd/streamsmd.proto", fileDescriptor_7b94842ca2f0bf8d) +} + +var fileDescriptor_7b94842ca2f0bf8d = []byte{ + // 439 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0x3d, 0x6f, 0xd3, 0x40, + 0x18, 0xf6, 0xf5, 0x03, 0xaa, 0x43, 0xaa, 0xcc, 0x89, 0x8a, 0x94, 0x8a, 0x53, 0x14, 0xa9, 0xa2, + 0x62, 0xf0, 0x09, 0x3a, 0x20, 0xd4, 0xc9, 0x49, 0x8c, 0x64, 0x29, 0x97, 0x46, 0xb6, 0x2b, 0x3e, + 0x16, 0xeb, 0x92, 0x5c, 0x8c, 0x69, 0xec, 0xb3, 0xec, 0x6b, 0x45, 0x37, 0x26, 0x66, 0x7e, 0x06, + 0x1b, 0x7f, 0x83, 0x31, 0x63, 0x47, 0xe2, 0x2c, 0x8c, 0xfd, 0x09, 0xc8, 0x8e, 0x5d, 0x1b, 0x81, + 0xd2, 0x2c, 0xd6, 0xab, 0xe7, 0xcb, 0xef, 0x73, 0x7a, 0xe1, 0xab, 0xe8, 0xdc, 0x23, 0x63, 0x26, + 0x99, 0x18, 0x7e, 0x22, 0x7e, 0x28, 0x79, 0x1c, 0xb2, 0x29, 0x09, 0xb8, 0x64, 0x19, 0x48, 0x12, + 0x19, 0x73, 0x16, 0x24, 0xc1, 0xb8, 0x9a, 0xb4, 0x28, 0x16, 0x52, 0xa0, 0x83, 0xc2, 0xa4, 0x95, + 0x5a, 0xad, 0x50, 0x68, 0x97, 0x2f, 0x9e, 0xdc, 0x91, 0x9a, 0x7d, 0x12, 0x2e, 0x83, 0x71, 0x35, + 0x2d, 0x53, 0x5b, 0x14, 0xee, 0xd0, 0x42, 0x85, 0x74, 0x78, 0x7f, 0x24, 0xa6, 0x17, 0x41, 0x98, + 0x34, 0x40, 0x73, 0xf3, 0xe8, 0xc1, 0xcb, 0x67, 0xda, 0x8a, 0x7f, 0x6a, 0x9d, 0x5c, 0xdb, 0xe5, + 0xc9, 0xc8, 0x2a, 0x7d, 0xad, 0xaf, 0x00, 0xc2, 0x0a, 0x47, 0x27, 0x70, 0xcb, 0x0f, 0x27, 0xa2, + 0x01, 0x9a, 0xe0, 0xff, 0x71, 0xc5, 0x3a, 0x55, 0x9c, 0x19, 0x4e, 0x84, 0x95, 0x9b, 0x32, 0xb3, + 0xbc, 0x8a, 0x78, 0x63, 0xa3, 0x09, 0x8e, 0x76, 0xd7, 0xda, 0xc5, 0xb9, 0x8a, 0xb8, 0x95, 0x9b, + 0x5a, 0x14, 0xee, 0x2e, 0xb1, 0xdb, 0x76, 0x27, 0x70, 0x3b, 0x62, 0x1e, 0x2f, 0xbb, 0x1d, 0xae, + 0xcc, 0x1b, 0x30, 0x8f, 0xe7, 0xcd, 0x96, 0x9e, 0x96, 0x01, 0x77, 0x4a, 0x08, 0xbd, 0xfe, 0xab, + 0xd4, 0xe1, 0xca, 0x52, 0x99, 0xa9, 0xaa, 0xf4, 0xfc, 0xc7, 0xed, 0xf3, 0x64, 0xab, 0xa2, 0x03, + 0xf8, 0xb8, 0x73, 0xda, 0x3b, 0xa3, 0x7d, 0xd7, 0x79, 0x3f, 0x30, 0xdc, 0xb3, 0xbe, 0x3d, 0x30, + 0x3a, 0xe6, 0x1b, 0xd3, 0xe8, 0xaa, 0x0a, 0xda, 0x87, 0x7b, 0x75, 0xd2, 0x76, 0x2c, 0x43, 0xa7, + 0xae, 0xd9, 0x55, 0x01, 0x7a, 0x0a, 0xf7, 0xeb, 0x14, 0x35, 0xfb, 0xae, 0x63, 0x52, 0xc3, 0x76, + 0x74, 0x3a, 0x50, 0x37, 0xfe, 0xa1, 0xf5, 0x77, 0x35, 0x7a, 0x13, 0xed, 0xc1, 0x87, 0x75, 0xba, + 0xa7, 0xb7, 0x8d, 0x9e, 0xba, 0x85, 0x1e, 0x41, 0xb5, 0x0e, 0x5b, 0xa7, 0x6f, 0x6d, 0x75, 0xbb, + 0xfd, 0x79, 0x36, 0xc7, 0xca, 0xf5, 0x1c, 0x2b, 0x37, 0x73, 0x0c, 0xbe, 0xa4, 0x18, 0x7c, 0x4f, + 0x31, 0xf8, 0x99, 0x62, 0x30, 0x4b, 0x31, 0xf8, 0x95, 0x62, 0xf0, 0x3b, 0xc5, 0xca, 0x4d, 0x8a, + 0xc1, 0xb7, 0x05, 0x56, 0x66, 0x0b, 0xac, 0x5c, 0x2f, 0xb0, 0xf2, 0xa1, 0xed, 0xf9, 0xf2, 0xe3, + 0xc5, 0x50, 0x1b, 0x89, 0x80, 0x78, 0x31, 0x9b, 0xb0, 0x90, 0x91, 0xa9, 0x38, 0xf7, 0xc9, 0xe5, + 0x31, 0x59, 0xf3, 0xfe, 0x87, 0xf7, 0xf2, 0x03, 0x3d, 0xfe, 0x13, 0x00, 0x00, 0xff, 0xff, 0x66, + 0x7a, 0xe2, 0x3c, 0x31, 0x03, 0x00, 0x00, +} + +func (x ColumnType) String() string { + s, ok := ColumnType_name[int32(x)] + if ok { + return s + } + return strconv.Itoa(int(x)) +} +func (this *Metadata) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Metadata) + if !ok { + that2, ok := that.(Metadata) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.Columns) != len(that1.Columns) { + return false + } + for i := range this.Columns { + if !this.Columns[i].Equal(that1.Columns[i]) { + return false + } + } + return true +} +func (this *ColumnDesc) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ColumnDesc) + if !ok { + that2, ok := that.(ColumnDesc) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !this.Info.Equal(that1.Info) { + return false + } + if this.Type != that1.Type { + return false + } + return true +} +func (this *ColumnMetadata) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ColumnMetadata) + if !ok { + that2, ok := that.(ColumnMetadata) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.Pages) != len(that1.Pages) { + return false + } + for i := range this.Pages { + if !this.Pages[i].Equal(that1.Pages[i]) { + return false + } + } + return true +} +func (this *PageDesc) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PageDesc) + if !ok { + that2, ok := that.(PageDesc) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !this.Info.Equal(that1.Info) { + return false + } + return true +} +func (this *Metadata) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 5) + s = append(s, "&streamsmd.Metadata{") + if this.Columns != nil { + s = append(s, "Columns: "+fmt.Sprintf("%#v", this.Columns)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *ColumnDesc) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 6) + s = append(s, "&streamsmd.ColumnDesc{") + if this.Info != nil { + s = append(s, "Info: "+fmt.Sprintf("%#v", this.Info)+",\n") + } + s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") + s = append(s, "}") + return strings.Join(s, "") +} +func (this *ColumnMetadata) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 5) + s = append(s, "&streamsmd.ColumnMetadata{") + if this.Pages != nil { + s = append(s, "Pages: "+fmt.Sprintf("%#v", this.Pages)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *PageDesc) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 5) + s = append(s, "&streamsmd.PageDesc{") + if this.Info != nil { + s = append(s, "Info: "+fmt.Sprintf("%#v", this.Info)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringStreamsmd(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func (m *Metadata) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Metadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Metadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Columns) > 0 { + for iNdEx := len(m.Columns) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Columns[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintStreamsmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ColumnDesc) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ColumnDesc) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ColumnDesc) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Type != 0 { + i = encodeVarintStreamsmd(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x10 + } + if m.Info != nil { + { + size, err := m.Info.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintStreamsmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ColumnMetadata) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ColumnMetadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ColumnMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Pages) > 0 { + for iNdEx := len(m.Pages) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Pages[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintStreamsmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *PageDesc) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PageDesc) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PageDesc) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Info != nil { + { + size, err := m.Info.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintStreamsmd(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintStreamsmd(dAtA []byte, offset int, v uint64) int { + offset -= sovStreamsmd(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Metadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Columns) > 0 { + for _, e := range m.Columns { + l = e.Size() + n += 1 + l + sovStreamsmd(uint64(l)) + } + } + return n +} + +func (m *ColumnDesc) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Info != nil { + l = m.Info.Size() + n += 1 + l + sovStreamsmd(uint64(l)) + } + if m.Type != 0 { + n += 1 + sovStreamsmd(uint64(m.Type)) + } + return n +} + +func (m *ColumnMetadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Pages) > 0 { + for _, e := range m.Pages { + l = e.Size() + n += 1 + l + sovStreamsmd(uint64(l)) + } + } + return n +} + +func (m *PageDesc) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Info != nil { + l = m.Info.Size() + n += 1 + l + sovStreamsmd(uint64(l)) + } + return n +} + +func sovStreamsmd(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozStreamsmd(x uint64) (n int) { + return sovStreamsmd(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *Metadata) String() string { + if this == nil { + return "nil" + } + repeatedStringForColumns := "[]*ColumnDesc{" + for _, f := range this.Columns { + repeatedStringForColumns += strings.Replace(f.String(), "ColumnDesc", "ColumnDesc", 1) + "," + } + repeatedStringForColumns += "}" + s := strings.Join([]string{`&Metadata{`, + `Columns:` + repeatedStringForColumns + `,`, + `}`, + }, "") + return s +} +func (this *ColumnDesc) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ColumnDesc{`, + `Info:` + strings.Replace(fmt.Sprintf("%v", this.Info), "ColumnInfo", "datasetmd.ColumnInfo", 1) + `,`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `}`, + }, "") + return s +} +func (this *ColumnMetadata) String() string { + if this == nil { + return "nil" + } + repeatedStringForPages := "[]*PageDesc{" + for _, f := range this.Pages { + repeatedStringForPages += strings.Replace(f.String(), "PageDesc", "PageDesc", 1) + "," + } + repeatedStringForPages += "}" + s := strings.Join([]string{`&ColumnMetadata{`, + `Pages:` + repeatedStringForPages + `,`, + `}`, + }, "") + return s +} +func (this *PageDesc) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PageDesc{`, + `Info:` + strings.Replace(fmt.Sprintf("%v", this.Info), "PageInfo", "datasetmd.PageInfo", 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringStreamsmd(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *Metadata) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Metadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Metadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Columns", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthStreamsmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthStreamsmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Columns = append(m.Columns, &ColumnDesc{}) + if err := m.Columns[len(m.Columns)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipStreamsmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ColumnDesc) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ColumnDesc: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ColumnDesc: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthStreamsmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthStreamsmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Info == nil { + m.Info = &datasetmd.ColumnInfo{} + } + if err := m.Info.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= ColumnType(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipStreamsmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ColumnMetadata) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ColumnMetadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ColumnMetadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pages", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthStreamsmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthStreamsmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Pages = append(m.Pages, &PageDesc{}) + if err := m.Pages[len(m.Pages)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipStreamsmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PageDesc) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PageDesc: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PageDesc: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthStreamsmd + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthStreamsmd + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Info == nil { + m.Info = &datasetmd.PageInfo{} + } + if err := m.Info.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipStreamsmd(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthStreamsmd + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipStreamsmd(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthStreamsmd + } + iNdEx += length + if iNdEx < 0 { + return 0, ErrInvalidLengthStreamsmd + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowStreamsmd + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipStreamsmd(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + if iNdEx < 0 { + return 0, ErrInvalidLengthStreamsmd + } + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthStreamsmd = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowStreamsmd = fmt.Errorf("proto: integer overflow") +) diff --git a/pkg/dataobj/internal/metadata/streamsmd/streamsmd.proto b/pkg/dataobj/internal/metadata/streamsmd/streamsmd.proto new file mode 100644 index 0000000000000..5f58faa91aa33 --- /dev/null +++ b/pkg/dataobj/internal/metadata/streamsmd/streamsmd.proto @@ -0,0 +1,60 @@ +// streamsmd.proto holds metadata for the streams section of a data object. The +// streams section conains references to log streams within the data object. +syntax = "proto3"; + +package dataobj.metadata.streams.v1; + +import "pkg/dataobj/internal/metadata/datasetmd/datasetmd.proto"; + +option go_package = "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/streamsmd"; + +// Metadata describes the metadata for the streams section. +message Metadata { + // Columns within the stream. + repeated ColumnDesc columns = 1; +} + +// ColumnDesc describes an individual column within the streams table. +message ColumnDesc { + // Information about the column. + dataobj.metadata.dataset.v1.ColumnInfo info = 1; + + // Column type. + ColumnType type = 2; +} + +// ColumnType represents the valid types that a stream's column can have. +enum ColumnType { + // Invalid column type. + COLUMN_TYPE_UNSPECIFIED = 0; + + // COLUMN_TYPE_STREAM_ID is a column containing the stream ID. Stream IDs are + // unique across the entire data object. + COLUMN_TYPE_STREAM_ID = 1; + + // COLUMN_TYPE_MIN_TIMESTAMP is a column containing the minimum timestamp of + // a stream. + COLUMN_TYPE_MIN_TIMESTAMP = 2; + + // COLUMN_TYPE_MAX_TIMESTAMP is a column containing the maximum timestamp of + // a stream. + COLUMN_TYPE_MAX_TIMESTAMP = 3; + + // COLUMN_TYPE_LABEL is a column containing a label. + COLUMN_TYPE_LABEL = 4; + + // COLUMN_TYPE_ROWS is a column indicating the number of rows for a stream. + COLUMN_TYPE_ROWS = 5; +} + +// ColumnMetadata describes the metadata for a column. +message ColumnMetadata { + // Pages within the column. + repeated PageDesc pages = 1; +} + +// PageDesc describes an individual page within a column. +message PageDesc { + // Information about the page. + dataobj.metadata.dataset.v1.PageInfo info = 1; +}
chore
data object encoding and decoding (#15676)
e13e12b7587f2d0e74150b67abafc41746fe2c55
2024-07-02 19:13:51
J Stickler
docs: fix broken link and add alt text (#13322)
false
diff --git a/docs/sources/operations/storage/table-manager/_index.md b/docs/sources/operations/storage/table-manager/_index.md index 148d1fdf7043d..6016b6bb12b93 100644 --- a/docs/sources/operations/storage/table-manager/_index.md +++ b/docs/sources/operations/storage/table-manager/_index.md @@ -16,6 +16,7 @@ table - also called periodic table - contains the data for a specific time range. This design brings two main benefits: + 1. **Schema config changes**: each table is bounded to a schema config and version, so that changes can be introduced over the time and multiple schema configs can coexist @@ -37,7 +38,6 @@ The Table Manager supports the following backends: - **Chunk store** - Filesystem (primarily used for local environments) - Loki does support the following backends for both index and chunk storage, but they are deprecated and will be removed in a future release: - [Amazon DynamoDB](https://aws.amazon.com/dynamodb) @@ -52,7 +52,6 @@ For detailed information on configuring the Table Manager, refer to the [`table_manager`](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#table_manager) section in the Loki configuration document. - ## Tables and schema config A periodic table stores the index or chunk data relative to a specific period @@ -70,14 +69,13 @@ This allows to have multiple non-overlapping schema configs over the time, in order to perform schema version upgrades or change storage settings (including changing the storage type). -![periodic_tables](./table-manager-periodic-tables.png) +{{< figure alt="periodic tables" align="center" src="./table-manager-periodic-tables.png" >}} The write path hits the table where the log entry timestamp falls into (usually the last table, except short periods close to the end of a table and the beginning of the next one), while the read path hits the tables containing data for the query time range. - ### Schema config example For example, the following `schema_config` defines two configurations: the first @@ -107,7 +105,6 @@ schema_config: period: 168h ``` - ### Table creation The Table Manager creates new tables slightly ahead of their start period, in @@ -118,7 +115,6 @@ The `creation_grace_period` property - in the [`table_manager`](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#table_manager) configuration block - defines how long before a table should be created. - ## Retention The retention - managed by the Table Manager - is disabled by default, due to @@ -143,7 +139,7 @@ is deleted, the Table Manager keeps the last tables alive using this formula: number_of_tables_to_keep = floor(retention_period / table_period) + 1 ``` -![retention](./table-manager-retention.png) +{{< figure alt="retention" align="center" src="./table-manager-retention.png" >}} {{% admonition type="note" %}} It's important to note that - due to the internal implementation - the table @@ -155,16 +151,16 @@ For detailed information on configuring the retention, refer to the [Loki Storage Retention]({{< relref "../retention" >}}) documentation. - ## Active / inactive tables A table can be active or inactive. A table is considered **active** if the current time is within the range: + - Table start period - [`creation_grace_period`](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#table_manager) - Table end period + max chunk age (hardcoded to `12h`) -![active_vs_inactive_tables](./table-manager-active-vs-inactive-tables.png) +{{< figure alt="active_vs_inactive_tables" align="center" src="./table-manager-active-vs-inactive-tables.png" >}} Currently, the difference between an active and inactive table **only applies to the DynamoDB storage** settings: capacity mode (on-demand or provisioned), @@ -177,7 +173,6 @@ read/write capacity units and autoscaling. | Write capacity unit | `provisioned_write_throughput` | `inactive_write_throughput` | | Autoscaling | Enabled (if configured) | Always disabled | - ## DynamoDB Provisioning When configuring DynamoDB with the Table Manager, the default [on-demand @@ -201,7 +196,6 @@ ensure that the primary index key is set to `h` (string) and the sort key is set to `r` (binary). The "period" attribute in the configuration YAML should be set to `0`. - ## Table Manager deployment mode The Table Manager can be executed in two ways: @@ -209,13 +203,11 @@ The Table Manager can be executed in two ways: 1. Implicitly executed when Loki runs in monolithic mode (single process) 1. Explicitly executed when Loki runs in microservices mode - ### Monolithic mode When Loki runs in [monolithic mode]({{< relref "../../../get-started/deployment-modes" >}}), the Table Manager is also started as component of the entire stack. - ### Microservices mode When Loki runs in [microservices mode]({{< relref "../../../get-started/deployment-modes" >}}), diff --git a/docs/sources/send-data/promtail/cloud/ec2/_index.md b/docs/sources/send-data/promtail/cloud/ec2/_index.md index 8f90523018ee6..3c4dea7565400 100644 --- a/docs/sources/send-data/promtail/cloud/ec2/_index.md +++ b/docs/sources/send-data/promtail/cloud/ec2/_index.md @@ -49,7 +49,9 @@ aws ec2 authorize-security-group-ingress --group-id sg-02c489bbdeffdca1d --proto aws ec2 authorize-security-group-ingress --group-id sg-02c489bbdeffdca1d --protocol tcp --port 3100 --cidr 0.0.0.0/0 ``` -> You don't need to open those ports to all IPs as shown above you can use your own IP range. +{{< admonition type="note" >}} +You don't need to open those ports to all IPs as shown above you can use your own IP range. +{{< /admonition >}} We're going to create an [Amazon Linux 2][Amazon Linux 2] instance as this is one of the most popular but feel free to use the AMI of your choice. @@ -65,7 +67,9 @@ To make it more interesting later let's tag (`Name=promtail-demo`) our instance: aws ec2 create-tags --resources i-041b0be05c2d5cfad --tags Key=Name,Value=promtail-demo ``` -> Tags enable you to categorize your AWS resources in different ways, for example, by purpose, owner, or environment. This is useful when you have many resources of the same type—you can quickly identify a specific resource based on the tags that you've assigned to it. You'll see later, Promtail can transform those tags into [Loki labels][labels]. +{{< admonition type="note" >}} +Tags enable you to categorize your AWS resources in different ways, for example, by purpose, owner, or environment. This is useful when you have many resources of the same type—you can quickly identify a specific resource based on the tags that you've assigned to it. You'll see later, Promtail can transform those tags into [Loki labels][labels]. +{{< /admonition >}} Finally let's grab the public DNS of our instance: @@ -150,7 +154,7 @@ Finally the [`relabeling_configs`][relabel] section has three purposes: 2. Choosing where Promtail should find log files to tail, in our example we want to include all log files that exist in `/var/log` using the glob `/var/log/**.log`. If you need to use multiple glob, you can simply add another job in your `scrape_configs`. -3. Ensuring discovered targets are only for the machine Promtail currently runs on. This is achieved by adding the label `__host__` using the incoming metadata `__meta_ec2_private_dns_name`. If it doesn't match the current `HOSTNAME` environment variable, the target will be dropped. +3. Ensuring discovered targets are only for the machine Promtail currently runs on. This is achieved by adding the label `__host__` using the incoming metadata `__meta_ec2_private_dns_name`. If it doesn't match the current `HOSTNAME` environment variable, the target will be dropped. If `__meta_ec2_private_dns_name` doesn't match your instance's hostname (on EC2 Windows instance for example, where it is the IP address and not the hostname), you can hardcode the hostname at this stage, or check if any of the instances tag contain the hostname (`__meta_ec2_tag_<tagkey>: each tag value of the instance`) Alright we should be ready to fire up Promtail, we're going to run it using the flag `--dry-run`. This is perfect to ensure everything is correctly, specially when you're still playing around with the configuration. Don't worry when using this mode, Promtail won't send any logs and won't remember any file positions. @@ -175,7 +179,7 @@ open http://ec2-13-59-62-37.us-east-2.compute.amazonaws.com:3100/ For example the page below is the service discovery page. It shows you all discovered targets, with their respective available labels and the reason it was dropped if it was the case. -![discovery page page][discovery page] +{{< figure alt="Service discovery page" align="center" src="./promtail-ec2-discovery.png" >}} This page is really useful to understand what labels are available to forward with the `relabeling` configuration but also why Promtail is not scraping your target. @@ -232,7 +236,7 @@ Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal promtail-linux-amd64[ You can now verify in Grafana that Loki has correctly received your instance logs by using the [LogQL]({{< relref "../../../../query" >}}) query `{zone="us-east-2"}`. -![Grafana Loki logs][ec2 logs] +{{< figure alt="Grafana Loki logs" align="center" src="./promtail-ec2-logs.png" >}} ## Sending systemd logs @@ -255,7 +259,9 @@ We will edit our previous config (`vi ec2-promtail.yaml`) and add the following Note that you can use [relabeling][relabeling] to convert systemd labels to match what you want. Finally make sure that the path of journald logs is correct, it might be different on some systems. -> You can download the final config example from our [GitHub repository][final config]. +{{< admonition type="note" >}} +You can download the final config example from our [GitHub repository][final config]. +{{< /admonition >}} That's it, save the config and you can `reboot` the machine (or simply restart the service `systemctl restart promtail.service`). @@ -276,14 +282,11 @@ Let's head back to Grafana and verify that your Promtail logs are available in G [prometheus scrape config]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config [ec2_sd_config]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#ec2_sd_config [role]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html -[discovery page]: ./promtail-ec2-discovery.png "Service discovery" [relabel]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config [systemd]: https://www.freedesktop.org/software/systemd/man/systemd.service.html [logql]: ../../../query -[ec2 logs]: ./promtail-ec2-logs.png "Grafana Loki logs" [config gist]: https://gist.github.com/cyriltovena/d0881cc717757db951b642be48c01445 [labels]: https://grafana.com/blog/2020/04/21/how-labels-in-loki-can-make-log-queries-faster-and-easier/ -[troubleshooting loki]: ../../../getting-started/troubleshooting#troubleshooting-targets [live tailing]: https://grafana.com/docs/grafana/latest/features/datasources/loki/#live-tailing [systemd]: ../../../installation/helm#run-promtail-with-systemd-journal-support [journald]: https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html diff --git a/docs/sources/send-data/promtail/cloud/ecs/_index.md b/docs/sources/send-data/promtail/cloud/ecs/_index.md index 25ee8c64fe21a..1375efea1f16c 100644 --- a/docs/sources/send-data/promtail/cloud/ecs/_index.md +++ b/docs/sources/send-data/promtail/cloud/ecs/_index.md @@ -36,7 +36,9 @@ aws ecs create-cluster --cluster-name ecs-firelens-cluster We will also need an [IAM Role to run containers][ecs iam] with, let's create a new one and authorize [ECS][ECS] to endorse this role. -> You might already have this `ecsTaskExecutionRole` role in your AWS account if that's the case you can skip this step. +{{< admonition type="note" >}} +You might already have this `ecsTaskExecutionRole` role in your AWS account if that's the case you can skip this step. +{{< /admonition >}} ```bash curl https://raw.githubusercontent.com/grafana/loki/main/docs/sources/send-data/promtail/cloud/ecs/ecs-role.json > ecs-role.json @@ -81,7 +83,9 @@ Amazon [Firelens][Firelens] is a log router (usually `fluentd` or `fluentbit`) y In this example we will use [fluentbit][fluentbit] with the [fluentbit output plugin][fluentbit loki] installed but if you prefer [fluentd][fluentd] make sure to check the [fluentd output plugin][fluentd loki] documentation. -> We recommend you to use [fluentbit][fluentbit] as it's less resources consuming than [fluentd][fluentd]. +{{< admonition type="note" >}} +We recommend you to use [fluentbit][fluentbit] as it's less resources consuming than [fluentd][fluentd]. +{{< /admonition >}} Our [task definition][task] will be made of two containers, the [Firelens][Firelens] log router to send logs to Loki (`log_router`) and a sample application to generate log with (`sample-app`). @@ -117,7 +121,9 @@ curl https://raw.githubusercontent.com/grafana/loki/main/docs/sources/send-data/ The `log_router` container image is the [Fluent bit Loki docker image][fluentbit loki image] which contains the Loki plugin pre-installed. As you can see the `firelensConfiguration` type is set to `fluentbit` and we've also added `options` to enable ECS log metadata. This will be useful when querying your logs with Loki LogQL label matchers. -> The `logConfiguration` is mostly there for debugging the fluent-bit container, but feel free to remove that part when you're done testing and configuring. +{{< admonition type="note" >}} +The `logConfiguration` is mostly there for debugging the fluent-bit container, but feel free to remove that part when you're done testing and configuring. +{{< /admonition >}} ```json { @@ -169,7 +175,9 @@ All `options` of the `logConfiguration` will be automatically translated into [f This `OUTPUT` config will forward logs to [GrafanaCloud][GrafanaCloud] Loki, to learn more about those options make sure to read the [fluentbit output plugin][fluentbit loki] documentation. We've kept some interesting and useful labels such as `container_name`, `ecs_task_definition` , `source` and `ecs_cluster` but you can statically add more via the `Labels` option. -> If you want run multiple containers in your task, all of them needs a `logConfiguration` section, this give you the opportunity to add different labels depending on the container. +{{< admonition type="note" >}} +If you want run multiple containers in your task, all of them needs a `logConfiguration` section, this give you the opportunity to add different labels depending on the container. +{{< /admonition >}} ```json { @@ -187,7 +195,7 @@ We've kept some interesting and useful labels such as `container_name`, `ecs_tas } ``` -Finally, you need to replace the `executionRoleArn` with the [ARN][arn] of the role we created in the [first section](#Setting-up-the-ECS-cluster). +Finally, you need to replace the `executionRoleArn` with the [ARN][arn] of the role we created in the [first section](#setting-up-the-ecs-cluster). Once you've finished editing the task definition we can then run the command below to create the task: @@ -209,15 +217,17 @@ aws ecs create-service --cluster ecs-firelens-cluster \ --network-configuration "awsvpcConfiguration={subnets=[subnet-306ca97d],securityGroups=[sg-02c489bbdeffdca1d],assignPublicIp=ENABLED}" ``` -> Make sure public (`assignPublicIp`) is enabled otherwise ECS won't connect to the internet and you won't be able to pull external docker images. +{{< admonition type="note" >}} +Make sure public (`assignPublicIp`) is enabled otherwise ECS won't connect to the internet and you won't be able to pull external docker images. +{{< /admonition >}} You can now access the ECS console and you should see your task running. Now let's open Grafana and use explore with the Loki data source to explore our task logs. Enter the query `{job="firelens"}` and you should see our `sample-app` logs showing up as shown below: -![grafana logs firelens][grafana logs firelens] +{{< figure alt="grafana logs firelens" align="center" src="./ecs-grafana.png" >}} Using the `Log Labels` dropdown you should be able to discover your workload via the ECS metadata, which is also visible if you expand a log line. -That's it ! Make sure to checkout LogQL to learn more about Loki powerful query language. +That's it. Make sure to checkout [LogQL][logql] to learn more about Loki powerful query language. [create an vpc]: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-subnets-commands-example.html [ECS]: https://aws.amazon.com/ecs/ @@ -239,7 +249,4 @@ That's it ! Make sure to checkout LogQL to learn more about Loki powerful query [logql]: https://grafana.com/docs/loki/<LOKI_VERSION>/logql/ [alpine]:https://hub.docker.com/_/alpine [fluentbit output]: https://fluentbit.io/documentation/0.14/output/ -[routing]: https://fluentbit.io/documentation/0.13/getting_started/routing.html [grafanacloud account]: https://grafana.com/login -[grafana logs firelens]: ./ecs-grafana.png -[logql]: ../../../query diff --git a/docs/sources/send-data/promtail/configuration.md b/docs/sources/send-data/promtail/configuration.md index ab3e2da37fcb8..f7838cec74785 100644 --- a/docs/sources/send-data/promtail/configuration.md +++ b/docs/sources/send-data/promtail/configuration.md @@ -2,8 +2,6 @@ title: Configure Promtail menuTitle: Configuration reference description: Configuration parameters for the Promtail agent. -aliases: -- ../../clients/promtail/configuration/ weight: 200 --- diff --git a/docs/sources/send-data/promtail/logrotation/_index.md b/docs/sources/send-data/promtail/logrotation/_index.md index eb4eb6fa54215..24e93fbc2a8c4 100644 --- a/docs/sources/send-data/promtail/logrotation/_index.md +++ b/docs/sources/send-data/promtail/logrotation/_index.md @@ -12,15 +12,16 @@ weight: 500 ## Why does log rotation matter? At any point in time, there may be three processes working on a log file as shown in the image below. -![block_diagram](./logrotation-components.png) + +{{< figure alt="block diagram showing three processes" align="center" src="./logrotation-components.png" >}} 1. Appender - A writer that keeps appending to a log file. This can be your application or some system daemons like Syslog, Docker log driver or Kubelet, etc. 2. Tailer - A reader that reads log lines as they are appended, for example, agents like Promtail. 3. Log Rotator - A process that rotates the log file either based on time (for example, scheduled every day) or size (for example, a log file reached its maximum size). -{{% admonition type="note" %}} +{{< admonition type="note" >}} Here `fd` defines a file descriptor. Once a file is open for read or write, The Operating System returns a unique file descriptor (usually an integer) per process, and all the operations like read and write are done over that file descriptor. In other words, once the file is opened successfully, the file descriptor matters more than the file name. -{{% /admonition %}} +{{< /admonition >}} One of the critical components here is the log rotator. Let's understand how it impacts other components like the appender and tailer. @@ -36,10 +37,12 @@ In both cases, after log rotation, all new log lines are written to the original These two methods of log rotation are shown in the following images. ### Copy and Truncate -![block_diagram](./logrotation-copy-and-truncate.png) + +{{< figure alt="Copy and truncate log rotation" align="center" src="./logrotation-copy-and-truncate.png" >}} ### Rename and Create -![block_diagram](./logrotation-rename-and-create.png) + +{{< figure alt="Rename and create log rotation" align="center" src="./logrotation-rename-and-create.png" >}} Both types of log rotation produce the same result. However, there are some subtle differences. @@ -66,6 +69,7 @@ It has a wide range of [options](https://man7.org/linux/man-pages/man8/logrotate It supports both methods of log rotation described previously. #### Copy and Truncate + ``` /var/log/apache2/*.log { weekly @@ -77,6 +81,7 @@ It supports both methods of log rotation described previously. Here `copytruncate` mode works exactly like (1) explained above. #### Rename and Create **(Recommend)** + ``` /var/log/apache2/*.log { weekly @@ -84,8 +89,8 @@ Here `copytruncate` mode works exactly like (1) explained above. create } ``` -Here, the `create` mode works as explained in (2) above. The `create` mode is optional because it's the default mode in `logrotate`. +Here, the `create` mode works as explained in (2) above. The `create` mode is optional because it's the default mode in `logrotate`. ### Kubernetes @@ -98,13 +103,14 @@ You can [configure](https://kubernetes.io/docs/concepts/cluster-administration/l Both should be part of the `kubelet` config. If you run a managed version of Kubernetes in Cloud, refer to your cloud provider documentation for configuring `kubelet`. Examples [GKE](https://cloud.google.com/kubernetes-engine/docs/how-to/node-system-config#create), [AKS](https://learn.microsoft.com/en-us/azure/aks/custom-node-configuration#use-custom-node-configuration) and [EKS](https://eksctl.io/usage/customizing-the-kubelet/#customizing-kubelet-configuration). -{{% admonition type="note" %}} +{{< admonition type="note" >}} Log rotation managed by `kubelet` supports only rename + create and doesn't support copy + truncate. -{{% /admonition %}} +{{< /admonition >}} If `kubelet` is not configured to manage the log rotation, then it's up to the Container Runtime Interface (CRI) the cluster uses. Alternatively, log rotation can be managed by the `logrotate` utility in the Kubernetes node itself. Check your container runtime (CRI) on your nodes by running: + ```bash $ kubectl get nodes -o wide ``` @@ -120,6 +126,7 @@ At the time of writing this guide, `containerd` [doesn't support any method of l When using `docker` as runtime (EKS before 1.24 uses it by default), log rotation is managed by its logging driver (if supported). Docker has [support for several logging drivers](https://docs.docker.com/config/containers/logging/configure/#supported-logging-drivers). You can determine which logging driver `docker` is using by running the following command: + ```bash docker info --format '{{.LoggingDriver}}' ``` @@ -130,6 +137,7 @@ Out of all these logging drivers only the `local` (default) and the `json-file` 2. `max-file` - The maximum number of log files that can be present. If rolling the logs creates excess files, the oldest file is removed. A positive integer. Defaults to 5. Example `/etc/docker/daemon.json`: + ```json { "log-driver": "local", @@ -142,9 +150,9 @@ Example `/etc/docker/daemon.json`: If neither `kubelet` nor `CRI` is configured for rotating logs, then the `logrotate` utility can be used on the Kubernetes nodes as explained previously. -{{% admonition type="note" %}} +{{< admonition type="note" >}} We recommend using kubelet for log rotation. -{{% /admonition %}} +{{< /admonition >}} ## Configure Promtail
docs
fix broken link and add alt text (#13322)
0075085e9a7f659d44ddb99de6d1d64806ddf4b3
2022-05-21 01:40:56
Gábor Farkas
docs: describe ordering in http query results (#6024)
false
diff --git a/docs/sources/api/_index.md b/docs/sources/api/_index.md index abd5ee03767f0..1515def55f3a4 100644 --- a/docs/sources/api/_index.md +++ b/docs/sources/api/_index.md @@ -155,6 +155,10 @@ And `<stream value>` is: } ``` +The items in the `values` array are sorted by timestamp. +The most recent item is first when using `direction=backward`. +The oldest item is first when using `direction=forward`. + See [statistics](#statistics) for information about the statistics returned by Loki. ### Examples @@ -277,12 +281,17 @@ Where `<matrix value>` is: <label key-value pairs> }, "values": [ - <number: second unix epoch>, - <string: value> + [ + <number: second unix epoch>, + <string: value> + ], + ... ] } ``` +The items in the `values` array are sorted by timestamp, and the oldest item is first. + And `<stream value>` is: ``` @@ -300,6 +309,10 @@ And `<stream value>` is: } ``` +The items in the `values` array are sorted by timestamp. +The most recent item is first when using `direction=backward`. +The oldest item is first when using `direction=forward`. + See [statistics](#statistics) for information about the statistics returned by Loki. ### Examples
docs
describe ordering in http query results (#6024)
21b901db9ba99960fef4c288eb5dceec7b56da42
2021-04-03 17:04:52
Ed Welch
loki: Distributor log message bodySize should always reflect the compressed size (#3572)
false
diff --git a/pkg/distributor/http.go b/pkg/distributor/http.go index 8928ca066bad6..9248ffe5fa70e 100644 --- a/pkg/distributor/http.go +++ b/pkg/distributor/http.go @@ -3,6 +3,7 @@ package distributor import ( "compress/gzip" "fmt" + "io" "math" "net/http" "strings" @@ -107,24 +108,26 @@ func (d *Distributor) PushHandler(w http.ResponseWriter, r *http.Request) { func ParseRequest(logger gokit.Logger, userID string, r *http.Request) (*logproto.PushRequest, error) { - var body lokiutil.SizeReader - + // Body + var body io.Reader + // bodySize should always reflect the compressed size of the request body + bodySize := lokiutil.NewSizeReader(r.Body) contentEncoding := r.Header.Get(contentEnc) switch contentEncoding { case "": - body = lokiutil.NewSizeReader(r.Body) + body = bodySize case "snappy": // Snappy-decoding is done by `util.ParseProtoReader(..., util.RawSnappy)` below. // Pass on body bytes. Note: HTTP clients do not need to set this header, // but they sometimes do. See #3407. - body = lokiutil.NewSizeReader(r.Body) + body = bodySize case "gzip": - gzipReader, err := gzip.NewReader(r.Body) + gzipReader, err := gzip.NewReader(bodySize) if err != nil { return nil, err } defer gzipReader.Close() - body = lokiutil.NewSizeReader(gzipReader) + body = gzipReader default: return nil, fmt.Errorf("Content-Encoding %q not supported", contentEncoding) } @@ -163,7 +166,7 @@ func ParseRequest(logger gokit.Logger, userID string, r *http.Request) (*logprot "path", r.URL.Path, "contentType", contentType, "contentEncoding", contentEncoding, - "bodySize", humanize.Bytes(uint64(body.Size())), + "bodySize", humanize.Bytes(uint64(bodySize.Size())), "streams", len(req.Streams), "entries", totalEntries, "streamLabelsSize", humanize.Bytes(uint64(streamLabelsSize)),
loki
Distributor log message bodySize should always reflect the compressed size (#3572)
c708ae691ca2d9a26b1c2a4591ed32dbfdd94619
2024-09-30 17:19:00
Dylan Guedes
feat(helm): Allow setting node attributes to `tokengen` and `provisioner` (#14311)
false
diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 9add6158f3a6a..4185c5eb31ebf 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -3039,6 +3039,7 @@ null }, "provisioner": { "additionalTenants": [], + "affinity": {}, "annotations": {}, "enabled": true, "env": [], @@ -3051,6 +3052,7 @@ null "tag": null }, "labels": {}, + "nodeSelector": {}, "priorityClassName": null, "provisionedSecretPrefix": null, "securityContext": { @@ -3058,9 +3060,11 @@ null "runAsGroup": 10001, "runAsNonRoot": true, "runAsUser": 10001 - } + }, + "tolerations": [] }, "tokengen": { + "affinity": {}, "annotations": {}, "enabled": true, "env": [], @@ -3069,6 +3073,7 @@ null "extraVolumeMounts": [], "extraVolumes": [], "labels": {}, + "nodeSelector": {}, "priorityClassName": "", "securityContext": { "fsGroup": 10001, @@ -3222,6 +3227,7 @@ null <td><pre lang="json"> { "additionalTenants": [], + "affinity": {}, "annotations": {}, "enabled": true, "env": [], @@ -3234,6 +3240,7 @@ null "tag": null }, "labels": {}, + "nodeSelector": {}, "priorityClassName": null, "provisionedSecretPrefix": null, "securityContext": { @@ -3241,7 +3248,8 @@ null "runAsGroup": 10001, "runAsNonRoot": true, "runAsUser": 10001 - } + }, + "tolerations": [] } </pre> </td> @@ -3253,6 +3261,15 @@ null <td><pre lang="json"> [] </pre> +</td> + </tr> + <tr> + <td>enterprise.provisioner.affinity</td> + <td>object</td> + <td>Affinity for tokengen Pods</td> + <td><pre lang="json"> +{} +</pre> </td> </tr> <tr> @@ -3358,6 +3375,15 @@ null <td><pre lang="json"> {} </pre> +</td> + </tr> + <tr> + <td>enterprise.provisioner.nodeSelector</td> + <td>object</td> + <td>Node selector for tokengen Pods</td> + <td><pre lang="json"> +{} +</pre> </td> </tr> <tr> @@ -3390,6 +3416,15 @@ null "runAsUser": 10001 } </pre> +</td> + </tr> + <tr> + <td>enterprise.provisioner.tolerations</td> + <td>list</td> + <td>Tolerations for tokengen Pods</td> + <td><pre lang="json"> +[] +</pre> </td> </tr> <tr> @@ -3398,6 +3433,7 @@ null <td>Configuration for `tokengen` target</td> <td><pre lang="json"> { + "affinity": {}, "annotations": {}, "enabled": true, "env": [], @@ -3406,6 +3442,7 @@ null "extraVolumeMounts": [], "extraVolumes": [], "labels": {}, + "nodeSelector": {}, "priorityClassName": "", "securityContext": { "fsGroup": 10001, @@ -3417,6 +3454,15 @@ null "tolerations": [] } </pre> +</td> + </tr> + <tr> + <td>enterprise.tokengen.affinity</td> + <td>object</td> + <td>Affinity for tokengen Pods</td> + <td><pre lang="json"> +{} +</pre> </td> </tr> <tr> @@ -3489,6 +3535,15 @@ true <td><pre lang="json"> {} </pre> +</td> + </tr> + <tr> + <td>enterprise.tokengen.nodeSelector</td> + <td>object</td> + <td>Node selector for tokengen Pods</td> + <td><pre lang="json"> +{} +</pre> </td> </tr> <tr> diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index 519755dbec944..2f1ee3541c716 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -13,9 +13,14 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) +## 6.16.0 + +- [ENHANCEMENT] Allow setting nodeSelector, tolerations and affinity to enterprise components (tokengen and provisioner). + ## 6.15.0 - [ENHANCEMENT] Allow setting annotations for memberlist and query-scheduler-discovery services + ## 6.14.1 - [BUGFIX] Fixed Memcached persistence options. diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 56e48a535e070..69baa3b24ea06 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -3,7 +3,7 @@ name: loki description: Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. type: application appVersion: 3.1.1 -version: 6.15.0 +version: 6.16.0 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index 92008e768d6bc..235c31643d103 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.15.0](https://img.shields.io/badge/Version-6.15.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.1.1](https://img.shields.io/badge/AppVersion-3.1.1-informational?style=flat-square) +![Version: 6.16.0](https://img.shields.io/badge/Version-6.16.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.1.1](https://img.shields.io/badge/AppVersion-3.1.1-informational?style=flat-square) Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. diff --git a/production/helm/loki/templates/provisioner/job-provisioner.yaml b/production/helm/loki/templates/provisioner/job-provisioner.yaml index 61fd2be8501ba..5a6bc063715f4 100644 --- a/production/helm/loki/templates/provisioner/job-provisioner.yaml +++ b/production/helm/loki/templates/provisioner/job-provisioner.yaml @@ -123,6 +123,18 @@ spec: {{- end }} - name: bootstrap mountPath: /bootstrap + {{- with .Values.enterprise.provisioner.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.enterprise.provisioner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.enterprise.provisioner.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} restartPolicy: OnFailure serviceAccount: {{ include "enterprise-logs.provisionerFullname" . }} serviceAccountName: {{ include "enterprise-logs.provisionerFullname" . }} diff --git a/production/helm/loki/templates/tokengen/job-tokengen.yaml b/production/helm/loki/templates/tokengen/job-tokengen.yaml index f9ae7374c2d17..b0950d6f19675 100644 --- a/production/helm/loki/templates/tokengen/job-tokengen.yaml +++ b/production/helm/loki/templates/tokengen/job-tokengen.yaml @@ -110,6 +110,14 @@ spec: restartPolicy: OnFailure serviceAccount: {{ template "enterprise-logs.tokengenFullname" . }} serviceAccountName: {{ template "enterprise-logs.tokengenFullname" . }} + {{- with .Values.enterprise.tokengen.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.enterprise.tokengen.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} {{- with .Values.enterprise.tokengen.tolerations }} tolerations: {{- toYaml . | nindent 8 }} diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index a3ee28a805338..3f44de3b3724f 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -540,6 +540,10 @@ enterprise: labels: {} # -- Additional annotations for the `tokengen` Job annotations: {} + # -- Affinity for tokengen Pods + affinity: {} + # -- Node selector for tokengen Pods + nodeSelector: {} # -- Tolerations for tokengen Job tolerations: [] # -- Additional volumes for Pods @@ -575,6 +579,12 @@ enterprise: labels: {} # -- Additional annotations for the `provisioner` Job annotations: {} + # -- Affinity for tokengen Pods + affinity: {} + # -- Node selector for tokengen Pods + nodeSelector: {} + # -- Tolerations for tokengen Pods + tolerations: [] # -- The name of the PriorityClass for provisioner Job priorityClassName: null # -- Run containers as user `enterprise-logs(uid=10001)`
feat
Allow setting node attributes to `tokengen` and `provisioner` (#14311)
dbc0e2489cb7d88f04155f4087e6e40a7dc92ff3
2024-06-21 12:52:05
Christian Haudum
chore(index-gateway): Improve instrumentation of index download/sync (#13194)
false
diff --git a/pkg/storage/stores/shipper/indexshipper/downloads/index_set.go b/pkg/storage/stores/shipper/indexshipper/downloads/index_set.go index 1be495ed46d99..8eae835b441c3 100644 --- a/pkg/storage/stores/shipper/indexshipper/downloads/index_set.go +++ b/pkg/storage/stores/shipper/indexshipper/downloads/index_set.go @@ -41,7 +41,7 @@ type IndexSet interface { LastUsedAt() time.Time UpdateLastUsedAt() Sync(ctx context.Context) (err error) - AwaitReady(ctx context.Context) error + AwaitReady(ctx context.Context, reason string) error } // indexSet is a collection of multiple files created for a same table by various ingesters. @@ -62,8 +62,7 @@ type indexSet struct { cancelFunc context.CancelFunc // helps with cancellation of initialization if we are asked to stop. } -func NewIndexSet(tableName, userID, cacheLocation string, baseIndexSet storage.IndexSet, openIndexFileFunc index.OpenIndexFileFunc, - logger log.Logger) (IndexSet, error) { +func NewIndexSet(tableName, userID, cacheLocation string, baseIndexSet storage.IndexSet, openIndexFileFunc index.OpenIndexFileFunc, logger log.Logger) (IndexSet, error) { if baseIndexSet.IsUserBasedIndexSet() && userID == "" { return nil, fmt.Errorf("userID must not be empty") } else if !baseIndexSet.IsUserBasedIndexSet() && userID != "" { @@ -75,10 +74,7 @@ func NewIndexSet(tableName, userID, cacheLocation string, baseIndexSet storage.I return nil, err } - maxConcurrent := runtime.GOMAXPROCS(0) / 2 - if maxConcurrent == 0 { - maxConcurrent = 1 - } + maxConcurrent := max(runtime.GOMAXPROCS(0)/2, 1) is := indexSet{ openIndexFileFunc: openIndexFileFunc, @@ -101,25 +97,25 @@ func NewIndexSet(tableName, userID, cacheLocation string, baseIndexSet storage.I func (t *indexSet) Init(forQuerying bool) (err error) { // Using background context to avoid cancellation of download when request times out. // We would anyways need the files for serving next requests. - ctx, cancelFunc := context.WithTimeout(context.Background(), downloadTimeout) - t.cancelFunc = cancelFunc + ctx := context.Background() + ctx, t.cancelFunc = context.WithTimeout(ctx, downloadTimeout) - logger := spanlogger.FromContextWithFallback(ctx, t.logger) + logger, ctx := spanlogger.NewWithLogger(ctx, t.logger, "indexSet.Init") defer func() { if err != nil { - level.Error(t.logger).Log("msg", fmt.Sprintf("failed to initialize table %s, cleaning it up", t.tableName), "err", err) + level.Error(logger).Log("msg", "failed to initialize table, cleaning it up", "table", t.tableName, "err", err) t.err = err // cleaning up files due to error to avoid returning invalid results. for fileName := range t.index { if err := t.cleanupDB(fileName); err != nil { - level.Error(t.logger).Log("msg", "failed to cleanup partially downloaded file", "filename", fileName, "err", err) + level.Error(logger).Log("msg", "failed to cleanup partially downloaded file", "filename", fileName, "err", err) } } } - t.cancelFunc() t.indexMtx.markReady() + t.cancelFunc() }() dirEntries, err := os.ReadDir(t.cacheLocation) @@ -137,12 +133,12 @@ func (t *indexSet) Init(forQuerying bool) (err error) { // if we fail to open an index file, lets skip it and let sync operation re-download the file from storage. idx, err := t.openIndexFileFunc(fullPath) if err != nil { - level.Error(t.logger).Log("msg", fmt.Sprintf("failed to open existing index file %s, removing the file and continuing without it to let the sync operation catch up", fullPath), "err", err) + level.Error(logger).Log("msg", fmt.Sprintf("failed to open existing index file %s, removing the file and continuing without it to let the sync operation catch up", fullPath), "err", err) // Sometimes files get corrupted when the process gets killed in the middle of a download operation which can cause problems in reading the file. // Implementation of openIndexFileFunc should take care of gracefully handling corrupted files. // Let us just remove the file and let the sync operation re-download it. if err := os.Remove(fullPath); err != nil { - level.Error(t.logger).Log("msg", fmt.Sprintf("failed to remove index file %s which failed to open", fullPath)) + level.Error(logger).Log("msg", fmt.Sprintf("failed to remove index file %s which failed to open", fullPath)) } continue } @@ -406,8 +402,18 @@ func (t *indexSet) checkStorageForUpdates(ctx context.Context, lock, bypassListC return } -func (t *indexSet) AwaitReady(ctx context.Context) error { - return t.indexMtx.awaitReady(ctx) +func (t *indexSet) AwaitReady(ctx context.Context, reason string) error { + start := time.Now() + err := t.indexMtx.awaitReady(ctx) + level.Info(t.logger).Log( + "msg", "waited for index set to become ready", + "reason", reason, + "table", t.tableName, + "user", t.userID, + "wait_time", time.Since(start), + "err", err, + ) + return err } func (t *indexSet) downloadFileFromStorage(ctx context.Context, fileName, folderPathForTable string) (string, error) { diff --git a/pkg/storage/stores/shipper/indexshipper/downloads/metrics.go b/pkg/storage/stores/shipper/indexshipper/downloads/metrics.go index d037af15f654d..4a9894368dd73 100644 --- a/pkg/storage/stores/shipper/indexshipper/downloads/metrics.go +++ b/pkg/storage/stores/shipper/indexshipper/downloads/metrics.go @@ -14,6 +14,10 @@ type metrics struct { queryTimeTableDownloadDurationSeconds *prometheus.CounterVec tablesSyncOperationTotal *prometheus.CounterVec tablesDownloadOperationDurationSeconds prometheus.Gauge + + // new metrics that will supersed the incorrect old types + queryWaitTime *prometheus.HistogramVec + tableSyncLatency *prometheus.HistogramVec } func newMetrics(r prometheus.Registerer) *metrics { @@ -30,6 +34,15 @@ func newMetrics(r prometheus.Registerer) *metrics { Name: "tables_download_operation_duration_seconds", Help: "Time (in seconds) spent in downloading updated files for all the tables", }), + + queryWaitTime: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ + Name: "query_wait_time_seconds", + Help: "Time (in seconds) spent waiting for index files to be queryable at query time", + }, []string{"table"}), + tableSyncLatency: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ + Name: "table_sync_latency_seconds", + Help: "Time (in seconds) spent in downloading updated files for all the tables", + }, []string{"table", "status"}), } return m diff --git a/pkg/storage/stores/shipper/indexshipper/downloads/table.go b/pkg/storage/stores/shipper/indexshipper/downloads/table.go index 4767861300594..f329c3b41dcd8 100644 --- a/pkg/storage/stores/shipper/indexshipper/downloads/table.go +++ b/pkg/storage/stores/shipper/indexshipper/downloads/table.go @@ -24,7 +24,7 @@ import ( // timeout for downloading initial files for a table to avoid leaking resources by allowing it to take all the time. const ( - downloadTimeout = 5 * time.Minute + downloadTimeout = 1 * time.Minute maxDownloadConcurrency = 50 ) @@ -57,12 +57,8 @@ type table struct { // NewTable just creates an instance of table without trying to load files from local storage or object store. // It is used for initializing table at query time. func NewTable(name, cacheLocation string, storageClient storage.Client, openIndexFileFunc index.OpenIndexFileFunc, metrics *metrics) Table { - maxConcurrent := runtime.GOMAXPROCS(0) / 2 - if maxConcurrent == 0 { - maxConcurrent = 1 - } - - table := table{ + maxConcurrent := max(runtime.GOMAXPROCS(0)/2, 1) + return &table{ name: name, cacheLocation: cacheLocation, storageClient: storageClient, @@ -74,8 +70,6 @@ func NewTable(name, cacheLocation string, storageClient storage.Client, openInde maxConcurrent: maxConcurrent, indexSets: map[string]IndexSet{}, } - - return &table } // LoadTable loads a table from local storage(syncs the table too if we have it locally) or downloads it from the shared store. @@ -91,10 +85,7 @@ func LoadTable(name, cacheLocation string, storageClient storage.Client, openInd return nil, err } - maxConcurrent := runtime.GOMAXPROCS(0) / 2 - if maxConcurrent == 0 { - maxConcurrent = 1 - } + maxConcurrent := max(runtime.GOMAXPROCS(0)/2, 1) table := table{ name: name, @@ -296,6 +287,8 @@ func (t *table) Sync(ctx context.Context) error { // forQuerying must be set to true only getting the index for querying since // it captures the amount of time it takes to download the index at query time. func (t *table) getOrCreateIndexSet(ctx context.Context, id string, forQuerying bool) (IndexSet, error) { + logger := spanlogger.FromContextWithFallback(ctx, log.With(t.logger, "user", id, "table", t.name)) + t.indexSetsMtx.RLock() indexSet, ok := t.indexSets[id] t.indexSetsMtx.RUnlock() @@ -318,28 +311,29 @@ func (t *table) getOrCreateIndexSet(ctx context.Context, id string, forQuerying } // instantiate the index set, add it to the map - indexSet, err = NewIndexSet(t.name, id, filepath.Join(t.cacheLocation, id), baseIndexSet, t.openIndexFileFunc, - loggerWithUserID(t.logger, id)) + indexSet, err = NewIndexSet(t.name, id, filepath.Join(t.cacheLocation, id), baseIndexSet, t.openIndexFileFunc, logger) if err != nil { return nil, err } t.indexSets[id] = indexSet - // initialize the index set in async mode, it would be upto the caller to wait for its readiness using IndexSet.AwaitReady() + // initialize the index set in async mode + // it is up to the caller to wait for its readiness using IndexSet.AwaitReady() go func() { + start := time.Now() + err := indexSet.Init(forQuerying) + duration := time.Since(start) + + level.Info(logger).Log("msg", "init index set", "duration", duration, "success", err == nil) + if forQuerying { - start := time.Now() - defer func() { - duration := time.Since(start) - t.metrics.queryTimeTableDownloadDurationSeconds.WithLabelValues(t.name).Add(duration.Seconds()) - logger := spanlogger.FromContextWithFallback(ctx, loggerWithUserID(t.logger, id)) - level.Info(logger).Log("msg", "downloaded index set at query time", "duration", duration) - }() + t.metrics.queryTimeTableDownloadDurationSeconds.WithLabelValues(t.name).Add(duration.Seconds()) + t.metrics.queryWaitTime.WithLabelValues(t.name).Observe(duration.Seconds()) + level.Info(logger).Log("msg", "downloaded index set at query time", "duration", duration) } - err := indexSet.Init(forQuerying) if err != nil { - level.Error(t.logger).Log("msg", fmt.Sprintf("failed to init user index set %s", id), "err", err) + level.Error(logger).Log("msg", "failed to init user index set", "err", err) t.cleanupBrokenIndexSet(ctx, id) } }() @@ -372,7 +366,7 @@ func (t *table) EnsureQueryReadiness(ctx context.Context, userIDs []string) erro if err != nil { return err } - err = commonIndexSet.AwaitReady(ctx) + err = commonIndexSet.AwaitReady(ctx, "ensure query readiness") if err != nil { return err } @@ -401,7 +395,7 @@ func (t *table) downloadUserIndexes(ctx context.Context, userIDs []string) error return err } - return indexSet.AwaitReady(ctx) + return indexSet.AwaitReady(ctx, "download user indexes") }) } diff --git a/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go b/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go index 612f1d1eaa2a9..6b69272593784 100644 --- a/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go +++ b/pkg/storage/stores/shipper/indexshipper/downloads/table_manager.go @@ -11,6 +11,7 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" @@ -131,7 +132,7 @@ func (tm *tableManager) loop() { case <-syncTicker.C: err := tm.syncTables(tm.ctx) if err != nil { - level.Error(tm.logger).Log("msg", "error syncing local boltdb files with storage", "err", err) + level.Error(tm.logger).Log("msg", "error syncing local index files with storage", "err", err) } // we need to keep ensuring query readiness to download every days new table which would otherwise be downloaded only during queries. @@ -180,10 +181,13 @@ func (tm *tableManager) ForEach(ctx context.Context, tableName, userID string, c func (tm *tableManager) getOrCreateTable(tableName string) (Table, error) { // if table is already there, use it. + start := time.Now() tm.tablesMtx.RLock() table, ok := tm.tables[tableName] tm.tablesMtx.RUnlock() + level.Info(tm.logger).Log("msg", "get or create table", "found", ok, "table", tableName, "wait_for_lock", time.Since(start)) + if !ok { tm.tablesMtx.Lock() defer tm.tablesMtx.Unlock() @@ -192,7 +196,7 @@ func (tm *tableManager) getOrCreateTable(tableName string) (Table, error) { table, ok = tm.tables[tableName] if !ok { // table not found, creating one. - level.Info(tm.logger).Log("msg", fmt.Sprintf("downloading all files for table %s", tableName)) + level.Info(tm.logger).Log("msg", "downloading all files for table", "table", tableName) tablePath := filepath.Join(tm.cfg.CacheDir, tableName) err := util.EnsureDirectory(tablePath) @@ -227,11 +231,16 @@ func (tm *tableManager) syncTables(ctx context.Context) error { level.Info(tm.logger).Log("msg", "syncing tables") - for _, table := range tm.tables { + for name, table := range tm.tables { + level.Debug(tm.logger).Log("msg", "syncing table", "table", name) + start := time.Now() err := table.Sync(ctx) + duration := float64(time.Since(start)) if err != nil { - return err + tm.metrics.tableSyncLatency.WithLabelValues(name, statusFailure).Observe(duration) + return errors.Wrapf(err, "failed to sync table '%s'", name) } + tm.metrics.tableSyncLatency.WithLabelValues(name, statusSuccess).Observe(duration) } return nil @@ -244,10 +253,10 @@ func (tm *tableManager) cleanupCache() error { level.Info(tm.logger).Log("msg", "cleaning tables cache") for name, table := range tm.tables { - level.Info(tm.logger).Log("msg", fmt.Sprintf("cleaning up expired table %s", name)) + level.Debug(tm.logger).Log("msg", "cleaning up expired table", "table", name) isEmpty, err := table.DropUnusedIndex(tm.cfg.CacheTTL, time.Now()) if err != nil { - return err + return errors.Wrapf(err, "failed to clean up expired table '%s'", name) } if isEmpty {
chore
Improve instrumentation of index download/sync (#13194)
67295e0a16677feabb83284e058926b016993128
2024-08-08 19:03:48
renovate[bot]
fix(deps): update github.com/axiomhq/hyperloglog digest to af9851f (#13806)
false
diff --git a/go.mod b/go.mod index 20dde38ea42da..f7a87ee02f839 100644 --- a/go.mod +++ b/go.mod @@ -118,7 +118,7 @@ require ( github.com/DmitriyVTitov/size v1.5.0 github.com/IBM/go-sdk-core/v5 v5.13.1 github.com/IBM/ibm-cos-sdk-go v1.10.0 - github.com/axiomhq/hyperloglog v0.0.0-20240124082744-24bca3a5b39b + github.com/axiomhq/hyperloglog v0.0.0-20240507144631-af9851f82b27 github.com/buger/jsonparser v1.1.1 github.com/coder/quartz v0.1.0 github.com/d4l3k/messagediff v1.2.1 diff --git a/go.sum b/go.sum index 76b72595a5214..cfbf2d45a1c00 100644 --- a/go.sum +++ b/go.sum @@ -383,8 +383,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.16.1 h1:xsOtPAvHqhvQvBza5ohaUcfq1Lce github.com/aws/aws-sdk-go-v2/service/sts v1.16.1/go.mod h1:Aq2/Qggh2oemSfyHH+EO4UBbgWG6zFCXLHYI4ILTY7w= github.com/aws/smithy-go v1.11.1 h1:IQ+lPZVkSM3FRtyaDox41R8YS6iwPMYIreejOgPW49g= github.com/aws/smithy-go v1.11.1/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= -github.com/axiomhq/hyperloglog v0.0.0-20240124082744-24bca3a5b39b h1:F3yMzKumBUQ6Fn0sYI1YQ16vQRucpZOfBQ9HXWl5+XI= -github.com/axiomhq/hyperloglog v0.0.0-20240124082744-24bca3a5b39b/go.mod h1:k08r+Yj1PRAmuayFiRK6MYuR5Ve4IuZtTfxErMIh0+c= +github.com/axiomhq/hyperloglog v0.0.0-20240507144631-af9851f82b27 h1:60m4tnanN1ctzIu4V3bfCNJ39BiOPSm1gHFlFjTkRE0= +github.com/axiomhq/hyperloglog v0.0.0-20240507144631-af9851f82b27/go.mod h1:k08r+Yj1PRAmuayFiRK6MYuR5Ve4IuZtTfxErMIh0+c= github.com/baidubce/bce-sdk-go v0.9.141 h1:EV5BH5lfymIGPSmYDo9xYdsVlvWAW6nFeiA6t929zBE= github.com/baidubce/bce-sdk-go v0.9.141/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc= diff --git a/vendor/github.com/axiomhq/hyperloglog/README.md b/vendor/github.com/axiomhq/hyperloglog/README.md index 00a5614f7eacb..cf5c05e842cab 100644 --- a/vendor/github.com/axiomhq/hyperloglog/README.md +++ b/vendor/github.com/axiomhq/hyperloglog/README.md @@ -44,7 +44,7 @@ Kindly check our [contributing guide](https://github.com/axiomhq/hyperloglog/blo ## License -&copy; Axiom, Inc., 2022 +&copy; Axiom, Inc., 2024 Distributed under MIT License (`The MIT License`). diff --git a/vendor/github.com/axiomhq/hyperloglog/compressed.go b/vendor/github.com/axiomhq/hyperloglog/compressed.go index 4b908be46c3da..d140b88c16cdc 100644 --- a/vendor/github.com/axiomhq/hyperloglog/compressed.go +++ b/vendor/github.com/axiomhq/hyperloglog/compressed.go @@ -103,9 +103,9 @@ func (v *compressedList) UnmarshalBinary(data []byte) error { return nil } -func newCompressedList() *compressedList { +func newCompressedList(capacity int) *compressedList { v := &compressedList{} - v.b = make(variableLengthList, 0) + v.b = make(variableLengthList, 0, capacity) return v } diff --git a/vendor/github.com/axiomhq/hyperloglog/hyperloglog.go b/vendor/github.com/axiomhq/hyperloglog/hyperloglog.go index 826639158e9bb..58a13a5d62872 100644 --- a/vendor/github.com/axiomhq/hyperloglog/hyperloglog.go +++ b/vendor/github.com/axiomhq/hyperloglog/hyperloglog.go @@ -71,7 +71,7 @@ func newSketch(precision uint8, sparse bool) (*Sketch, error) { } if sparse { s.tmpSet = set{} - s.sparseList = newCompressedList() + s.sparseList = newCompressedList(0) } else { s.regs = newRegisters(m) } @@ -253,9 +253,9 @@ func (sk *Sketch) Estimate() uint64 { } if sk.b == 0 { - est = (sk.alpha * m * (m - ez) / (sum + beta(ez))) + est = sk.alpha * m * (m - ez) / (sum + beta(ez)) } else { - est = (sk.alpha * m * m / sum) + est = sk.alpha * m * m / sum } return uint64(est + 0.5) @@ -272,7 +272,7 @@ func (sk *Sketch) mergeSparse() { } sort.Sort(keys) - newList := newCompressedList() + newList := newCompressedList(4*len(sk.tmpSet) + len(sk.sparseList.b)) for iter, i := sk.sparseList.Iter(), 0; iter.HasNext() || i < len(keys); { if !iter.HasNext() { newList.Append(keys[i]) diff --git a/vendor/modules.txt b/vendor/modules.txt index 66e15ee11f90b..ccc80b28f445e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -464,7 +464,7 @@ github.com/aws/smithy-go/rand github.com/aws/smithy-go/time github.com/aws/smithy-go/transport/http github.com/aws/smithy-go/transport/http/internal/io -# github.com/axiomhq/hyperloglog v0.0.0-20240124082744-24bca3a5b39b +# github.com/axiomhq/hyperloglog v0.0.0-20240507144631-af9851f82b27 ## explicit; go 1.12 github.com/axiomhq/hyperloglog # github.com/baidubce/bce-sdk-go v0.9.141
fix
update github.com/axiomhq/hyperloglog digest to af9851f (#13806)
40ee7667244f2e094b5a7199705b4f3dacb7ffaf
2024-06-26 18:01:40
Paul Rogers
feat: Collect duplicate log line metrics (#13084)
false
diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index a3966db2f9af1..145ab85144a06 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -3805,6 +3805,14 @@ These are values which allow you to control aspects of Loki's operation, most co # CLI flag: -operation-config.log-push-request-streams [log_push_request_streams: <boolean> | default = false] +# Log metrics for duplicate lines received. +# CLI flag: -operation-config.log-duplicate-metrics +[log_duplicate_metrics: <boolean> | default = false] + +# Log stream info for duplicate lines received +# CLI flag: -operation-config.log-duplicate-stream-info +[log_duplicate_stream_info: <boolean> | default = false] + # Log push errors with a rate limited logger, will show client push errors # without overly spamming logs. # CLI flag: -operation-config.limited-log-push-errors diff --git a/pkg/chunkenc/dumb_chunk.go b/pkg/chunkenc/dumb_chunk.go index e2d520df6e024..ef8548b1438da 100644 --- a/pkg/chunkenc/dumb_chunk.go +++ b/pkg/chunkenc/dumb_chunk.go @@ -36,17 +36,18 @@ func (c *dumbChunk) SpaceFor(_ *logproto.Entry) bool { return len(c.entries) < tmpNumEntries } -func (c *dumbChunk) Append(entry *logproto.Entry) error { +// The dumbChunk does not check for duplicates, and will always return false +func (c *dumbChunk) Append(entry *logproto.Entry) (bool, error) { if len(c.entries) == tmpNumEntries { - return ErrChunkFull + return false, ErrChunkFull } if len(c.entries) > 0 && c.entries[len(c.entries)-1].Timestamp.After(entry.Timestamp) { - return ErrOutOfOrder + return false, ErrOutOfOrder } c.entries = append(c.entries, *entry) - return nil + return false, nil } func (c *dumbChunk) Size() int { diff --git a/pkg/chunkenc/interface.go b/pkg/chunkenc/interface.go index 3825a6520af5f..f0b17c7750f3d 100644 --- a/pkg/chunkenc/interface.go +++ b/pkg/chunkenc/interface.go @@ -132,7 +132,8 @@ func SupportedEncoding() string { type Chunk interface { Bounds() (time.Time, time.Time) SpaceFor(*logproto.Entry) bool - Append(*logproto.Entry) error + // Append returns true if the entry appended was a duplicate + Append(*logproto.Entry) (bool, error) Iterator(ctx context.Context, mintT, maxtT time.Time, direction logproto.Direction, pipeline log.StreamPipeline) (iter.EntryIterator, error) SampleIterator(ctx context.Context, from, through time.Time, extractor log.StreamSampleExtractor) iter.SampleIterator // Returns the list of blocks in the chunks. diff --git a/pkg/chunkenc/memchunk.go b/pkg/chunkenc/memchunk.go index 107e3c71a97d5..f4e27255633dd 100644 --- a/pkg/chunkenc/memchunk.go +++ b/pkg/chunkenc/memchunk.go @@ -181,9 +181,10 @@ func (hb *headBlock) Reset() { func (hb *headBlock) Bounds() (int64, int64) { return hb.mint, hb.maxt } -func (hb *headBlock) Append(ts int64, line string, _ labels.Labels) error { +// The headBlock does not check for duplicates, and will always return false +func (hb *headBlock) Append(ts int64, line string, _ labels.Labels) (bool, error) { if !hb.IsEmpty() && hb.maxt > ts { - return ErrOutOfOrder + return false, ErrOutOfOrder } hb.entries = append(hb.entries, entry{t: ts, s: line}) @@ -193,7 +194,7 @@ func (hb *headBlock) Append(ts int64, line string, _ labels.Labels) error { hb.maxt = ts hb.size += len(line) - return nil + return false, nil } func (hb *headBlock) Serialise(pool WriterPool) ([]byte, error) { @@ -340,7 +341,7 @@ func (hb *headBlock) Convert(version HeadBlockFmt, symbolizer *symbolizer) (Head out := version.NewBlock(symbolizer) for _, e := range hb.entries { - if err := out.Append(e.t, e.s, e.structuredMetadata); err != nil { + if _, err := out.Append(e.t, e.s, e.structuredMetadata); err != nil { return nil, err } } @@ -834,27 +835,29 @@ func (c *MemChunk) Utilization() float64 { } // Append implements Chunk. -func (c *MemChunk) Append(entry *logproto.Entry) error { +// The MemChunk may return true or false, depending on what the head block returns. +func (c *MemChunk) Append(entry *logproto.Entry) (bool, error) { entryTimestamp := entry.Timestamp.UnixNano() // If the head block is empty but there are cut blocks, we have to make // sure the new entry is not out of order compared to the previous block if c.headFmt < UnorderedHeadBlockFmt && c.head.IsEmpty() && len(c.blocks) > 0 && c.blocks[len(c.blocks)-1].maxt > entryTimestamp { - return ErrOutOfOrder + return false, ErrOutOfOrder } if c.format < ChunkFormatV4 { entry.StructuredMetadata = nil } - if err := c.head.Append(entryTimestamp, entry.Line, logproto.FromLabelAdaptersToLabels(entry.StructuredMetadata)); err != nil { - return err + dup, err := c.head.Append(entryTimestamp, entry.Line, logproto.FromLabelAdaptersToLabels(entry.StructuredMetadata)) + if err != nil { + return dup, err } if c.head.UncompressedSize() >= c.blockSize { - return c.cut() + return false, c.cut() } - return nil + return dup, nil } // Close implements Chunk. @@ -1122,7 +1125,7 @@ func (c *MemChunk) Rebound(start, end time.Time, filter filter.Func) (Chunk, err if filter != nil && filter(entry.Timestamp, entry.Line, logproto.FromLabelAdaptersToLabels(entry.StructuredMetadata)...) { continue } - if err := newChunk.Append(&entry); err != nil { + if _, err := newChunk.Append(&entry); err != nil { return nil, err } } diff --git a/pkg/chunkenc/memchunk_test.go b/pkg/chunkenc/memchunk_test.go index f7ed66b7c8906..1d9ef3eea21f7 100644 --- a/pkg/chunkenc/memchunk_test.go +++ b/pkg/chunkenc/memchunk_test.go @@ -88,7 +88,8 @@ func TestBlocksInclusive(t *testing.T) { for _, format := range allPossibleFormats { chunkfmt, headfmt := format.chunkFormat, format.headBlockFmt chk := NewMemChunk(chunkfmt, enc, headfmt, testBlockSize, testTargetSize) - err := chk.Append(logprotoEntry(1, "1")) + dup, err := chk.Append(logprotoEntry(1, "1")) + require.False(t, dup) require.Nil(t, err) err = chk.cut() require.Nil(t, err) @@ -178,7 +179,9 @@ func TestBlock(t *testing.T) { } for _, c := range cases { - require.NoError(t, chk.Append(logprotoEntryWithStructuredMetadata(c.ts, c.str, c.lbs))) + dup, err := chk.Append(logprotoEntryWithStructuredMetadata(c.ts, c.str, c.lbs)) + require.False(t, dup) + require.NoError(t, err) if c.cut { require.NoError(t, chk.cut()) } @@ -442,7 +445,9 @@ func TestSerialization(t *testing.T) { if appendWithStructuredMetadata { entry.StructuredMetadata = []logproto.LabelAdapter{{Name: "foo", Value: strconv.Itoa(i)}} } - require.NoError(t, chk.Append(entry)) + dup, err := chk.Append(entry) + require.False(t, dup) + require.NoError(t, err) } require.NoError(t, chk.Close()) @@ -527,7 +532,9 @@ func TestChunkFilling(t *testing.T) { i := int64(0) for ; chk.SpaceFor(entry) && i < 30; i++ { entry.Timestamp = time.Unix(0, i) - require.NoError(t, chk.Append(entry)) + dup, err := chk.Append(entry) + require.False(t, dup) + require.NoError(t, err) } require.Equal(t, int64(lines), i) @@ -576,7 +583,9 @@ func TestGZIPChunkTargetSize(t *testing.T) { Line: string(logLine), } entry.Timestamp = time.Unix(0, i) - require.NoError(t, chk.Append(entry)) + dup, err := chk.Append(entry) + require.False(t, dup) + require.NoError(t, err) } // 5000 is a limit ot make sure the test doesn't run away, we shouldn't need this many log lines to make 1MB chunk @@ -606,37 +615,61 @@ func TestMemChunk_AppendOutOfOrder(t *testing.T) { tests := map[string]tester{ "append out of order in the same block": func(t *testing.T, chk *MemChunk) { - assert.NoError(t, chk.Append(logprotoEntry(5, "test"))) - assert.NoError(t, chk.Append(logprotoEntry(6, "test"))) + dup, err := chk.Append(logprotoEntry(5, "test")) + assert.False(t, dup) + assert.NoError(t, err) + dup, err = chk.Append(logprotoEntry(6, "test")) + assert.False(t, dup) + assert.NoError(t, err) if chk.headFmt == OrderedHeadBlockFmt { - assert.EqualError(t, chk.Append(logprotoEntry(1, "test")), ErrOutOfOrder.Error()) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.EqualError(t, err, ErrOutOfOrder.Error()) + assert.False(t, dup) } else { - assert.NoError(t, chk.Append(logprotoEntry(1, "test"))) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.False(t, dup) + assert.NoError(t, err) } }, "append out of order in a new block right after cutting the previous one": func(t *testing.T, chk *MemChunk) { - assert.NoError(t, chk.Append(logprotoEntry(5, "test"))) - assert.NoError(t, chk.Append(logprotoEntry(6, "test"))) + dup, err := chk.Append(logprotoEntry(5, "test")) + assert.False(t, dup) + assert.NoError(t, err) + dup, err = chk.Append(logprotoEntry(6, "test")) + assert.False(t, dup) + assert.NoError(t, err) assert.NoError(t, chk.cut()) if chk.headFmt == OrderedHeadBlockFmt { - assert.EqualError(t, chk.Append(logprotoEntry(1, "test")), ErrOutOfOrder.Error()) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.False(t, dup) + assert.EqualError(t, err, ErrOutOfOrder.Error()) } else { - assert.NoError(t, chk.Append(logprotoEntry(1, "test"))) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.False(t, dup) + assert.NoError(t, err) } }, "append out of order in a new block after multiple cuts": func(t *testing.T, chk *MemChunk) { - assert.NoError(t, chk.Append(logprotoEntry(5, "test"))) + dup, err := chk.Append(logprotoEntry(5, "test")) + assert.False(t, dup) + assert.NoError(t, err) assert.NoError(t, chk.cut()) - assert.NoError(t, chk.Append(logprotoEntry(6, "test"))) + dup, err = chk.Append(logprotoEntry(6, "test")) + assert.False(t, dup) + assert.NoError(t, err) assert.NoError(t, chk.cut()) if chk.headFmt == OrderedHeadBlockFmt { - assert.EqualError(t, chk.Append(logprotoEntry(1, "test")), ErrOutOfOrder.Error()) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.False(t, dup) + assert.EqualError(t, err, ErrOutOfOrder.Error()) } else { - assert.NoError(t, chk.Append(logprotoEntry(1, "test"))) + dup, err = chk.Append(logprotoEntry(1, "test")) + assert.False(t, dup) + assert.NoError(t, err) } }, } @@ -705,7 +738,7 @@ func TestChunkStats(t *testing.T) { if !c.SpaceFor(entry) { break } - if err := c.Append(entry); err != nil { + if _, err := c.Append(entry); err != nil { t.Fatal(err) } inserted++ @@ -826,7 +859,7 @@ func BenchmarkWrite(b *testing.B) { c := NewMemChunk(ChunkFormatV3, enc, f, testBlockSize, testTargetSize) // adds until full so we trigger cut which serialize using gzip for c.SpaceFor(entry) { - _ = c.Append(entry) + _, _ = c.Append(entry) entry.Timestamp = time.Unix(0, i) entry.Line = testdata.LogString(i) if withStructuredMetadata { @@ -977,7 +1010,7 @@ func BenchmarkHeadBlockIterator(b *testing.B) { } for i := 0; i < j; i++ { - if err := h.Append(int64(i), "this is the append string", structuredMetadata); err != nil { + if _, err := h.Append(int64(i), "this is the append string", structuredMetadata); err != nil { b.Fatal(err) } } @@ -1009,7 +1042,7 @@ func BenchmarkHeadBlockSampleIterator(b *testing.B) { } for i := 0; i < j; i++ { - if err := h.Append(int64(i), "this is the append string", structuredMetadata); err != nil { + if _, err := h.Append(int64(i), "this is the append string", structuredMetadata); err != nil { b.Fatal(err) } } @@ -1034,13 +1067,13 @@ func TestMemChunk_IteratorBounds(t *testing.T) { t.Helper() c := NewMemChunk(ChunkFormatV3, EncNone, DefaultTestHeadBlockFmt, 1e6, 1e6) - if err := c.Append(&logproto.Entry{ + if _, err := c.Append(&logproto.Entry{ Timestamp: time.Unix(0, 1), Line: "1", }); err != nil { t.Fatal(err) } - if err := c.Append(&logproto.Entry{ + if _, err := c.Append(&logproto.Entry{ Timestamp: time.Unix(0, 2), Line: "2", }); err != nil { @@ -1099,7 +1132,9 @@ func TestMemchunkLongLine(t *testing.T) { c := NewMemChunk(ChunkFormatV3, enc, DefaultTestHeadBlockFmt, testBlockSize, testTargetSize) for i := 1; i <= 10; i++ { - require.NoError(t, c.Append(&logproto.Entry{Timestamp: time.Unix(0, int64(i)), Line: strings.Repeat("e", 200000)})) + dup, err := c.Append(&logproto.Entry{Timestamp: time.Unix(0, int64(i)), Line: strings.Repeat("e", 200000)}) + require.False(t, dup) + require.NoError(t, err) } noopStreamPipeline := log.NewNoopPipeline().ForStream(labels.Labels{}) it, err := c.Iterator(context.Background(), time.Unix(0, 0), time.Unix(0, 100), logproto.FORWARD, noopStreamPipeline) @@ -1143,7 +1178,9 @@ func TestCheckpointEncoding(t *testing.T) { }}, } require.Equal(t, true, c.SpaceFor(entry)) - require.Nil(t, c.Append(entry)) + dup, err := c.Append(entry) + require.False(t, dup) + require.Nil(t, err) } // cut it @@ -1178,7 +1215,9 @@ func TestCheckpointEncoding(t *testing.T) { Line: fmt.Sprintf("hi there - %d", i), } require.Equal(t, true, c.SpaceFor(entry)) - require.Nil(t, c.Append(entry)) + dup, err := c.Append(entry) + require.False(t, dup) + require.Nil(t, err) } // ensure new blocks are not cut @@ -1321,7 +1360,9 @@ func Test_HeadIteratorReverse(t *testing.T) { } var i int64 for e := genEntry(i); c.SpaceFor(e); e, i = genEntry(i+1), i+1 { - require.NoError(t, c.Append(e)) + dup, err := c.Append(e) + require.False(t, dup) + require.NoError(t, err) } assertOrder := func(t *testing.T, total int64) { @@ -1427,7 +1468,7 @@ func TestMemChunk_Rebound(t *testing.T) { func buildTestMemChunk(t *testing.T, from, through time.Time) *MemChunk { chk := NewMemChunk(ChunkFormatV3, EncGZIP, DefaultTestHeadBlockFmt, defaultBlockSize, 0) for ; from.Before(through); from = from.Add(time.Second) { - err := chk.Append(&logproto.Entry{ + _, err := chk.Append(&logproto.Entry{ Line: from.String(), Timestamp: from, }) @@ -1558,7 +1599,7 @@ func buildFilterableTestMemChunk(t *testing.T, from, through time.Time, matching if matchingFrom != nil && matchingTo != nil && (from.Equal(*matchingFrom) || (from.After(*matchingFrom) && (from.Before(*matchingTo)))) { t.Logf("%v matching line", from.String()) - err := chk.Append(&logproto.Entry{ + _, err := chk.Append(&logproto.Entry{ Line: fmt.Sprintf("matching %v", from.String()), Timestamp: from, StructuredMetadata: structuredMetadata, @@ -1570,7 +1611,7 @@ func buildFilterableTestMemChunk(t *testing.T, from, through time.Time, matching if withStructuredMetadata { structuredMetadata = push.LabelsAdapter{{Name: "ding", Value: "dong"}} } - err := chk.Append(&logproto.Entry{ + _, err := chk.Append(&logproto.Entry{ Line: from.String(), Timestamp: from, StructuredMetadata: structuredMetadata, @@ -1700,7 +1741,9 @@ func TestMemChunk_SpaceFor(t *testing.T) { chk.blocks = make([]block, tc.nBlocks) chk.cutBlockSize = tc.cutBlockSize for i := 0; i < tc.headSize; i++ { - require.NoError(t, chk.head.Append(int64(i), "a", nil)) + dup, err := chk.head.Append(int64(i), "a", nil) + require.False(t, dup) + require.NoError(t, err) } expect := tc.expect @@ -1724,23 +1767,31 @@ func TestMemChunk_IteratorWithStructuredMetadata(t *testing.T) { {Name: "job", Value: "fake"}, } chk := newMemChunkWithFormat(ChunkFormatV4, enc, UnorderedWithStructuredMetadataHeadBlockFmt, testBlockSize, testTargetSize) - require.NoError(t, chk.Append(logprotoEntryWithStructuredMetadata(1, "lineA", []logproto.LabelAdapter{ + dup, err := chk.Append(logprotoEntryWithStructuredMetadata(1, "lineA", []logproto.LabelAdapter{ {Name: "traceID", Value: "123"}, {Name: "user", Value: "a"}, - }))) - require.NoError(t, chk.Append(logprotoEntryWithStructuredMetadata(2, "lineB", []logproto.LabelAdapter{ + })) + require.False(t, dup) + require.NoError(t, err) + dup, err = chk.Append(logprotoEntryWithStructuredMetadata(2, "lineB", []logproto.LabelAdapter{ {Name: "traceID", Value: "456"}, {Name: "user", Value: "b"}, - }))) + })) + require.False(t, dup) + require.NoError(t, err) require.NoError(t, chk.cut()) - require.NoError(t, chk.Append(logprotoEntryWithStructuredMetadata(3, "lineC", []logproto.LabelAdapter{ + dup, err = chk.Append(logprotoEntryWithStructuredMetadata(3, "lineC", []logproto.LabelAdapter{ {Name: "traceID", Value: "789"}, {Name: "user", Value: "c"}, - }))) - require.NoError(t, chk.Append(logprotoEntryWithStructuredMetadata(4, "lineD", []logproto.LabelAdapter{ + })) + require.False(t, dup) + require.NoError(t, err) + dup, err = chk.Append(logprotoEntryWithStructuredMetadata(4, "lineD", []logproto.LabelAdapter{ {Name: "traceID", Value: "123"}, {Name: "user", Value: "d"}, - }))) + })) + require.False(t, dup) + require.NoError(t, err) // The expected bytes is the sum of bytes decompressed and bytes read from the head chunk. // First we add the bytes read from the store (aka decompressed). That's diff --git a/pkg/chunkenc/unordered.go b/pkg/chunkenc/unordered.go index 788f9c0a7c45b..807f80b2c0f87 100644 --- a/pkg/chunkenc/unordered.go +++ b/pkg/chunkenc/unordered.go @@ -5,6 +5,7 @@ import ( "context" "encoding/binary" "fmt" + "io" "math" "time" @@ -34,7 +35,7 @@ type HeadBlock interface { Entries() int UncompressedSize() int Convert(HeadBlockFmt, *symbolizer) (HeadBlock, error) - Append(int64, string, labels.Labels) error + Append(int64, string, labels.Labels) (bool, error) Iterator( ctx context.Context, direction logproto.Direction, @@ -110,7 +111,8 @@ func (e *nsEntries) ValueAtDimension(_ uint64) int64 { return e.ts } -func (hb *unorderedHeadBlock) Append(ts int64, line string, structuredMetadata labels.Labels) error { +// unorderedHeadBlock will return true if the entry is a duplicate, false otherwise +func (hb *unorderedHeadBlock) Append(ts int64, line string, structuredMetadata labels.Labels) (bool, error) { if hb.format < UnorderedWithStructuredMetadataHeadBlockFmt { // structuredMetadata must be ignored for the previous head block formats structuredMetadata = nil @@ -135,7 +137,7 @@ func (hb *unorderedHeadBlock) Append(ts int64, line string, structuredMetadata l for _, et := range displaced[0].(*nsEntries).entries { if et.line == line { e.entries = displaced[0].(*nsEntries).entries - return nil + return true, nil } } e.entries = append(displaced[0].(*nsEntries).entries, nsEntry{line, hb.symbolizer.Add(structuredMetadata)}) @@ -156,7 +158,7 @@ func (hb *unorderedHeadBlock) Append(ts int64, line string, structuredMetadata l hb.size += len(structuredMetadata) * 2 * 4 // 4 bytes per label and value pair as structuredMetadataSymbols hb.lines++ - return nil + return false, nil } func metaLabelsLen(metaLabels labels.Labels) int { @@ -443,7 +445,8 @@ func (hb *unorderedHeadBlock) Convert(version HeadBlockFmt, symbolizer *symboliz 0, math.MaxInt64, func(_ *stats.Context, ts int64, line string, structuredMetadataSymbols symbols) error { - return out.Append(ts, line, hb.symbolizer.Lookup(structuredMetadataSymbols)) + _, err := out.Append(ts, line, hb.symbolizer.Lookup(structuredMetadataSymbols)) + return err }, ) return out, err @@ -583,7 +586,7 @@ func (hb *unorderedHeadBlock) LoadBytes(b []byte) error { } } - if err := hb.Append(ts, line, hb.symbolizer.Lookup(structuredMetadataSymbols)); err != nil { + if _, err := hb.Append(ts, line, hb.symbolizer.Lookup(structuredMetadataSymbols)); err != nil { return err } } diff --git a/pkg/chunkenc/unordered_test.go b/pkg/chunkenc/unordered_test.go index f4930952660fc..43c07d0f835f3 100644 --- a/pkg/chunkenc/unordered_test.go +++ b/pkg/chunkenc/unordered_test.go @@ -35,7 +35,9 @@ func iterEq(t *testing.T, exp []entry, got iter.EntryIterator) { func Test_forEntriesEarlyReturn(t *testing.T) { hb := newUnorderedHeadBlock(UnorderedHeadBlockFmt, newSymbolizer()) for i := 0; i < 10; i++ { - require.Nil(t, hb.Append(int64(i), fmt.Sprint(i), labels.Labels{{Name: "i", Value: fmt.Sprint(i)}})) + dup, err := hb.Append(int64(i), fmt.Sprint(i), labels.Labels{{Name: "i", Value: fmt.Sprint(i)}}) + require.False(t, dup) + require.Nil(t, err) } // forward @@ -86,6 +88,7 @@ func Test_Unordered_InsertRetrieval(t *testing.T) { desc string input, exp []entry dir logproto.Direction + hasDup bool }{ { desc: "simple forward", @@ -152,7 +155,8 @@ func Test_Unordered_InsertRetrieval(t *testing.T) { exp: []entry{ {0, "a", nil}, {0, "b", nil}, {1, "c", nil}, }, - dir: logproto.FORWARD, + dir: logproto.FORWARD, + hasDup: true, }, { desc: "ts remove exact dupe backward", @@ -162,7 +166,8 @@ func Test_Unordered_InsertRetrieval(t *testing.T) { exp: []entry{ {1, "c", nil}, {0, "b", nil}, {0, "a", nil}, }, - dir: logproto.BACKWARD, + dir: logproto.BACKWARD, + hasDup: true, }, } { t.Run(tc.desc, func(t *testing.T) { @@ -172,9 +177,17 @@ func Test_Unordered_InsertRetrieval(t *testing.T) { } { t.Run(format.String(), func(t *testing.T) { hb := newUnorderedHeadBlock(format, newSymbolizer()) + dup := false for _, e := range tc.input { - require.Nil(t, hb.Append(e.t, e.s, e.structuredMetadata)) + tmpdup, err := hb.Append(e.t, e.s, e.structuredMetadata) + if !dup { // only set dup if it's not already true + if tmpdup { // can't examine duplicates until we start getting all the data + dup = true + } + } + require.Nil(t, err) } + require.Equal(t, tc.hasDup, dup) itr := hb.Iterator( context.Background(), @@ -250,7 +263,9 @@ func Test_UnorderedBoundedIter(t *testing.T) { t.Run(format.String(), func(t *testing.T) { hb := newUnorderedHeadBlock(format, newSymbolizer()) for _, e := range tc.input { - require.Nil(t, hb.Append(e.t, e.s, e.structuredMetadata)) + dup, err := hb.Append(e.t, e.s, e.structuredMetadata) + require.False(t, dup) + require.Nil(t, err) } itr := hb.Iterator( @@ -281,9 +296,15 @@ func TestHeadBlockInterop(t *testing.T) { unorderedWithStructuredMetadata := newUnorderedHeadBlock(UnorderedWithStructuredMetadataHeadBlockFmt, newSymbolizer()) for i := 0; i < 100; i++ { metaLabels := labels.Labels{{Name: "foo", Value: fmt.Sprint(99 - i)}} - require.Nil(t, unordered.Append(int64(99-i), fmt.Sprint(99-i), metaLabels)) - require.Nil(t, unorderedWithStructuredMetadata.Append(int64(99-i), fmt.Sprint(99-i), metaLabels)) - require.Nil(t, ordered.Append(int64(i), fmt.Sprint(i), labels.Labels{{Name: "foo", Value: fmt.Sprint(i)}})) + dup, err := unordered.Append(int64(99-i), fmt.Sprint(99-i), metaLabels) + require.False(t, dup) + require.Nil(t, err) + dup, err = unorderedWithStructuredMetadata.Append(int64(99-i), fmt.Sprint(99-i), metaLabels) + require.False(t, dup) + require.Nil(t, err) + dup, err = ordered.Append(int64(i), fmt.Sprint(i), labels.Labels{{Name: "foo", Value: fmt.Sprint(i)}}) + require.False(t, dup) + require.Nil(t, err) } // turn to bytes @@ -359,14 +380,14 @@ func BenchmarkHeadBlockWrites(b *testing.B) { headBlockFn := func() func(int64, string, labels.Labels) { hb := &headBlock{} return func(ts int64, line string, metaLabels labels.Labels) { - _ = hb.Append(ts, line, metaLabels) + _, _ = hb.Append(ts, line, metaLabels) } } unorderedHeadBlockFn := func() func(int64, string, labels.Labels) { hb := newUnorderedHeadBlock(UnorderedHeadBlockFmt, nil) return func(ts int64, line string, metaLabels labels.Labels) { - _ = hb.Append(ts, line, metaLabels) + _, _ = hb.Append(ts, line, metaLabels) } } @@ -432,10 +453,12 @@ func TestUnorderedChunkIterators(t *testing.T) { c := NewMemChunk(ChunkFormatV4, EncSnappy, UnorderedWithStructuredMetadataHeadBlockFmt, testBlockSize, testTargetSize) for i := 0; i < 100; i++ { // push in reverse order - require.Nil(t, c.Append(&logproto.Entry{ + dup, err := c.Append(&logproto.Entry{ Timestamp: time.Unix(int64(99-i), 0), Line: fmt.Sprint(99 - i), - })) + }) + require.False(t, dup) + require.Nil(t, err) // ensure we have a mix of cut blocks + head block. if i%30 == 0 { @@ -574,7 +597,7 @@ func TestUnorderedIteratorCountsAllEntries(t *testing.T) { func chunkFrom(xs []logproto.Entry) ([]byte, error) { c := NewMemChunk(ChunkFormatV4, EncSnappy, UnorderedWithStructuredMetadataHeadBlockFmt, testBlockSize, testTargetSize) for _, x := range xs { - if err := c.Append(&x); err != nil { + if _, err := c.Append(&x); err != nil { return nil, err } } @@ -634,7 +657,9 @@ func TestReorder(t *testing.T) { t.Run(tc.desc, func(t *testing.T) { c := NewMemChunk(ChunkFormatV4, EncSnappy, UnorderedWithStructuredMetadataHeadBlockFmt, testBlockSize, testTargetSize) for _, x := range tc.input { - require.Nil(t, c.Append(&x)) + dup, err := c.Append(&x) + require.False(t, dup) + require.Nil(t, err) } require.Nil(t, c.Close()) b, err := c.Bytes() @@ -657,10 +682,12 @@ func TestReorderAcrossBlocks(t *testing.T) { {3, 7}, } { for _, x := range batch { - require.Nil(t, c.Append(&logproto.Entry{ + dup, err := c.Append(&logproto.Entry{ Timestamp: time.Unix(int64(x), 0), Line: fmt.Sprint(x), - })) + }) + require.False(t, dup) + require.Nil(t, err) } require.Nil(t, c.cut()) } @@ -705,7 +732,9 @@ func Test_HeadIteratorHash(t *testing.T) { "ordered": &headBlock{}, } { t.Run(name, func(t *testing.T) { - require.NoError(t, b.Append(1, "foo", labels.Labels{{Name: "foo", Value: "bar"}})) + dup, err := b.Append(1, "foo", labels.Labels{{Name: "foo", Value: "bar"}}) + require.False(t, dup) + require.NoError(t, err) eit := b.Iterator(context.Background(), logproto.BACKWARD, 0, 2, log.NewNoopPipeline().ForStream(lbs)) for eit.Next() { diff --git a/pkg/chunkenc/util_test.go b/pkg/chunkenc/util_test.go index a1860f9ae297a..de74f7946e2ad 100644 --- a/pkg/chunkenc/util_test.go +++ b/pkg/chunkenc/util_test.go @@ -33,7 +33,7 @@ func generateData(enc Encoding, chunksCount, blockSize, targetSize int) ([]Chunk c := NewMemChunk(ChunkFormatV4, enc, UnorderedWithStructuredMetadataHeadBlockFmt, blockSize, targetSize) for c.SpaceFor(entry) { size += uint64(len(entry.Line)) - _ = c.Append(entry) + _, _ = c.Append(entry) i++ entry = logprotoEntry(i, testdata.LogString(i)) } @@ -55,7 +55,7 @@ func fillChunkClose(c Chunk, close bool) int64 { Line: testdata.LogString(i), } for c.SpaceFor(entry) { - err := c.Append(entry) + _, err := c.Append(entry) if err != nil { panic(err) } @@ -81,7 +81,7 @@ func fillChunkRandomOrder(c Chunk, close bool) { } for c.SpaceFor(entry) { - err := c.Append(entry) + _, err := c.Append(entry) if err != nil { panic(err) } diff --git a/pkg/compactor/retention/retention_test.go b/pkg/compactor/retention/retention_test.go index 6c261d34799e5..a3f157dc77743 100644 --- a/pkg/compactor/retention/retention_test.go +++ b/pkg/compactor/retention/retention_test.go @@ -223,11 +223,13 @@ func createChunk(t testing.TB, userID string, lbs labels.Labels, from model.Time chunkEnc := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncSnappy, chunkenc.UnorderedWithStructuredMetadataHeadBlockFmt, blockSize, targetSize) for ts := from; !ts.After(through); ts = ts.Add(1 * time.Minute) { - require.NoError(t, chunkEnc.Append(&logproto.Entry{ + dup, err := chunkEnc.Append(&logproto.Entry{ Timestamp: ts.Time(), Line: ts.String(), StructuredMetadata: logproto.FromLabelsToLabelAdapters(labels.FromStrings("foo", ts.String())), - })) + }) + require.False(t, dup) + require.NoError(t, err) } require.NoError(t, chunkEnc.Close()) diff --git a/pkg/distributor/writefailures/manager.go b/pkg/distributor/writefailures/manager.go index f02ab2e57d76f..5a02a7f2c2226 100644 --- a/pkg/distributor/writefailures/manager.go +++ b/pkg/distributor/writefailures/manager.go @@ -39,7 +39,8 @@ func (m *Manager) Log(tenantID string, err error) { return } - if !m.tenantCfgs.LimitedLogPushErrors(tenantID) { + if !(m.tenantCfgs.LimitedLogPushErrors(tenantID) || + m.tenantCfgs.LogDuplicateStreamInfo(tenantID)) { return } diff --git a/pkg/ingester/chunk_test.go b/pkg/ingester/chunk_test.go index 4523bc8cc1d8b..9ceb3c740926e 100644 --- a/pkg/ingester/chunk_test.go +++ b/pkg/ingester/chunk_test.go @@ -55,10 +55,11 @@ func TestIterator(t *testing.T) { t.Run(chk.name, func(t *testing.T) { chunk := chk.new() for i := int64(0); i < entries; i++ { - err := chunk.Append(&logproto.Entry{ + dup, err := chunk.Append(&logproto.Entry{ Timestamp: time.Unix(i, 0), Line: fmt.Sprintf("line %d", i), }) + require.False(t, dup) require.NoError(t, err) } diff --git a/pkg/ingester/encoding_test.go b/pkg/ingester/encoding_test.go index 4bb1aab0b8da6..458da1132c963 100644 --- a/pkg/ingester/encoding_test.go +++ b/pkg/ingester/encoding_test.go @@ -22,7 +22,9 @@ func fillChunk(t testing.TB, c chunkenc.Chunk) { } for c.SpaceFor(entry) { - require.NoError(t, c.Append(entry)) + dup, err := c.Append(entry) + require.False(t, dup) + require.NoError(t, err) i++ entry.Timestamp = time.Unix(0, i) entry.Line = fmt.Sprintf("entry for line %d", i) @@ -120,10 +122,12 @@ func Test_EncodingChunks(t *testing.T) { func Test_EncodingCheckpoint(t *testing.T) { conf := dummyConf() c := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncGZIP, chunkenc.UnorderedWithStructuredMetadataHeadBlockFmt, conf.BlockSize, conf.TargetChunkSize) - require.Nil(t, c.Append(&logproto.Entry{ + dup, err := c.Append(&logproto.Entry{ Timestamp: time.Unix(1, 0), Line: "hi there", - })) + }) + require.False(t, dup) + require.Nil(t, err) data, err := c.Bytes() require.Nil(t, err) from, to := c.Bounds() diff --git a/pkg/ingester/instance.go b/pkg/ingester/instance.go index 1d30e7e23ece4..b8d4ed68e9a7e 100644 --- a/pkg/ingester/instance.go +++ b/pkg/ingester/instance.go @@ -311,7 +311,7 @@ func (i *instance) createStream(ctx context.Context, pushReqStream logproto.Stre return nil, fmt.Errorf("failed to create stream: %w", err) } - s := newStream(chunkfmt, headfmt, i.cfg, i.limiter, i.instanceID, fp, sortedLabels, i.limiter.UnorderedWrites(i.instanceID), i.streamRateCalculator, i.metrics, i.writeFailures) + s := newStream(chunkfmt, headfmt, i.cfg, i.limiter, i.instanceID, fp, sortedLabels, i.limiter.UnorderedWrites(i.instanceID), i.streamRateCalculator, i.metrics, i.writeFailures, i.configs) // record will be nil when replaying the wal (we don't want to rewrite wal entries as we replay them). if record != nil { @@ -376,7 +376,7 @@ func (i *instance) createStreamByFP(ls labels.Labels, fp model.Fingerprint) (*st return nil, fmt.Errorf("failed to create stream for fingerprint: %w", err) } - s := newStream(chunkfmt, headfmt, i.cfg, i.limiter, i.instanceID, fp, sortedLabels, i.limiter.UnorderedWrites(i.instanceID), i.streamRateCalculator, i.metrics, i.writeFailures) + s := newStream(chunkfmt, headfmt, i.cfg, i.limiter, i.instanceID, fp, sortedLabels, i.limiter.UnorderedWrites(i.instanceID), i.streamRateCalculator, i.metrics, i.writeFailures, i.configs) i.onStreamCreated(s) diff --git a/pkg/ingester/instance_test.go b/pkg/ingester/instance_test.go index f5e9591654819..80074f6391e90 100644 --- a/pkg/ingester/instance_test.go +++ b/pkg/ingester/instance_test.go @@ -316,9 +316,10 @@ func setupTestStreams(t *testing.T) (*instance, time.Time, int) { require.NoError(t, err) chunkfmt, headfmt, err := instance.chunkFormatAt(minTs(&testStream)) require.NoError(t, err) - chunk := newStream(chunkfmt, headfmt, cfg, limiter, "fake", 0, nil, true, NewStreamRateCalculator(), NilMetrics, nil).NewChunk() + chunk := newStream(chunkfmt, headfmt, cfg, limiter, "fake", 0, nil, true, NewStreamRateCalculator(), NilMetrics, nil, nil).NewChunk() for _, entry := range testStream.Entries { - err = chunk.Append(&entry) + dup, err := chunk.Append(&entry) + require.False(t, dup) require.NoError(t, err) } stream.chunks = append(stream.chunks, chunkDesc{chunk: chunk}) @@ -575,7 +576,7 @@ func Benchmark_instance_addNewTailer(b *testing.B) { b.Run("addTailersToNewStream", func(b *testing.B) { for n := 0; n < b.N; n++ { - inst.addTailersToNewStream(newStream(chunkfmt, headfmt, nil, limiter, "fake", 0, lbs, true, NewStreamRateCalculator(), NilMetrics, nil)) + inst.addTailersToNewStream(newStream(chunkfmt, headfmt, nil, limiter, "fake", 0, lbs, true, NewStreamRateCalculator(), NilMetrics, nil, nil)) } }) } diff --git a/pkg/ingester/metrics.go b/pkg/ingester/metrics.go index 756eba0ebea74..fd2a3e52bbb97 100644 --- a/pkg/ingester/metrics.go +++ b/pkg/ingester/metrics.go @@ -66,6 +66,8 @@ type ingesterMetrics struct { shutdownMarker prometheus.Gauge flushQueueLength prometheus.Gauge + + duplicateLogBytesTotal *prometheus.CounterVec } // setRecoveryBytesInUse bounds the bytes reports to >= 0. @@ -293,5 +295,12 @@ func newIngesterMetrics(r prometheus.Registerer, metricsNamespace string) *inges Name: "flush_queue_length", Help: "The total number of series pending in the flush queue.", }), + + duplicateLogBytesTotal: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: metricsNamespace, + Subsystem: "ingester", + Name: "duplicate_log_bytes_total", + Help: "The total number of bytes that were discarded for duplicate log lines.", + }, []string{"tenant"}), } } diff --git a/pkg/ingester/stream.go b/pkg/ingester/stream.go index 0aa3c41ea619b..7d37859b1541f 100644 --- a/pkg/ingester/stream.go +++ b/pkg/ingester/stream.go @@ -8,6 +8,8 @@ import ( "sync" "time" + "github.com/grafana/loki/v3/pkg/runtime" + "github.com/go-kit/log/level" "github.com/grafana/dskit/httpgrpc" "github.com/opentracing/opentracing-go" @@ -78,6 +80,8 @@ type stream struct { chunkFormat byte chunkHeadBlockFormat chunkenc.HeadBlockFmt + + configs *runtime.TenantConfigs } type chunkDesc struct { @@ -107,6 +111,7 @@ func newStream( streamRateCalculator *StreamRateCalculator, metrics *ingesterMetrics, writeFailures *writefailures.Manager, + configs *runtime.TenantConfigs, ) *stream { hashNoShard, _ := labels.HashWithoutLabels(make([]byte, 0, 1024), ShardLbName) return &stream{ @@ -126,6 +131,8 @@ func newStream( writeFailures: writeFailures, chunkFormat: chunkFormat, chunkHeadBlockFormat: headBlockFmt, + + configs: configs, } } @@ -333,7 +340,8 @@ func (s *stream) storeEntries(ctx context.Context, entries []logproto.Entry, usa } chunk.lastUpdated = time.Now() - if err := chunk.chunk.Append(&entries[i]); err != nil { + dup, err := chunk.chunk.Append(&entries[i]) + if err != nil { invalid = append(invalid, entryWithError{&entries[i], err}) if chunkenc.IsOutOfOrderErr(err) { s.writeFailures.Log(s.tenant, err) @@ -342,6 +350,9 @@ func (s *stream) storeEntries(ctx context.Context, entries []logproto.Entry, usa } continue } + if dup { + s.handleLoggingOfDuplicateEntry(entries[i]) + } s.entryCt++ s.lastLine.ts = entries[i].Timestamp @@ -357,6 +368,21 @@ func (s *stream) storeEntries(ctx context.Context, entries []logproto.Entry, usa return bytesAdded, storedEntries, invalid } +func (s *stream) handleLoggingOfDuplicateEntry(entry logproto.Entry) { + if s.configs == nil { + return + } + if s.configs.LogDuplicateMetrics(s.tenant) { + s.metrics.duplicateLogBytesTotal.WithLabelValues(s.tenant).Add(float64(len(entry.Line))) + } + if s.configs.LogDuplicateStreamInfo(s.tenant) { + errMsg := fmt.Sprintf("duplicate log entry with size=%d at timestamp %s for stream %s", len(entry.Line), entry.Timestamp.Format(time.RFC3339), s.labelsString) + dupErr := errors.New(errMsg) + s.writeFailures.Log(s.tenant, dupErr) + } + +} + func (s *stream) validateEntries(ctx context.Context, entries []logproto.Entry, isReplay, rateLimitWholeStream bool, usageTracker push.UsageTracker) ([]logproto.Entry, []entryWithError) { var ( diff --git a/pkg/ingester/stream_test.go b/pkg/ingester/stream_test.go index e4dd4a37ab355..68974ae016b39 100644 --- a/pkg/ingester/stream_test.go +++ b/pkg/ingester/stream_test.go @@ -9,12 +9,20 @@ import ( "testing" "time" + "github.com/prometheus/client_golang/prometheus/testutil" + + gokitlog "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" + + "github.com/grafana/loki/v3/pkg/runtime" + "github.com/grafana/dskit/httpgrpc" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + "github.com/grafana/loki/v3/pkg/distributor/writefailures" "github.com/grafana/loki/v3/pkg/iter" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/log" @@ -69,6 +77,7 @@ func TestMaxReturnedStreamsErrors(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) _, err := s.Push(context.Background(), []logproto.Entry{ @@ -122,6 +131,7 @@ func TestPushDeduplication(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) written, err := s.Push(context.Background(), []logproto.Entry{ @@ -136,6 +146,76 @@ func TestPushDeduplication(t *testing.T) { require.Equal(t, len("test"+"newer, better test"), written) } +func TestPushDeduplicationExtraMetrics(t *testing.T) { + limits, err := validation.NewOverrides(defaultLimitsTestConfig(), nil) + require.NoError(t, err) + limiter := NewLimiter(limits, NilMetrics, &ringCountMock{count: 1}, 1) + + chunkfmt, headfmt := defaultChunkFormat(t) + + buf := bytes.NewBuffer(nil) + logger := gokitlog.NewLogfmtLogger(buf) + + provider := &providerMock{ + tenantConfig: func(tenantID string) *runtime.Config { + if tenantID == "fake" { + return &runtime.Config{ + LogDuplicateMetrics: true, + LogDuplicateStreamInfo: true, + } + } + + return &runtime.Config{} + }, + } + + runtimeCfg, err := runtime.NewTenantConfigs(provider) + + registry := prometheus.NewRegistry() + manager := writefailures.NewManager(logger, registry, writefailures.Cfg{LogRate: flagext.ByteSize(1000), AddInsightsLabel: true}, runtimeCfg, "ingester") + + require.NoError(t, err) + metrics := newIngesterMetrics(registry, "loki") + + s := newStream( + chunkfmt, + headfmt, + defaultConfig(), + limiter, + "fake", + model.Fingerprint(0), + labels.Labels{ + {Name: "foo", Value: "bar"}, + }, + true, + NewStreamRateCalculator(), + metrics, + manager, + runtimeCfg, + ) + + _, err = s.Push(context.Background(), []logproto.Entry{ + {Timestamp: time.Unix(1, 0), Line: "test"}, + }, recordPool.GetRecord(), 0, true, false, nil) + require.NoError(t, err) + _, err = s.Push(context.Background(), []logproto.Entry{ + {Timestamp: time.Unix(1, 0), Line: "not a test"}, + }, recordPool.GetRecord(), 0, true, false, nil) + require.NoError(t, err) + _, err = s.Push(context.Background(), []logproto.Entry{ + {Timestamp: time.Unix(1, 0), Line: "test"}, + }, recordPool.GetRecord(), 0, true, false, nil) + require.NoError(t, err) + require.Len(t, s.chunks, 1) + require.Equal(t, 2, s.chunks[0].chunk.Size(), "expected exact duplicate to be dropped and newer content with same timestamp to be appended") + require.Equal(t, float64(4), testutil.ToFloat64(metrics.duplicateLogBytesTotal.WithLabelValues("fake"))) + + content := buf.String() + require.NotEmpty(t, content) + require.Contains(t, content, "insight") + require.Contains(t, content, "duplicate") +} + func TestPushRejectOldCounter(t *testing.T) { limits, err := validation.NewOverrides(defaultLimitsTestConfig(), nil) require.NoError(t, err) @@ -157,6 +237,7 @@ func TestPushRejectOldCounter(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) // counter should be 2 now since the first line will be deduped @@ -204,10 +285,11 @@ func TestStreamIterator(t *testing.T) { chunk := chk.new() for j := int64(0); j < entries; j++ { k := i*entries + j - err := chunk.Append(&logproto.Entry{ + dup, err := chunk.Append(&logproto.Entry{ Timestamp: time.Unix(k, 0), Line: fmt.Sprintf("line %d", k), }) + require.False(t, dup) require.NoError(t, err) } s.chunks = append(s.chunks, chunkDesc{chunk: chunk}) @@ -263,6 +345,7 @@ func TestEntryErrorCorrectlyReported(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) s.highestTs = time.Now() @@ -301,6 +384,7 @@ func TestUnorderedPush(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) for _, x := range []struct { @@ -403,6 +487,7 @@ func TestPushRateLimit(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) entries := []logproto.Entry{ @@ -443,6 +528,7 @@ func TestPushRateLimitAllOrNothing(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) entries := []logproto.Entry{ @@ -482,6 +568,7 @@ func TestReplayAppendIgnoresValidityWindow(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ) base := time.Now() @@ -532,7 +619,7 @@ func Benchmark_PushStream(b *testing.B) { limiter := NewLimiter(limits, NilMetrics, &ringCountMock{count: 1}, 1) chunkfmt, headfmt := defaultChunkFormat(b) - s := newStream(chunkfmt, headfmt, &Config{MaxChunkAge: 24 * time.Hour}, limiter, "fake", model.Fingerprint(0), ls, true, NewStreamRateCalculator(), NilMetrics, nil) + s := newStream(chunkfmt, headfmt, &Config{MaxChunkAge: 24 * time.Hour}, limiter, "fake", model.Fingerprint(0), ls, true, NewStreamRateCalculator(), NilMetrics, nil, nil) expr, err := syntax.ParseLogSelector(`{namespace="loki-dev"}`, true) require.NoError(b, err) t, err := newTailer("foo", expr, &fakeTailServer{}, 10) @@ -566,3 +653,11 @@ func defaultChunkFormat(t testing.TB) (byte, chunkenc.HeadBlockFmt) { return chunkfmt, headfmt } + +type providerMock struct { + tenantConfig func(string) *runtime.Config +} + +func (m *providerMock) TenantConfig(userID string) *runtime.Config { + return m.tenantConfig(userID) +} diff --git a/pkg/ingester/streams_map_test.go b/pkg/ingester/streams_map_test.go index d98369ff152a9..b14b3e07e497f 100644 --- a/pkg/ingester/streams_map_test.go +++ b/pkg/ingester/streams_map_test.go @@ -31,6 +31,7 @@ func TestStreamsMap(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ), newStream( chunkfmt, @@ -46,6 +47,7 @@ func TestStreamsMap(t *testing.T) { NewStreamRateCalculator(), NilMetrics, nil, + nil, ), } var s *stream diff --git a/pkg/loki/runtime_config_test.go b/pkg/loki/runtime_config_test.go index 36126841dc47b..81081a856ca2b 100644 --- a/pkg/loki/runtime_config_test.go +++ b/pkg/loki/runtime_config_test.go @@ -91,8 +91,12 @@ configs: "1": log_push_request: false limited_log_push_errors: false + log_duplicate_metrics: false + log_duplicate_stream_info: false "2": log_push_request: true + log_duplicate_metrics: true + log_duplicate_stream_info: true `) tenantConfigs, err := runtime.NewTenantConfigs(runtimeGetter) @@ -104,6 +108,12 @@ configs: require.Equal(t, true, tenantConfigs.LogPushRequest("2")) require.Equal(t, true, tenantConfigs.LimitedLogPushErrors("3")) require.Equal(t, false, tenantConfigs.LogPushRequest("3")) + require.Equal(t, false, tenantConfigs.LogDuplicateMetrics("1")) + require.Equal(t, true, tenantConfigs.LogDuplicateMetrics("2")) + require.Equal(t, false, tenantConfigs.LogDuplicateMetrics("3")) + require.Equal(t, false, tenantConfigs.LogDuplicateStreamInfo("1")) + require.Equal(t, true, tenantConfigs.LogDuplicateStreamInfo("2")) + require.Equal(t, false, tenantConfigs.LogDuplicateStreamInfo("3")) } func newTestRuntimeconfig(t *testing.T, yaml string) runtime.TenantConfigProvider { diff --git a/pkg/runtime/config.go b/pkg/runtime/config.go index 85f8dc3d81b4a..1655789dae71d 100644 --- a/pkg/runtime/config.go +++ b/pkg/runtime/config.go @@ -5,9 +5,11 @@ import ( ) type Config struct { - LogStreamCreation bool `yaml:"log_stream_creation"` - LogPushRequest bool `yaml:"log_push_request"` - LogPushRequestStreams bool `yaml:"log_push_request_streams"` + LogStreamCreation bool `yaml:"log_stream_creation"` + LogPushRequest bool `yaml:"log_push_request"` + LogPushRequestStreams bool `yaml:"log_push_request_streams"` + LogDuplicateMetrics bool `yaml:"log_duplicate_metrics"` + LogDuplicateStreamInfo bool `yaml:"log_duplicate_stream_info"` // LimitedLogPushErrors is to be implemented and will allow logging push failures at a controlled pace. LimitedLogPushErrors bool `yaml:"limited_log_push_errors"` @@ -18,6 +20,8 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) { f.BoolVar(&cfg.LogStreamCreation, "operation-config.log-stream-creation", false, "Log every new stream created by a push request (very verbose, recommend to enable via runtime config only).") f.BoolVar(&cfg.LogPushRequest, "operation-config.log-push-request", false, "Log every push request (very verbose, recommend to enable via runtime config only).") f.BoolVar(&cfg.LogPushRequestStreams, "operation-config.log-push-request-streams", false, "Log every stream in a push request (very verbose, recommend to enable via runtime config only).") + f.BoolVar(&cfg.LogDuplicateMetrics, "operation-config.log-duplicate-metrics", false, "Log metrics for duplicate lines received.") + f.BoolVar(&cfg.LogDuplicateStreamInfo, "operation-config.log-duplicate-stream-info", false, "Log stream info for duplicate lines received") f.BoolVar(&cfg.LimitedLogPushErrors, "operation-config.limited-log-push-errors", true, "Log push errors with a rate limited logger, will show client push errors without overly spamming logs.") } @@ -94,6 +98,14 @@ func (o *TenantConfigs) LogPushRequestStreams(userID string) bool { return o.getOverridesForUser(userID).LogPushRequestStreams } +func (o *TenantConfigs) LogDuplicateMetrics(userID string) bool { + return o.getOverridesForUser(userID).LogDuplicateMetrics +} + +func (o *TenantConfigs) LogDuplicateStreamInfo(userID string) bool { + return o.getOverridesForUser(userID).LogDuplicateStreamInfo +} + func (o *TenantConfigs) LimitedLogPushErrors(userID string) bool { return o.getOverridesForUser(userID).LimitedLogPushErrors } diff --git a/pkg/storage/bloom/v1/bloom_tokenizer_test.go b/pkg/storage/bloom/v1/bloom_tokenizer_test.go index 7685faaa92427..9bef1ab2ca202 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer_test.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer_test.go @@ -101,7 +101,7 @@ func TestTokenizerPopulate(t *testing.T) { sbf := filter.NewScalableBloomFilter(1024, 0.01, 0.8) memChunk := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncSnappy, chunkenc.ChunkHeadFormatFor(chunkenc.ChunkFormatV4), 256000, 1500000) - _ = memChunk.Append(&push.Entry{ + _, _ = memChunk.Append(&push.Entry{ Timestamp: time.Unix(0, 1), Line: testLine, }) @@ -140,7 +140,7 @@ func TestBloomTokenizerPopulateWithoutPreexistingBloom(t *testing.T) { bt := NewBloomTokenizer(DefaultNGramLength, DefaultNGramSkip, 0, metrics) memChunk := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncSnappy, chunkenc.ChunkHeadFormatFor(chunkenc.ChunkFormatV4), 256000, 1500000) - _ = memChunk.Append(&push.Entry{ + _, _ = memChunk.Append(&push.Entry{ Timestamp: time.Unix(0, 1), Line: testLine, }) @@ -174,7 +174,7 @@ func TestBloomTokenizerPopulateWithoutPreexistingBloom(t *testing.T) { func chunkRefItrFromLines(lines ...string) (iter.EntryIterator, error) { memChunk := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncSnappy, chunkenc.ChunkHeadFormatFor(chunkenc.ChunkFormatV4), 256000, 1500000) for i, line := range lines { - if err := memChunk.Append(&push.Entry{ + if _, err := memChunk.Append(&push.Entry{ Timestamp: time.Unix(0, int64(i)), Line: line, }); err != nil { @@ -261,7 +261,7 @@ func BenchmarkPopulateSeriesWithBloom(b *testing.B) { sbf := filter.NewScalableBloomFilter(1024, 0.01, 0.8) memChunk := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncSnappy, chunkenc.ChunkHeadFormatFor(chunkenc.ChunkFormatV4), 256000, 1500000) - _ = memChunk.Append(&push.Entry{ + _, _ = memChunk.Append(&push.Entry{ Timestamp: time.Unix(0, 1), Line: testLine, }) diff --git a/pkg/storage/chunk/cache/cache_test.go b/pkg/storage/chunk/cache/cache_test.go index 23550dd34965e..c6ab61666b88d 100644 --- a/pkg/storage/chunk/cache/cache_test.go +++ b/pkg/storage/chunk/cache/cache_test.go @@ -36,7 +36,7 @@ func fillCache(t *testing.T, scfg config.SchemaConfig, cache cache.Cache) ([]str cs := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncGZIP, chunkenc.UnorderedWithStructuredMetadataHeadBlockFmt, 256*1024, 0) - err := cs.Append(&logproto.Entry{ + _, err := cs.Append(&logproto.Entry{ Timestamp: ts.Time(), Line: fmt.Sprintf("line ts=%d", ts), }) diff --git a/pkg/storage/chunk/client/testutils/testutils.go b/pkg/storage/chunk/client/testutils/testutils.go index 2b35b612badca..b34e75a6a166f 100644 --- a/pkg/storage/chunk/client/testutils/testutils.go +++ b/pkg/storage/chunk/client/testutils/testutils.go @@ -89,7 +89,7 @@ func DummyChunkFor(from, through model.Time, metric labels.Labels) chunk.Chunk { cs := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncGZIP, chunkenc.UnorderedWithStructuredMetadataHeadBlockFmt, 256*1024, 0) for ts := from; ts <= through; ts = ts.Add(15 * time.Second) { - err := cs.Append(&logproto.Entry{Timestamp: ts.Time(), Line: fmt.Sprintf("line ts=%d", ts)}) + _, err := cs.Append(&logproto.Entry{Timestamp: ts.Time(), Line: fmt.Sprintf("line ts=%d", ts)}) if err != nil { panic(err) } diff --git a/pkg/storage/chunk/fetcher/fetcher_test.go b/pkg/storage/chunk/fetcher/fetcher_test.go index 902b0dae1d743..03efc9afdc809 100644 --- a/pkg/storage/chunk/fetcher/fetcher_test.go +++ b/pkg/storage/chunk/fetcher/fetcher_test.go @@ -314,7 +314,7 @@ func makeChunks(now time.Time, tpls ...c) []chunk.Chunk { memChk := chunkenc.NewMemChunk(chunkenc.ChunkFormatV4, chunkenc.EncNone, chunkenc.UnorderedWithStructuredMetadataHeadBlockFmt, 256*1024, 0) // To make sure the fetcher doesn't swap keys and buffers each chunk is built with different, but deterministic data for i := 0; i < from; i++ { - _ = memChk.Append(&logproto.Entry{ + _, _ = memChk.Append(&logproto.Entry{ Timestamp: time.Unix(int64(i), 0), Line: fmt.Sprintf("line ts=%d", i), }) diff --git a/pkg/storage/hack/main.go b/pkg/storage/hack/main.go index f85e44a41ac5f..74257a8ba6ad0 100644 --- a/pkg/storage/hack/main.go +++ b/pkg/storage/hack/main.go @@ -110,7 +110,7 @@ func fillStore(cm storage.ClientMetrics) error { Line: randString(250), } if chunkEnc.SpaceFor(entry) { - _ = chunkEnc.Append(entry) + _, _ = chunkEnc.Append(entry) } else { from, to := chunkEnc.Bounds() c := chunk.NewChunk("fake", fp, metric, chunkenc.NewFacade(chunkEnc, 0, 0), model.TimeFromUnixNano(from.UnixNano()), model.TimeFromUnixNano(to.UnixNano())) diff --git a/pkg/storage/store_test.go b/pkg/storage/store_test.go index 51f04538cc189..13bcaa9688a91 100644 --- a/pkg/storage/store_test.go +++ b/pkg/storage/store_test.go @@ -2049,7 +2049,9 @@ func TestQueryReferencingStructuredMetadata(t *testing.T) { }, } } - require.NoError(t, chunkEnc.Append(&entry)) + dup, err := chunkEnc.Append(&entry) + require.False(t, dup) + require.NoError(t, err) } require.NoError(t, chunkEnc.Close()) diff --git a/pkg/storage/stores/series/series_store_test.go b/pkg/storage/stores/series/series_store_test.go index 15ecb1623eebb..553ea945f94f7 100644 --- a/pkg/storage/stores/series/series_store_test.go +++ b/pkg/storage/stores/series/series_store_test.go @@ -755,7 +755,8 @@ func dummyChunkWithFormat(t testing.TB, now model.Time, metric labels.Labels, fo chk := chunkenc.NewMemChunk(format, chunkenc.EncGZIP, headfmt, 256*1024, 0) for i := 0; i < samples; i++ { ts := time.Duration(i) * 15 * time.Second - err := chk.Append(&logproto.Entry{Timestamp: chunkStart.Time().Add(ts), Line: fmt.Sprintf("line %d", i)}) + dup, err := chk.Append(&logproto.Entry{Timestamp: chunkStart.Time().Add(ts), Line: fmt.Sprintf("line %d", i)}) + require.False(t, dup) require.NoError(t, err) } diff --git a/pkg/storage/stores/shipper/indexshipper/boltdb/compactor/util.go b/pkg/storage/stores/shipper/indexshipper/boltdb/compactor/util.go index 25ccb52e9b18e..6f1b0326a5cc6 100644 --- a/pkg/storage/stores/shipper/indexshipper/boltdb/compactor/util.go +++ b/pkg/storage/stores/shipper/indexshipper/boltdb/compactor/util.go @@ -34,10 +34,12 @@ func createChunk(t testing.TB, chunkFormat byte, headBlockFmt chunkenc.HeadBlock chunkEnc := chunkenc.NewMemChunk(chunkFormat, chunkenc.EncSnappy, headBlockFmt, blockSize, targetSize) for ts := from; !ts.After(through); ts = ts.Add(1 * time.Minute) { - require.NoError(t, chunkEnc.Append(&logproto.Entry{ + dup, err := chunkEnc.Append(&logproto.Entry{ Timestamp: ts.Time(), Line: ts.String(), - })) + }) + require.False(t, dup) + require.NoError(t, err) } require.NoError(t, chunkEnc.Close()) diff --git a/pkg/storage/util_test.go b/pkg/storage/util_test.go index 7c325cc4da6bb..5ef02e74b1caf 100644 --- a/pkg/storage/util_test.go +++ b/pkg/storage/util_test.go @@ -110,7 +110,7 @@ func newChunk(chunkFormat byte, headBlockFmt chunkenc.HeadBlockFmt, stream logpr from, through := loki_util.RoundToMilliseconds(stream.Entries[0].Timestamp, stream.Entries[len(stream.Entries)-1].Timestamp) chk := chunkenc.NewMemChunk(chunkFormat, chunkenc.EncGZIP, headBlockFmt, 256*1024, 0) for _, e := range stream.Entries { - _ = chk.Append(&e) + _, _ = chk.Append(&e) } chk.Close() c := chunk.NewChunk("fake", client.Fingerprint(lbs), lbs, chunkenc.NewFacade(chk, 0, 0), from, through)
feat
Collect duplicate log line metrics (#13084)
133c884d9e9e2749853e6784ae0768ad9a609d13
2025-03-06 03:06:21
renovate[bot]
fix(deps): update module golang.org/x/net to v0.37.0 (main) (#16582)
false
diff --git a/go.mod b/go.mod index 4954f38f54d22..6f86530456c66 100644 --- a/go.mod +++ b/go.mod @@ -100,7 +100,7 @@ require ( go.uber.org/atomic v1.11.0 go.uber.org/goleak v1.3.0 golang.org/x/crypto v0.36.0 - golang.org/x/net v0.36.0 + golang.org/x/net v0.37.0 golang.org/x/sync v0.12.0 golang.org/x/sys v0.31.0 golang.org/x/time v0.11.0 diff --git a/go.sum b/go.sum index 4462d86108504..ccedec2d1c2c0 100644 --- a/go.sum +++ b/go.sum @@ -1423,8 +1423,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= -golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= diff --git a/vendor/modules.txt b/vendor/modules.txt index 1b71209624ffc..5dc47a55a33c5 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1985,7 +1985,7 @@ golang.org/x/exp/slices # golang.org/x/mod v0.22.0 ## explicit; go 1.22.0 golang.org/x/mod/semver -# golang.org/x/net v0.36.0 +# golang.org/x/net v0.37.0 ## explicit; go 1.23.0 golang.org/x/net/bpf golang.org/x/net/context
fix
update module golang.org/x/net to v0.37.0 (main) (#16582)
8012362674568379a3871ff8c4a2bfd1ddba7ad1
2021-03-10 08:13:50
Ed Welch
loki: Per Tenant Runtime Configs (#3460)
false
diff --git a/cmd/loki/loki-local-config.yaml b/cmd/loki/loki-local-config.yaml index 0b45802732d00..6d39f98ae205e 100644 --- a/cmd/loki/loki-local-config.yaml +++ b/cmd/loki/loki-local-config.yaml @@ -2,6 +2,7 @@ auth_enabled: false server: http_listen_port: 3100 + grpc_listen_port: 9096 ingester: wal: diff --git a/pkg/distributor/distributor.go b/pkg/distributor/distributor.go index 7d916954efbed..e20ec7a233f18 100644 --- a/pkg/distributor/distributor.go +++ b/pkg/distributor/distributor.go @@ -27,6 +27,7 @@ import ( "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/logql" "github.com/grafana/loki/pkg/util" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -65,6 +66,7 @@ type Distributor struct { cfg Config clientCfg client.Config + tenantConfigs *runtime.TenantConfigs ingestersRing ring.ReadRing validator *Validator pool *ring_client.Pool @@ -82,7 +84,7 @@ type Distributor struct { } // New a distributor creates. -func New(cfg Config, clientCfg client.Config, ingestersRing ring.ReadRing, overrides *validation.Overrides, registerer prometheus.Registerer) (*Distributor, error) { +func New(cfg Config, clientCfg client.Config, configs *runtime.TenantConfigs, ingestersRing ring.ReadRing, overrides *validation.Overrides, registerer prometheus.Registerer) (*Distributor, error) { factory := cfg.factory if factory == nil { factory = func(addr string) (ring_client.PoolClient, error) { @@ -121,6 +123,7 @@ func New(cfg Config, clientCfg client.Config, ingestersRing ring.ReadRing, overr d := Distributor{ cfg: cfg, clientCfg: clientCfg, + tenantConfigs: configs, ingestersRing: ingestersRing, distributorsRing: distributorsRing, validator: validator, diff --git a/pkg/distributor/distributor_test.go b/pkg/distributor/distributor_test.go index 5b4ac06dd5247..9dfab1dfc4b27 100644 --- a/pkg/distributor/distributor_test.go +++ b/pkg/distributor/distributor_test.go @@ -31,6 +31,7 @@ import ( "github.com/grafana/loki/pkg/ingester/client" "github.com/grafana/loki/pkg/logproto" fe "github.com/grafana/loki/pkg/util/flagext" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -313,7 +314,7 @@ func prepare(t *testing.T, limits *validation.Limits, kvStore kv.Client, factory } } - d, err := New(distributorConfig, clientConfig, ingestersRing, overrides, nil) + d, err := New(distributorConfig, clientConfig, runtime.DefaultTenantConfigs(), ingestersRing, overrides, nil) require.NoError(t, err) require.NoError(t, services.StartAndAwaitRunning(context.Background(), d)) diff --git a/pkg/distributor/http.go b/pkg/distributor/http.go index c663488a4cb68..8928ca066bad6 100644 --- a/pkg/distributor/http.go +++ b/pkg/distributor/http.go @@ -5,11 +5,13 @@ import ( "fmt" "math" "net/http" + "strings" "time" "github.com/cortexproject/cortex/pkg/util" util_log "github.com/cortexproject/cortex/pkg/util/log" "github.com/dustin/go-humanize" + gokit "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -43,29 +45,67 @@ const applicationJSON = "application/json" // PushHandler reads a snappy-compressed proto from the HTTP body. func (d *Distributor) PushHandler(w http.ResponseWriter, r *http.Request) { - req, err := ParseRequest(r) + logger := util_log.WithContext(r.Context(), util_log.Logger) + userID, _ := user.ExtractOrgID(r.Context()) + req, err := ParseRequest(logger, userID, r) if err != nil { + if d.tenantConfigs.LogPushRequest(userID) { + level.Debug(logger).Log( + "msg", "push request failed", + "code", http.StatusBadRequest, + "err", err, + ) + } http.Error(w, err.Error(), http.StatusBadRequest) return } + if d.tenantConfigs.LogPushRequestStreams(userID) { + var sb strings.Builder + for _, s := range req.Streams { + sb.WriteString(s.Labels) + } + level.Debug(logger).Log( + "msg", "push request streams", + "streams", sb.String(), + ) + } + _, err = d.Push(r.Context(), req) if err == nil { + if d.tenantConfigs.LogPushRequest(userID) { + level.Debug(logger).Log( + "msg", "push request successful", + ) + } w.WriteHeader(http.StatusNoContent) return } resp, ok := httpgrpc.HTTPResponseFromError(err) if ok { - http.Error(w, string(resp.Body), int(resp.Code)) + body := string(resp.Body) + if d.tenantConfigs.LogPushRequest(userID) { + level.Debug(logger).Log( + "msg", "push request failed", + "code", resp.Code, + "err", body, + ) + } + http.Error(w, body, int(resp.Code)) } else { + if d.tenantConfigs.LogPushRequest(userID) { + level.Debug(logger).Log( + "msg", "push request failed", + "code", http.StatusInternalServerError, + "err", err.Error(), + ) + } http.Error(w, err.Error(), http.StatusInternalServerError) } } -func ParseRequest(r *http.Request) (*logproto.PushRequest, error) { - userID, _ := user.ExtractOrgID(r.Context()) - logger := util_log.WithContext(r.Context(), util_log.Logger) +func ParseRequest(logger gokit.Logger, userID string, r *http.Request) (*logproto.PushRequest, error) { var body lokiutil.SizeReader diff --git a/pkg/distributor/http_test.go b/pkg/distributor/http_test.go index a17ebffcb7488..0f68eb5e082a4 100644 --- a/pkg/distributor/http_test.go +++ b/pkg/distributor/http_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + util_log "github.com/cortexproject/cortex/pkg/util/log" "github.com/stretchr/testify/assert" ) @@ -75,7 +76,7 @@ func TestParseRequest(t *testing.T) { if len(test.contentEncoding) > 0 { request.Header.Add("Content-Encoding", test.contentEncoding) } - data, err := ParseRequest(request) + data, err := ParseRequest(util_log.Logger, "", request) if test.valid { assert.Nil(t, err, "Should not give error for %d", index) assert.NotNil(t, data, "Should give data for %d", index) diff --git a/pkg/ingester/checkpoint_test.go b/pkg/ingester/checkpoint_test.go index 5aadc50290339..e0063067e26cb 100644 --- a/pkg/ingester/checkpoint_test.go +++ b/pkg/ingester/checkpoint_test.go @@ -21,6 +21,7 @@ import ( "github.com/grafana/loki/pkg/ingester/client" "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/logql/log" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -70,7 +71,7 @@ func TestIngesterWAL(t *testing.T) { } } - i, err := New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err := New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck @@ -113,7 +114,7 @@ func TestIngesterWAL(t *testing.T) { expectCheckpoint(t, walDir, false, time.Second) // restart the ingester - i, err = New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err = New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) @@ -127,7 +128,7 @@ func TestIngesterWAL(t *testing.T) { require.Nil(t, services.StopAndAwaitTerminated(context.Background(), i)) // restart the ingester - i, err = New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err = New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) @@ -152,7 +153,7 @@ func TestIngesterWALIgnoresStreamLimits(t *testing.T) { } } - i, err := New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err := New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck @@ -198,7 +199,7 @@ func TestIngesterWALIgnoresStreamLimits(t *testing.T) { require.NoError(t, err) // restart the ingester - i, err = New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err = New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) @@ -258,7 +259,7 @@ func TestIngesterWALBackpressureSegments(t *testing.T) { } } - i, err := New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err := New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck @@ -279,7 +280,7 @@ func TestIngesterWALBackpressureSegments(t *testing.T) { expectCheckpoint(t, walDir, false, time.Second) // restart the ingester, ensuring we replayed from WAL. - i, err = New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err = New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) @@ -303,7 +304,7 @@ func TestIngesterWALBackpressureCheckpoint(t *testing.T) { } } - i, err := New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err := New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck @@ -324,7 +325,7 @@ func TestIngesterWALBackpressureCheckpoint(t *testing.T) { require.Nil(t, services.StopAndAwaitTerminated(context.Background(), i)) // restart the ingester, ensuring we can replay from the checkpoint as well. - i, err = New(ingesterConfig, client.Config{}, newStore(), limits, nil) + i, err = New(ingesterConfig, client.Config{}, newStore(), limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck require.Nil(t, services.StartAndAwaitRunning(context.Background(), i)) @@ -455,7 +456,7 @@ func Test_SeriesIterator(t *testing.T) { limiter := NewLimiter(limits, &ringCountMock{count: 1}, 1) for i := 0; i < 3; i++ { - inst := newInstance(defaultConfig(), fmt.Sprintf("%d", i), limiter, noopWAL{}, NilMetrics, nil) + inst := newInstance(defaultConfig(), fmt.Sprintf("%d", i), limiter, runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, nil) require.NoError(t, inst.Push(context.Background(), &logproto.PushRequest{Streams: []logproto.Stream{stream1}})) require.NoError(t, inst.Push(context.Background(), &logproto.PushRequest{Streams: []logproto.Stream{stream2}})) instances = append(instances, inst) @@ -505,7 +506,7 @@ func Benchmark_SeriesIterator(b *testing.B) { limiter := NewLimiter(limits, &ringCountMock{count: 1}, 1) for i := range instances { - inst := newInstance(defaultConfig(), fmt.Sprintf("instance %d", i), limiter, noopWAL{}, NilMetrics, nil) + inst := newInstance(defaultConfig(), fmt.Sprintf("instance %d", i), limiter, nil, noopWAL{}, NilMetrics, nil) require.NoError(b, inst.Push(context.Background(), &logproto.PushRequest{ diff --git a/pkg/ingester/flush_test.go b/pkg/ingester/flush_test.go index 982d4bce1f092..f59871ed97168 100644 --- a/pkg/ingester/flush_test.go +++ b/pkg/ingester/flush_test.go @@ -12,6 +12,7 @@ import ( "github.com/grafana/loki/pkg/logql" "github.com/grafana/loki/pkg/logql/log" + "github.com/grafana/loki/pkg/util/runtime" "github.com/cortexproject/cortex/pkg/chunk" "github.com/cortexproject/cortex/pkg/ring" @@ -257,7 +258,7 @@ func newTestStore(t require.TestingT, cfg Config, walOverride WAL) (*testStore, limits, err := validation.NewOverrides(defaultLimitsTestConfig(), nil) require.NoError(t, err) - ing, err := New(cfg, client.Config{}, store, limits, nil) + ing, err := New(cfg, client.Config{}, store, limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) require.NoError(t, services.StartAndAwaitRunning(context.Background(), ing)) diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index 9a05f4186b7b4..81cf22dadaf9d 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -34,6 +34,7 @@ import ( "github.com/grafana/loki/pkg/storage/stores/shipper" errUtil "github.com/grafana/loki/pkg/util" listutil "github.com/grafana/loki/pkg/util" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -121,8 +122,9 @@ func (cfg *Config) Validate() error { type Ingester struct { services.Service - cfg Config - clientConfig client.Config + cfg Config + clientConfig client.Config + tenantConfigs *runtime.TenantConfigs shutdownMtx sync.Mutex // Allows processes to grab a lock and prevent a shutdown instancesMtx sync.RWMutex @@ -168,7 +170,7 @@ type ChunkStore interface { } // New makes a new Ingester. -func New(cfg Config, clientConfig client.Config, store ChunkStore, limits *validation.Overrides, registerer prometheus.Registerer) (*Ingester, error) { +func New(cfg Config, clientConfig client.Config, store ChunkStore, limits *validation.Overrides, configs *runtime.TenantConfigs, registerer prometheus.Registerer) (*Ingester, error) { if cfg.ingesterClientFactory == nil { cfg.ingesterClientFactory = client.New } @@ -178,6 +180,7 @@ func New(cfg Config, clientConfig client.Config, store ChunkStore, limits *valid i := &Ingester{ cfg: cfg, clientConfig: clientConfig, + tenantConfigs: configs, instances: map[string]*instance{}, store: store, periodicConfigs: store.GetSchemaConfigs(), @@ -401,7 +404,7 @@ func (i *Ingester) getOrCreateInstance(instanceID string) *instance { defer i.instancesMtx.Unlock() inst, ok = i.instances[instanceID] if !ok { - inst = newInstance(&i.cfg, instanceID, i.limiter, i.wal, i.metrics, i.flushOnShutdownSwitch) + inst = newInstance(&i.cfg, instanceID, i.limiter, i.tenantConfigs, i.wal, i.metrics, i.flushOnShutdownSwitch) i.instances[instanceID] = inst } return inst diff --git a/pkg/ingester/ingester_test.go b/pkg/ingester/ingester_test.go index 98b8bba0b65de..36743044af3d0 100644 --- a/pkg/ingester/ingester_test.go +++ b/pkg/ingester/ingester_test.go @@ -25,6 +25,7 @@ import ( "github.com/grafana/loki/pkg/iter" "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/logql" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -37,7 +38,7 @@ func TestIngester(t *testing.T) { chunks: map[string][]chunk.Chunk{}, } - i, err := New(ingesterConfig, client.Config{}, store, limits, nil) + i, err := New(ingesterConfig, client.Config{}, store, limits, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck @@ -219,7 +220,7 @@ func TestIngesterStreamLimitExceeded(t *testing.T) { chunks: map[string][]chunk.Chunk{}, } - i, err := New(ingesterConfig, client.Config{}, store, overrides, nil) + i, err := New(ingesterConfig, client.Config{}, store, overrides, runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) defer services.StopAndAwaitTerminated(context.Background(), i) //nolint:errcheck diff --git a/pkg/ingester/instance.go b/pkg/ingester/instance.go index 268e002d797d0..c98ebb8cf9551 100644 --- a/pkg/ingester/instance.go +++ b/pkg/ingester/instance.go @@ -28,6 +28,7 @@ import ( "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/logql" "github.com/grafana/loki/pkg/logql/stats" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -79,6 +80,7 @@ type instance struct { tailerMtx sync.RWMutex limiter *Limiter + configs *runtime.TenantConfigs wal WAL @@ -89,14 +91,7 @@ type instance struct { metrics *ingesterMetrics } -func newInstance( - cfg *Config, - instanceID string, - limiter *Limiter, - wal WAL, - metrics *ingesterMetrics, - flushOnShutdownSwitch *OnceSwitch, -) *instance { +func newInstance(cfg *Config, instanceID string, limiter *Limiter, configs *runtime.TenantConfigs, wal WAL, metrics *ingesterMetrics, flushOnShutdownSwitch *OnceSwitch) *instance { i := &instance{ cfg: cfg, streams: map[string]*stream{}, @@ -110,6 +105,7 @@ func newInstance( tailers: map[uint32]*tailer{}, limiter: limiter, + configs: configs, wal: wal, metrics: metrics, @@ -209,6 +205,15 @@ func (i *instance) getOrCreateStream(pushReqStream logproto.Stream, lock bool, r } if err != nil { + if i.configs.LogStreamCreation(i.instanceID) { + level.Debug(util_log.Logger).Log( + "msg", "failed to create stream, exceeded limit", + "org_id", i.instanceID, + "err", err, + "stream", pushReqStream.Labels, + ) + } + validation.DiscardedSamples.WithLabelValues(validation.StreamLimit, i.instanceID).Add(float64(len(pushReqStream.Entries))) bytes := 0 for _, e := range pushReqStream.Entries { @@ -220,6 +225,14 @@ func (i *instance) getOrCreateStream(pushReqStream logproto.Stream, lock bool, r labels, err := logql.ParseLabels(pushReqStream.Labels) if err != nil { + if i.configs.LogStreamCreation(i.instanceID) { + level.Debug(util_log.Logger).Log( + "msg", "failed to create stream, failed to parse labels", + "org_id", i.instanceID, + "err", err, + "stream", pushReqStream.Labels, + ) + } return nil, httpgrpc.Errorf(http.StatusBadRequest, err.Error()) } fp := i.getHashForLabels(labels) @@ -244,6 +257,14 @@ func (i *instance) getOrCreateStream(pushReqStream logproto.Stream, lock bool, r i.streamsCreatedTotal.Inc() i.addTailersToNewStream(stream) + if i.configs.LogStreamCreation(i.instanceID) { + level.Debug(util_log.Logger).Log( + "msg", "successfully created stream", + "org_id", i.instanceID, + "stream", pushReqStream.Labels, + ) + } + return stream, nil } diff --git a/pkg/ingester/instance_test.go b/pkg/ingester/instance_test.go index 7ce0bcf2946fb..c7e04fc255a06 100644 --- a/pkg/ingester/instance_test.go +++ b/pkg/ingester/instance_test.go @@ -17,6 +17,7 @@ import ( "github.com/grafana/loki/pkg/iter" "github.com/grafana/loki/pkg/logproto" "github.com/grafana/loki/pkg/logql" + loki_runtime "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -38,7 +39,7 @@ func TestLabelsCollisions(t *testing.T) { require.NoError(t, err) limiter := NewLimiter(limits, &ringCountMock{count: 1}, 1) - i := newInstance(defaultConfig(), "test", limiter, noopWAL{}, nil, &OnceSwitch{}) + i := newInstance(defaultConfig(), "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, nil, &OnceSwitch{}) // avoid entries from the future. tt := time.Now().Add(-5 * time.Minute) @@ -65,7 +66,7 @@ func TestConcurrentPushes(t *testing.T) { require.NoError(t, err) limiter := NewLimiter(limits, &ringCountMock{count: 1}, 1) - inst := newInstance(defaultConfig(), "test", limiter, noopWAL{}, NilMetrics, &OnceSwitch{}) + inst := newInstance(defaultConfig(), "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, &OnceSwitch{}) const ( concurrent = 10 @@ -123,7 +124,7 @@ func TestSyncPeriod(t *testing.T) { minUtil = 0.20 ) - inst := newInstance(defaultConfig(), "test", limiter, noopWAL{}, NilMetrics, &OnceSwitch{}) + inst := newInstance(defaultConfig(), "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, &OnceSwitch{}) lbls := makeRandomLabels() tt := time.Now() @@ -163,7 +164,7 @@ func Test_SeriesQuery(t *testing.T) { cfg.SyncPeriod = 1 * time.Minute cfg.SyncMinUtilization = 0.20 - instance := newInstance(cfg, "test", limiter, noopWAL{}, NilMetrics, &OnceSwitch{}) + instance := newInstance(cfg, "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, &OnceSwitch{}) currentTime := time.Now() @@ -273,7 +274,7 @@ func Benchmark_PushInstance(b *testing.B) { require.NoError(b, err) limiter := NewLimiter(limits, &ringCountMock{count: 1}, 1) - i := newInstance(&Config{}, "test", limiter, noopWAL{}, NilMetrics, &OnceSwitch{}) + i := newInstance(&Config{}, "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, &OnceSwitch{}) ctx := context.Background() for n := 0; n < b.N; n++ { @@ -315,7 +316,7 @@ func Benchmark_instance_addNewTailer(b *testing.B) { ctx := context.Background() - inst := newInstance(&Config{}, "test", limiter, noopWAL{}, NilMetrics, &OnceSwitch{}) + inst := newInstance(&Config{}, "test", limiter, loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, &OnceSwitch{}) t, err := newTailer("foo", `{namespace="foo",pod="bar",instance=~"10.*"}`, nil) require.NoError(b, err) for i := 0; i < 10000; i++ { @@ -365,7 +366,7 @@ func Test_Iterator(t *testing.T) { defaultLimits := defaultLimitsTestConfig() overrides, err := validation.NewOverrides(defaultLimits, nil) require.NoError(t, err) - instance := newInstance(&ingesterConfig, "fake", NewLimiter(overrides, &ringCountMock{count: 1}, 1), noopWAL{}, NilMetrics, nil) + instance := newInstance(&ingesterConfig, "fake", NewLimiter(overrides, &ringCountMock{count: 1}, 1), loki_runtime.DefaultTenantConfigs(), noopWAL{}, NilMetrics, nil) ctx := context.TODO() direction := logproto.BACKWARD limit := uint32(2) diff --git a/pkg/ingester/recovery_test.go b/pkg/ingester/recovery_test.go index 39a3f9149e6db..a26533f633bcc 100644 --- a/pkg/ingester/recovery_test.go +++ b/pkg/ingester/recovery_test.go @@ -17,6 +17,7 @@ import ( "github.com/grafana/loki/pkg/ingester/client" "github.com/grafana/loki/pkg/logproto" + loki_runtime "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -205,7 +206,7 @@ func TestSeriesRecoveryNoDuplicates(t *testing.T) { chunks: map[string][]chunk.Chunk{}, } - i, err := New(ingesterConfig, client.Config{}, store, limits, nil) + i, err := New(ingesterConfig, client.Config{}, store, limits, loki_runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) mkSample := func(i int) *logproto.PushRequest { @@ -239,7 +240,7 @@ func TestSeriesRecoveryNoDuplicates(t *testing.T) { require.Equal(t, false, iter.Next()) // create a new ingester now - i, err = New(ingesterConfig, client.Config{}, store, limits, nil) + i, err = New(ingesterConfig, client.Config{}, store, limits, loki_runtime.DefaultTenantConfigs(), nil) require.NoError(t, err) // recover the checkpointed series diff --git a/pkg/loki/loki.go b/pkg/loki/loki.go index 2e2d384a9adfd..12ba1d4f83f5c 100644 --- a/pkg/loki/loki.go +++ b/pkg/loki/loki.go @@ -12,6 +12,7 @@ import ( "github.com/felixge/fgprof" "github.com/grafana/loki/pkg/storage/stores/shipper/compactor" + "github.com/grafana/loki/pkg/util/runtime" "github.com/cortexproject/cortex/pkg/util/flagext" "github.com/cortexproject/cortex/pkg/util/modules" @@ -145,6 +146,7 @@ type Loki struct { Server *server.Server ring *ring.Ring overrides *validation.Overrides + tenantConfigs *runtime.TenantConfigs distributor *distributor.Distributor ingester *ingester.Ingester querier *querier.Querier @@ -344,6 +346,7 @@ func (t *Loki) setupModuleManager() error { mm.RegisterModule(MemberlistKV, t.initMemberlistKV) mm.RegisterModule(Ring, t.initRing) mm.RegisterModule(Overrides, t.initOverrides) + mm.RegisterModule(TenantConfigs, t.initTenantConfigs) mm.RegisterModule(Distributor, t.initDistributor) mm.RegisterModule(Store, t.initStore) mm.RegisterModule(Ingester, t.initIngester) @@ -360,12 +363,13 @@ func (t *Loki) setupModuleManager() error { deps := map[string][]string{ Ring: {RuntimeConfig, Server, MemberlistKV}, Overrides: {RuntimeConfig}, - Distributor: {Ring, Server, Overrides}, + TenantConfigs: {RuntimeConfig}, + Distributor: {Ring, Server, Overrides, TenantConfigs}, Store: {Overrides}, - Ingester: {Store, Server, MemberlistKV}, - Querier: {Store, Ring, Server, IngesterQuerier}, - QueryFrontend: {Server, Overrides}, - Ruler: {Ring, Server, Store, RulerStorage, IngesterQuerier, Overrides}, + Ingester: {Store, Server, MemberlistKV, TenantConfigs}, + Querier: {Store, Ring, Server, IngesterQuerier, TenantConfigs}, + QueryFrontend: {Server, Overrides, TenantConfigs}, + Ruler: {Ring, Server, Store, RulerStorage, IngesterQuerier, Overrides, TenantConfigs}, TableManager: {Server}, Compactor: {Server}, IngesterQuerier: {Ring}, diff --git a/pkg/loki/modules.go b/pkg/loki/modules.go index 52f522ac1af36..51b241bdf1917 100644 --- a/pkg/loki/modules.go +++ b/pkg/loki/modules.go @@ -16,6 +16,7 @@ import ( "github.com/grafana/loki/pkg/ruler/manager" "github.com/grafana/loki/pkg/storage/stores/shipper/compactor" + "github.com/grafana/loki/pkg/util/runtime" "github.com/cortexproject/cortex/pkg/chunk" "github.com/cortexproject/cortex/pkg/chunk/cache" @@ -60,6 +61,7 @@ const ( Ring string = "ring" RuntimeConfig string = "runtime-config" Overrides string = "overrides" + TenantConfigs string = "tenant-configs" Server string = "server" Distributor string = "distributor" Ingester string = "ingester" @@ -140,11 +142,17 @@ func (t *Loki) initOverrides() (_ services.Service, err error) { return nil, err } +func (t *Loki) initTenantConfigs() (_ services.Service, err error) { + t.tenantConfigs, err = runtime.NewTenantConfigs(tenantConfigFromRuntimeConfig(t.runtimeConfig)) + // tenantConfigs are not a service, since they don't have any operational state. + return nil, err +} + func (t *Loki) initDistributor() (services.Service, error) { t.cfg.Distributor.DistributorRing.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.cfg.Distributor.DistributorRing.KVStore.MemberlistKV = t.memberlistKV.GetMemberlistKV var err error - t.distributor, err = distributor.New(t.cfg.Distributor, t.cfg.IngesterClient, t.ring, t.overrides, prometheus.DefaultRegisterer) + t.distributor, err = distributor.New(t.cfg.Distributor, t.cfg.IngesterClient, t.tenantConfigs, t.ring, t.overrides, prometheus.DefaultRegisterer) if err != nil { return nil, err } @@ -218,7 +226,7 @@ func (t *Loki) initIngester() (_ services.Service, err error) { t.cfg.Ingester.LifecyclerConfig.RingConfig.KVStore.MemberlistKV = t.memberlistKV.GetMemberlistKV t.cfg.Ingester.LifecyclerConfig.ListenPort = t.cfg.Server.GRPCListenPort - t.ingester, err = ingester.New(t.cfg.Ingester, t.cfg.IngesterClient, t.store, t.overrides, prometheus.DefaultRegisterer) + t.ingester, err = ingester.New(t.cfg.Ingester, t.cfg.IngesterClient, t.store, t.overrides, t.tenantConfigs, prometheus.DefaultRegisterer) if err != nil { return } diff --git a/pkg/loki/runtime_config.go b/pkg/loki/runtime_config.go index 99ea284f34eb6..2f753df774af2 100644 --- a/pkg/loki/runtime_config.go +++ b/pkg/loki/runtime_config.go @@ -7,6 +7,7 @@ import ( "github.com/cortexproject/cortex/pkg/util/runtimeconfig" "gopkg.in/yaml.v2" + "github.com/grafana/loki/pkg/util/runtime" "github.com/grafana/loki/pkg/util/validation" ) @@ -15,6 +16,7 @@ import ( // These values are then pushed to the components that are interested in them. type runtimeConfigValues struct { TenantLimits map[string]*validation.Limits `yaml:"overrides"` + TenantConfig map[string]*runtime.Config `yaml:"configs"` Multi kv.MultiRuntimeConfig `yaml:"multi_kv_config"` } @@ -45,6 +47,19 @@ func tenantLimitsFromRuntimeConfig(c *runtimeconfig.Manager) validation.TenantLi } } +func tenantConfigFromRuntimeConfig(c *runtimeconfig.Manager) runtime.TenantConfig { + if c == nil { + return nil + } + return func(userID string) *runtime.Config { + cfg, ok := c.GetConfig().(*runtimeConfigValues) + if !ok || cfg == nil { + return nil + } + return cfg.TenantConfig[userID] + } +} + func multiClientRuntimeConfigChannel(manager *runtimeconfig.Manager) func() <-chan kv.MultiRuntimeConfig { if manager == nil { return nil diff --git a/pkg/promtail/targets/lokipush/pushtarget.go b/pkg/promtail/targets/lokipush/pushtarget.go index 9c3ea6d936cae..a2d488dbeeba7 100644 --- a/pkg/promtail/targets/lokipush/pushtarget.go +++ b/pkg/promtail/targets/lokipush/pushtarget.go @@ -14,6 +14,7 @@ import ( "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/relabel" "github.com/weaveworks/common/server" + "github.com/weaveworks/common/user" "github.com/grafana/loki/pkg/distributor" "github.com/grafana/loki/pkg/logproto" @@ -102,7 +103,9 @@ func (t *PushTarget) run() error { } func (t *PushTarget) handle(w http.ResponseWriter, r *http.Request) { - req, err := distributor.ParseRequest(r) + logger := util_log.WithContext(r.Context(), util_log.Logger) + userID, _ := user.ExtractOrgID(r.Context()) + req, err := distributor.ParseRequest(logger, userID, r) if err != nil { level.Warn(t.logger).Log("msg", "failed to parse incoming push request", "err", err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) diff --git a/pkg/util/runtime/config.go b/pkg/util/runtime/config.go new file mode 100644 index 0000000000000..110a9fce2a8df --- /dev/null +++ b/pkg/util/runtime/config.go @@ -0,0 +1,56 @@ +package runtime + +type Config struct { + LogStreamCreation bool `yaml:"log_stream_creation"` + LogPushRequest bool `yaml:"log_push_request"` + LogPushRequestStreams bool `yaml:"log_push_request_streams"` +} + +// TenantConfig is a function that returns configs for given tenant, or +// nil, if there are no tenant-specific configs. +type TenantConfig func(userID string) *Config + +// TenantConfigs periodically fetch a set of per-user configs, and provides convenience +// functions for fetching the correct value. +type TenantConfigs struct { + defaultConfig *Config + tenantConfig TenantConfig +} + +// DefaultTenantConfigs creates and returns a new TenantConfigs with the defaults populated. +func DefaultTenantConfigs() *TenantConfigs { + return &TenantConfigs{ + defaultConfig: &Config{}, + tenantConfig: nil, + } +} + +// NewTenantConfig makes a new TenantConfigs +func NewTenantConfigs(tenantConfig TenantConfig) (*TenantConfigs, error) { + return &TenantConfigs{ + defaultConfig: DefaultTenantConfigs().defaultConfig, + tenantConfig: tenantConfig, + }, nil +} + +func (o *TenantConfigs) getOverridesForUser(userID string) *Config { + if o.tenantConfig != nil { + l := o.tenantConfig(userID) + if l != nil { + return l + } + } + return o.defaultConfig +} + +func (o *TenantConfigs) LogStreamCreation(userID string) bool { + return o.getOverridesForUser(userID).LogStreamCreation +} + +func (o *TenantConfigs) LogPushRequest(userID string) bool { + return o.getOverridesForUser(userID).LogPushRequest +} + +func (o *TenantConfigs) LogPushRequestStreams(userID string) bool { + return o.getOverridesForUser(userID).LogPushRequestStreams +}
loki
Per Tenant Runtime Configs (#3460)
cbdd36a41282bf85ab1007ca1a6a8a227608c40b
2024-11-22 16:11:38
Owen Diehl
feat: blockbuilder component (#14621)
false
diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index 203d7130232a7..5fd2850f229dc 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -137,6 +137,57 @@ Pass the `-config.expand-env` flag at the command line to enable this way of set # itself to a key value store. [ingester: <ingester>] +block_builder: + # How many flushes can happen concurrently + # CLI flag: -blockbuilder.concurrent-flushes + [concurrent_flushes: <int> | default = 1] + + # How many workers to process writes, defaults to number of available cpus + # CLI flag: -blockbuilder.concurrent-writers + [concurrent_writers: <int> | default = 1] + + # The targeted _uncompressed_ size in bytes of a chunk block When this + # threshold is exceeded the head block will be cut and compressed inside the + # chunk. + # CLI flag: -blockbuilder.chunks-block-size + [chunk_block_size: <int> | default = 256KB] + + # A target _compressed_ size in bytes for chunks. This is a desired size not + # an exact size, chunks may be slightly bigger or significantly smaller if + # they get flushed for other reasons (e.g. chunk_idle_period). A value of 0 + # creates chunks with a fixed 10 blocks, a non zero value will create chunks + # with a variable number of blocks to meet the target size. + # CLI flag: -blockbuilder.chunk-target-size + [chunk_target_size: <int> | default = 1536KB] + + # The algorithm to use for compressing chunk. (none, gzip, lz4-64k, snappy, + # lz4-256k, lz4-1M, lz4, flate, zstd) + # CLI flag: -blockbuilder.chunk-encoding + [chunk_encoding: <string> | default = "snappy"] + + # The maximum duration of a timeseries chunk in memory. If a timeseries runs + # for longer than this, the current chunk will be flushed to the store and a + # new chunk created. + # CLI flag: -blockbuilder.max-chunk-age + [max_chunk_age: <duration> | default = 2h] + + # The interval at which to run. + # CLI flag: -blockbuilder.interval + [interval: <duration> | default = 10m] + + backoff_config: + # Minimum delay when backing off. + # CLI flag: -blockbuilder.backoff..backoff-min-period + [min_period: <duration> | default = 100ms] + + # Maximum delay when backing off. + # CLI flag: -blockbuilder.backoff..backoff-max-period + [max_period: <duration> | default = 10s] + + # Number of times to backoff and retry before failing. + # CLI flag: -blockbuilder.backoff..backoff-retries + [max_retries: <int> | default = 10] + pattern_ingester: # Whether the pattern ingester is enabled. # CLI flag: -pattern-ingester.enabled diff --git a/pkg/blockbuilder/controller.go b/pkg/blockbuilder/controller.go new file mode 100644 index 0000000000000..f252b3d657444 --- /dev/null +++ b/pkg/blockbuilder/controller.go @@ -0,0 +1,305 @@ +package blockbuilder + +import ( + "context" + "fmt" + "time" + + "github.com/prometheus/prometheus/model/labels" + + "github.com/grafana/dskit/backoff" + + "github.com/grafana/loki/v3/pkg/kafka" + "github.com/grafana/loki/v3/pkg/kafka/partition" + + "github.com/grafana/loki/pkg/push" +) + +// [min,max) +type Offsets struct { + Min, Max int64 +} + +type Job struct { + Partition int32 + Offsets Offsets +} + +// Interface required for interacting with queue partitions. +type PartitionController interface { + Topic() string + Partition() int32 + // Returns the highest committed offset from the consumer group + HighestCommittedOffset(ctx context.Context) (int64, error) + // Returns the highest available offset in the partition + HighestPartitionOffset(ctx context.Context) (int64, error) + // Returns the earliest available offset in the partition + EarliestPartitionOffset(ctx context.Context) (int64, error) + // Commits the offset to the consumer group. + Commit(context.Context, int64) error + // Process will run load batches at a time and send them to channel, + // so it's advised to not buffer the channel for natural backpressure. + // As a convenience, it returns the last seen offset, which matches + // the final record sent on the channel. + Process(context.Context, Offsets, chan<- []AppendInput) (int64, error) + + Close() error +} + +// PartitionJobController loads a single job a time, bound to a given +// * topic +// * partition +// * offset_step_len: the number of offsets each job to contain. e.g. "10" could yield a job w / min=15, max=25 +// +// At a high level, it watches a source topic/partition (where log data is ingested) and a "committed" topic/partition. +// The "committed" partition corresponds to the offsets from the source partition which have been committed to object storage. +// In essence, the following loop is performed +// 1. load the most recent record from the "committed" partition. This contains the highest msg offset in the "source" partition +// that has been committed to object storage. We'll call that $START_POS. +// 2. Create a job with `min=$START_POS+1,end=$START_POS+1+$STEP_LEN` +// 3. Sometime later when the job has been processed, we'll commit the final processed offset from the "source" partition (which +// will be <= $END_POS) to the "committed" partition. +// +// NB(owen-d): In our case, "source" is the partition +// +// containing log data and "committed" is the consumer group +type PartitionJobController struct { + stepLen int64 + part partition.ReaderIfc + backoff backoff.Config + decoder *kafka.Decoder +} + +func NewPartitionJobController( + controller partition.ReaderIfc, + backoff backoff.Config, +) (*PartitionJobController, error) { + decoder, err := kafka.NewDecoder() + if err != nil { + return nil, err + } + return &PartitionJobController{ + stepLen: 1000, // Default step length of 1000 offsets per job + part: controller, + backoff: backoff, + decoder: decoder, + }, nil +} + +func (l *PartitionJobController) HighestCommittedOffset(ctx context.Context) (int64, error) { + return withBackoff( + ctx, + l.backoff, + func() (int64, error) { + return l.part.FetchLastCommittedOffset(ctx) + }, + ) +} + +func (l *PartitionJobController) HighestPartitionOffset(ctx context.Context) (int64, error) { + return withBackoff( + ctx, + l.backoff, + func() (int64, error) { + return l.part.FetchPartitionOffset(ctx, partition.KafkaEndOffset) + }, + ) +} + +func (l *PartitionJobController) EarliestPartitionOffset(ctx context.Context) (int64, error) { + return withBackoff( + ctx, + l.backoff, + func() (int64, error) { + return l.part.FetchPartitionOffset(ctx, partition.KafkaStartOffset) + }, + ) +} + +func (l *PartitionJobController) Process(ctx context.Context, offsets Offsets, ch chan<- []AppendInput) (int64, error) { + l.part.SetOffsetForConsumption(offsets.Min) + + var ( + lastOffset = offsets.Min - 1 + boff = backoff.New(ctx, l.backoff) + err error + ) + + for boff.Ongoing() { + var records []partition.Record + records, err = l.part.Poll(ctx) + if err != nil { + boff.Wait() + continue + } + + if len(records) == 0 { + // No more records available + break + } + + // Reset backoff on successful poll + boff.Reset() + + converted := make([]AppendInput, 0, len(records)) + for _, record := range records { + offset := records[len(records)-1].Offset + if offset >= offsets.Max { + break + } + lastOffset = offset + + stream, labels, err := l.decoder.Decode(record.Content) + if err != nil { + return 0, fmt.Errorf("failed to decode record: %w", err) + } + if len(stream.Entries) == 0 { + continue + } + + converted = append(converted, AppendInput{ + tenant: record.TenantID, + labels: labels, + labelsStr: stream.Labels, + entries: stream.Entries, + }) + + select { + case ch <- converted: + case <-ctx.Done(): + return 0, ctx.Err() + } + } + } + + return lastOffset, err +} + +// LoadJob(ctx) returns the next job by finding the most recent unconsumed offset in the partition +// Returns whether an applicable job exists, the job, and an error +func (l *PartitionJobController) LoadJob(ctx context.Context) (bool, Job, error) { + // Read the most recent committed offset + committedOffset, err := l.HighestCommittedOffset(ctx) + if err != nil { + return false, Job{}, err + } + + earliestOffset, err := l.EarliestPartitionOffset(ctx) + if err != nil { + return false, Job{}, err + } + + startOffset := committedOffset + 1 + if startOffset < earliestOffset { + startOffset = earliestOffset + } + + highestOffset, err := l.HighestPartitionOffset(ctx) + if err != nil { + return false, Job{}, err + } + if highestOffset == committedOffset { + return false, Job{}, nil + } + + // Create the job with the calculated offsets + job := Job{ + Partition: l.part.Partition(), + Offsets: Offsets{ + Min: startOffset, + Max: min(startOffset+l.stepLen, highestOffset), + }, + } + + return true, job, nil +} + +// implement a dummy controller which can be parameterized to +// deterministically simulate partitions +type dummyPartitionController struct { + topic string + partition int32 + committed int64 + highest int64 + numTenants int // number of unique tenants to simulate + streamsPerTenant int // number of streams per tenant + entriesPerOffset int // coefficient for entries per offset +} + +// used in testing +// nolint:revive +func NewDummyPartitionController(topic string, partition int32, highest int64) *dummyPartitionController { + return &dummyPartitionController{ + topic: topic, + partition: partition, + committed: 0, // always starts at zero + highest: highest, + numTenants: 2, // default number of tenants + streamsPerTenant: 2, // default streams per tenant + entriesPerOffset: 1, // default entries per offset coefficient + } +} + +func (d *dummyPartitionController) Topic() string { + return d.topic +} + +func (d *dummyPartitionController) Partition() int32 { + return d.partition +} + +func (d *dummyPartitionController) HighestCommittedOffset(_ context.Context) (int64, error) { + return d.committed, nil +} + +func (d *dummyPartitionController) HighestPartitionOffset(_ context.Context) (int64, error) { + return d.highest, nil +} + +func (d *dummyPartitionController) Commit(_ context.Context, offset int64) error { + d.committed = offset + return nil +} + +func (d *dummyPartitionController) Process(ctx context.Context, offsets Offsets, ch chan<- []AppendInput) (int64, error) { + for i := int(offsets.Min); i < int(offsets.Max); i++ { + batch := d.createBatch(i) + select { + case <-ctx.Done(): + return int64(i - 1), ctx.Err() + case ch <- batch: + } + } + return offsets.Max - 1, nil +} + +// creates (tenants*streams) inputs +func (d *dummyPartitionController) createBatch(offset int) []AppendInput { + result := make([]AppendInput, 0, d.numTenants*d.streamsPerTenant) + for i := 0; i < d.numTenants; i++ { + tenant := fmt.Sprintf("tenant-%d", i) + for j := 0; j < d.streamsPerTenant; j++ { + lbls := labels.Labels{ + {Name: "stream", Value: fmt.Sprintf("stream-%d", j)}, + } + entries := make([]push.Entry, d.entriesPerOffset) + for k := 0; k < d.entriesPerOffset; k++ { + entries[k] = push.Entry{ + Timestamp: time.Now(), + Line: fmt.Sprintf("tenant=%d stream=%d line=%d offset=%d", i, j, k, offset), + } + } + result = append(result, AppendInput{ + tenant: tenant, + labels: lbls, + labelsStr: lbls.String(), + entries: entries, + }) + } + } + return result +} + +func (d *dummyPartitionController) Close() error { + return nil +} diff --git a/pkg/blockbuilder/metrics.go b/pkg/blockbuilder/metrics.go new file mode 100644 index 0000000000000..31679e34f4466 --- /dev/null +++ b/pkg/blockbuilder/metrics.go @@ -0,0 +1,152 @@ +package blockbuilder + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/grafana/loki/v3/pkg/analytics" + "github.com/grafana/loki/v3/pkg/util/constants" +) + +type SlimgesterMetrics struct { + chunkUtilization prometheus.Histogram + chunkEntries prometheus.Histogram + chunkSize prometheus.Histogram + chunkCompressionRatio prometheus.Histogram + chunksPerTenant *prometheus.CounterVec + chunkSizePerTenant *prometheus.CounterVec + chunkAge prometheus.Histogram + chunkEncodeTime prometheus.Histogram + chunksFlushFailures prometheus.Counter + chunksFlushedPerReason *prometheus.CounterVec + chunkLifespan prometheus.Histogram + chunksEncoded *prometheus.CounterVec + chunkDecodeFailures *prometheus.CounterVec + flushedChunksStats *analytics.Counter + flushedChunksBytesStats *analytics.Statistics + flushedChunksLinesStats *analytics.Statistics + flushedChunksAgeStats *analytics.Statistics + flushedChunksLifespanStats *analytics.Statistics + flushedChunksUtilizationStats *analytics.Statistics + + chunksCreatedTotal prometheus.Counter + samplesPerChunk prometheus.Histogram + blocksPerChunk prometheus.Histogram + chunkCreatedStats *analytics.Counter +} + +func NewSlimgesterMetrics(r prometheus.Registerer) *SlimgesterMetrics { + return &SlimgesterMetrics{ + chunkUtilization: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_utilization", + Help: "Distribution of stored chunk utilization (when stored).", + Buckets: prometheus.LinearBuckets(0, 0.2, 6), + }), + chunkEntries: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_entries", + Help: "Distribution of stored lines per chunk (when stored).", + Buckets: prometheus.ExponentialBuckets(200, 2, 9), // biggest bucket is 200*2^(9-1) = 51200 + }), + chunkSize: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_size_bytes", + Help: "Distribution of stored chunk sizes (when stored).", + Buckets: prometheus.ExponentialBuckets(20000, 2, 10), // biggest bucket is 20000*2^(10-1) = 10,240,000 (~10.2MB) + }), + chunkCompressionRatio: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_compression_ratio", + Help: "Compression ratio of chunks (when stored).", + Buckets: prometheus.LinearBuckets(.75, 2, 10), + }), + chunksPerTenant: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunks_stored_total", + Help: "Total stored chunks per tenant.", + }, []string{"tenant"}), + chunkSizePerTenant: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_stored_bytes_total", + Help: "Total bytes stored in chunks per tenant.", + }, []string{"tenant"}), + chunkAge: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_age_seconds", + Help: "Distribution of chunk ages (when stored).", + // with default settings chunks should flush between 5 min and 12 hours + // so buckets at 1min, 5min, 10min, 30min, 1hr, 2hr, 4hr, 10hr, 12hr, 16hr + Buckets: []float64{60, 300, 600, 1800, 3600, 7200, 14400, 36000, 43200, 57600}, + }), + chunkEncodeTime: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_encode_time_seconds", + Help: "Distribution of chunk encode times.", + // 10ms to 10s. + Buckets: prometheus.ExponentialBuckets(0.01, 4, 6), + }), + chunksFlushFailures: promauto.With(r).NewCounter(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunks_flush_failures_total", + Help: "Total number of flush failures.", + }), + chunksFlushedPerReason: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunks_flushed_total", + Help: "Total flushed chunks per reason.", + }, []string{"reason"}), + chunkLifespan: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_bounds_hours", + Help: "Distribution of chunk end-start durations.", + // 1h -> 8hr + Buckets: prometheus.LinearBuckets(1, 1, 8), + }), + chunksEncoded: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunks_encoded_total", + Help: "The total number of chunks encoded in the ingester.", + }, []string{"user"}), + chunkDecodeFailures: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunk_decode_failures_total", + Help: "The number of freshly encoded chunks that failed to decode.", + }, []string{"user"}), + flushedChunksStats: analytics.NewCounter("slimgester_flushed_chunks"), + flushedChunksBytesStats: analytics.NewStatistics("slimgester_flushed_chunks_bytes"), + flushedChunksLinesStats: analytics.NewStatistics("slimgester_flushed_chunks_lines"), + flushedChunksAgeStats: analytics.NewStatistics( + "slimgester_flushed_chunks_age_seconds", + ), + flushedChunksLifespanStats: analytics.NewStatistics( + "slimgester_flushed_chunks_lifespan_seconds", + ), + flushedChunksUtilizationStats: analytics.NewStatistics( + "slimgester_flushed_chunks_utilization", + ), + chunksCreatedTotal: promauto.With(r).NewCounter(prometheus.CounterOpts{ + Namespace: constants.Loki, + Name: "slimgester_chunks_created_total", + Help: "The total number of chunks created in the ingester.", + }), + samplesPerChunk: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Subsystem: "slimgester", + Name: "samples_per_chunk", + Help: "The number of samples in a chunk.", + + Buckets: prometheus.LinearBuckets(4096, 2048, 6), + }), + blocksPerChunk: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Subsystem: "slimgester", + Name: "blocks_per_chunk", + Help: "The number of blocks in a chunk.", + + Buckets: prometheus.ExponentialBuckets(5, 2, 6), + }), + + chunkCreatedStats: analytics.NewCounter("slimgester_chunk_created"), + } +} diff --git a/pkg/blockbuilder/pipeline.go b/pkg/blockbuilder/pipeline.go new file mode 100644 index 0000000000000..494763d8c83f3 --- /dev/null +++ b/pkg/blockbuilder/pipeline.go @@ -0,0 +1,99 @@ +package blockbuilder + +import ( + "context" + + "github.com/grafana/dskit/multierror" + "golang.org/x/sync/errgroup" +) + +type stage struct { + name string + parallelism int + grp *errgroup.Group + ctx context.Context + fn func(context.Context) error + cleanup func(context.Context) error // optional; will be called once the underlying group returns +} + +// pipeline is a sequence of n different stages. +type pipeline struct { + ctx context.Context // base context + // we use a separate errgroup for stage dispatch/collection + // and inherit stage-specific groups from this ctx to + // propagate cancellation + grp *errgroup.Group + stages []stage +} + +func newPipeline(ctx context.Context) *pipeline { + stagesGrp, ctx := errgroup.WithContext(ctx) + return &pipeline{ + ctx: ctx, + grp: stagesGrp, + } +} + +func (p *pipeline) AddStageWithCleanup( + name string, + parallelism int, + fn func(context.Context) error, + cleanup func(context.Context) error, +) { + grp, ctx := errgroup.WithContext(p.ctx) + p.stages = append(p.stages, stage{ + name: name, + parallelism: parallelism, + fn: fn, + cleanup: cleanup, + ctx: ctx, + grp: grp, + }) +} + +func (p *pipeline) AddStage( + name string, + parallelism int, + fn func(context.Context) error, +) { + p.AddStageWithCleanup(name, parallelism, fn, nil) +} + +func (p *pipeline) Run() error { + + for i := range p.stages { + // we're using this in subsequent async closures; + // assign it directly in-loop + s := p.stages[i] + + // spin up n workers for each stage using that stage's + // error group. + for j := 0; j < s.parallelism; j++ { + s.grp.Go(func() error { + return s.fn(s.ctx) + }) + } + + // Using the pipeline's err group, await the stage finish, + // calling any necessary cleanup fn + // NB: by using the pipeline's errgroup here, we propagate + // failures to downstream stage contexts, so once a single stage + // fails, the others will be notified. + p.grp.Go(func() error { + var errs multierror.MultiError + errs.Add(s.grp.Wait()) + if s.cleanup != nil { + // NB: we use the pipeline's context for the cleanup call b/c + // the stage's context is cancelled once `Wait` returns. + // That's ok. cleanup is always called for a relevant stage + // and just needs to know if _other_ stages failed at this point + errs.Add(s.cleanup(p.ctx)) + } + + return errs.Err() + }) + } + + // finish all stages + return p.grp.Wait() +} diff --git a/pkg/blockbuilder/pipeline_test.go b/pkg/blockbuilder/pipeline_test.go new file mode 100644 index 0000000000000..9ec69d2006ebe --- /dev/null +++ b/pkg/blockbuilder/pipeline_test.go @@ -0,0 +1,87 @@ +package blockbuilder + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +type testStage struct { + parallelism int + fn func(context.Context) error + cleanup func(context.Context) error +} + +func TestPipeline(t *testing.T) { + tests := []struct { + name string + stages []testStage + expectedErr error + }{ + { + name: "single stage success", + stages: []testStage{ + { + parallelism: 1, + fn: func(_ context.Context) error { + return nil + }, + }, + }, + }, + { + name: "multiple stages success", + stages: []testStage{ + { + parallelism: 2, + fn: func(_ context.Context) error { + return nil + }, + }, + { + parallelism: 1, + fn: func(_ context.Context) error { + return nil + }, + }, + }, + }, + { + name: "stage error propagates", + stages: []testStage{ + { + parallelism: 1, + fn: func(_ context.Context) error { + return errors.New("stage error") + }, + }, + }, + expectedErr: errors.New("stage error"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := newPipeline(context.Background()) + + for i, stage := range tt.stages { + if stage.cleanup != nil { + p.AddStageWithCleanup(fmt.Sprint(i), stage.parallelism, stage.fn, stage.cleanup) + } else { + p.AddStage(fmt.Sprint(i), stage.parallelism, stage.fn) + } + } + + err := p.Run() + if tt.expectedErr != nil { + require.Error(t, err) + require.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/pkg/blockbuilder/plan.txt b/pkg/blockbuilder/plan.txt new file mode 100644 index 0000000000000..a3a80a735fa4d --- /dev/null +++ b/pkg/blockbuilder/plan.txt @@ -0,0 +1,34 @@ +# Purpose +blockbuilder is responsible for consuming ingested data in the queue (kafka, etc) and writing it in an optimized form to long term storage. While this should always remain true, it can be built and iterated upon in phases. First, let's look at the simplest possible architecture: + +* [interface] loads "jobs": partitions+offset ranges in kafka +* For each job, process data, building the storage format +* [interface] Upon completion (inc flushing to storage), commit work + * e.g. update consumer group processed offset in kafka +* consumes + +# First Impl: Alongside existing multi-zone ingester writers +Goal: modify ingester architecture towards RF1, but don't actually write to storage yet, b/c we haven't solved coordinating interim reads/writes. +Deliverable: RF1 metrics proof +* run replicas==partitions (from ingesters) +* run every $INTERVAL (5m?), +* slim down ingester write path + * remove disk (all WALs). + * ignore limits if too complex (for now) + * /dev/null backend + + +# TODO improvements +* metadata store + * include offsets committed for coordination b/w ingester-readers & long term storage +* planner/scheduler+worker architecture +* shuffle sharding + + +# Things to solve +* limits application +* job sizing -- coordinate kafka offsets w/ underlying bytes added? + * ideally we can ask kafka for "the next 1GB" in a partition, but to do this we'd need the kafka offsets (auto-incremented integers for messages within a partition) to be derived from the message size. Right now, different batch sizes can cause kafka msgs to have very different sizes. + * idea: another set of partitions to store offsets->datasize? Sounds shitty tbh & breaks the consistency bound on writes (what if kafka acks first write but doesnt ack the second?) + * what if we stored byte counter metadata in kafka records so we could O(log(n)) seek an offset range w/ the closest $SIZE + * Likely a reasonable perf tradeoff as this isn't called often (only in job planner in the future). \ No newline at end of file diff --git a/pkg/blockbuilder/slimgester.go b/pkg/blockbuilder/slimgester.go new file mode 100644 index 0000000000000..705b47444a6f2 --- /dev/null +++ b/pkg/blockbuilder/slimgester.go @@ -0,0 +1,811 @@ +package blockbuilder + +import ( + "bytes" + "context" + "flag" + "fmt" + "math" + "sync" + "time" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/grafana/dskit/backoff" + "github.com/grafana/dskit/services" + "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/labels" + + "github.com/grafana/loki/v3/pkg/chunkenc" + "github.com/grafana/loki/v3/pkg/compression" + "github.com/grafana/loki/v3/pkg/ingester" + "github.com/grafana/loki/v3/pkg/storage/chunk" + "github.com/grafana/loki/v3/pkg/storage/config" + "github.com/grafana/loki/v3/pkg/storage/stores" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" + "github.com/grafana/loki/v3/pkg/storage/types" + "github.com/grafana/loki/v3/pkg/util" + "github.com/grafana/loki/v3/pkg/util/flagext" + util_log "github.com/grafana/loki/v3/pkg/util/log" + + "github.com/grafana/loki/pkg/push" +) + +const ( + flushReasonFull = "full" + flushReasonMaxAge = "max_age" + onePointFiveMB = 3 << 19 +) + +type Config struct { + ConcurrentFlushes int `yaml:"concurrent_flushes"` + ConcurrentWriters int `yaml:"concurrent_writers"` + BlockSize flagext.ByteSize `yaml:"chunk_block_size"` + TargetChunkSize flagext.ByteSize `yaml:"chunk_target_size"` + ChunkEncoding string `yaml:"chunk_encoding"` + parsedEncoding compression.Codec `yaml:"-"` // placeholder for validated encoding + MaxChunkAge time.Duration `yaml:"max_chunk_age"` + Interval time.Duration `yaml:"interval"` + Backoff backoff.Config `yaml:"backoff_config"` +} + +func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { + f.IntVar(&cfg.ConcurrentFlushes, prefix+"concurrent-flushes", 1, "How many flushes can happen concurrently") + f.IntVar(&cfg.ConcurrentWriters, prefix+"concurrent-writers", 1, "How many workers to process writes, defaults to number of available cpus") + _ = cfg.BlockSize.Set("256KB") + f.Var(&cfg.BlockSize, prefix+"chunks-block-size", "The targeted _uncompressed_ size in bytes of a chunk block When this threshold is exceeded the head block will be cut and compressed inside the chunk.") + _ = cfg.TargetChunkSize.Set(fmt.Sprint(onePointFiveMB)) + f.Var(&cfg.TargetChunkSize, prefix+"chunk-target-size", "A target _compressed_ size in bytes for chunks. This is a desired size not an exact size, chunks may be slightly bigger or significantly smaller if they get flushed for other reasons (e.g. chunk_idle_period). A value of 0 creates chunks with a fixed 10 blocks, a non zero value will create chunks with a variable number of blocks to meet the target size.") + f.StringVar(&cfg.ChunkEncoding, prefix+"chunk-encoding", compression.Snappy.String(), fmt.Sprintf("The algorithm to use for compressing chunk. (%s)", compression.SupportedCodecs())) + f.DurationVar(&cfg.MaxChunkAge, prefix+"max-chunk-age", 2*time.Hour, "The maximum duration of a timeseries chunk in memory. If a timeseries runs for longer than this, the current chunk will be flushed to the store and a new chunk created.") + f.DurationVar(&cfg.Interval, prefix+"interval", 10*time.Minute, "The interval at which to run.") + cfg.Backoff.RegisterFlagsWithPrefix(prefix+"backoff.", f) +} + +// RegisterFlags registers flags. +func (cfg *Config) RegisterFlags(flags *flag.FlagSet) { + cfg.RegisterFlagsWithPrefix("blockbuilder.", flags) +} + +func (cfg *Config) Validate() error { + enc, err := compression.ParseCodec(cfg.ChunkEncoding) + if err != nil { + return err + } + cfg.parsedEncoding = enc + return nil +} + +// BlockBuilder is a slimmed-down version of the ingester, intended to +// ingest logs without WALs. Broadly, it accumulates logs into per-tenant chunks in the same way the existing ingester does, +// without a WAL. Index (TSDB) creation is also not an out-of-band procedure and must be called directly. In essence, this +// allows us to buffer data, flushing chunks to storage as necessary, and then when ready to commit this, relevant TSDBs (one per period) are created and flushed to storage. This allows an external caller to prepare a batch of data, build relevant chunks+indices, ensure they're flushed, and then return. As long as chunk+index creation is deterministic, this operation is also +// idempotent, making retries simple and impossible to introduce duplicate data. +// It contains the following methods: +// - `Append(context.Context, logproto.PushRequest) error` +// Adds a push request to ingested data. May flush existing chunks when they're full/etc. +// - `Commit(context.Context) error` +// Serializes (cuts) any buffered data into chunks, flushes them to storage, then creates + flushes TSDB indices +// containing all chunk references. Finally, clears internal state. +type BlockBuilder struct { + services.Service + + id string + cfg Config + periodicConfigs []config.PeriodConfig + + metrics *SlimgesterMetrics + logger log.Logger + + store stores.ChunkWriter + objStore *MultiStore + jobController *PartitionJobController +} + +func NewBlockBuilder( + id string, + cfg Config, + periodicConfigs []config.PeriodConfig, + store stores.ChunkWriter, + objStore *MultiStore, + logger log.Logger, + reg prometheus.Registerer, + jobController *PartitionJobController, +) (*BlockBuilder, + error) { + i := &BlockBuilder{ + id: id, + cfg: cfg, + periodicConfigs: periodicConfigs, + metrics: NewSlimgesterMetrics(reg), + logger: logger, + store: store, + objStore: objStore, + jobController: jobController, + } + + i.Service = services.NewBasicService(nil, i.running, nil) + return i, nil +} + +func (i *BlockBuilder) running(ctx context.Context) error { + ticker := time.NewTicker(i.cfg.Interval) + defer ticker.Stop() + + // run once in beginning + select { + case <-ctx.Done(): + return nil + default: + _, err := i.runOne(ctx) + if err != nil { + return err + } + } + + for { + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + skipped, err := i.runOne(ctx) + level.Info(i.logger).Log( + "msg", "completed block builder run", "skipped", + "skipped", skipped, + "err", err, + ) + if err != nil { + return err + } + } + } +} + +// runOne performs a single +func (i *BlockBuilder) runOne(ctx context.Context) (skipped bool, err error) { + + exists, job, err := i.jobController.LoadJob(ctx) + if err != nil { + return false, err + } + + if !exists { + level.Info(i.logger).Log("msg", "no available job to process") + return true, nil + } + + logger := log.With( + i.logger, + "partition", job.Partition, + "job_min_offset", job.Offsets.Min, + "job_max_offset", job.Offsets.Max, + ) + + level.Debug(logger).Log("msg", "beginning job") + + indexer := newTsdbCreator() + appender := newAppender(i.id, + i.cfg, + i.periodicConfigs, + i.store, + i.objStore, + logger, + i.metrics, + ) + + var lastOffset int64 + p := newPipeline(ctx) + + // Pipeline stage 1: Process the job offsets and write records to inputCh + // This stage reads from the partition and feeds records into the input channel + // When complete, it stores the last processed offset and closes the channel + inputCh := make(chan []AppendInput) + p.AddStageWithCleanup( + "load records", + 1, + func(ctx context.Context) error { + lastOffset, err = i.jobController.Process(ctx, job.Offsets, inputCh) + return err + }, + func(ctx context.Context) error { + level.Debug(logger).Log( + "msg", "finished loading records", + "ctx_error", ctx.Err(), + ) + close(inputCh) + return nil + }, + ) + + // Stage 2: Process input records and generate chunks + // This stage receives AppendInput batches, appends them to appropriate instances, + // and forwards any cut chunks to the chunks channel for flushing. + // ConcurrentWriters workers process inputs in parallel to maximize throughput. + flush := make(chan *chunk.Chunk) + p.AddStageWithCleanup( + "appender", + i.cfg.ConcurrentWriters, + func(ctx context.Context) error { + + for { + select { + case <-ctx.Done(): + return ctx.Err() + case inputs, ok := <-inputCh: + // inputs are finished; we're done + if !ok { + return nil + } + + for _, input := range inputs { + cut, err := appender.Append(ctx, input) + if err != nil { + level.Error(logger).Log("msg", "failed to append records", "err", err) + return err + } + + for _, chk := range cut { + select { + case <-ctx.Done(): + return ctx.Err() + case flush <- chk: + } + } + } + } + } + }, + func(ctx context.Context) (err error) { + defer func() { + level.Debug(logger).Log( + "msg", "finished appender", + "err", err, + "ctx_error", ctx.Err(), + ) + }() + defer close(flush) + + // once we're done appending, cut all remaining chunks. + chks, err := appender.CutRemainingChunks(ctx) + if err != nil { + return err + } + + for _, chk := range chks { + select { + case <-ctx.Done(): + return ctx.Err() + case flush <- chk: + } + } + return nil + }, + ) + + // Stage 3: Flush chunks to storage + // This stage receives chunks from the chunks channel and flushes them to storage + // using ConcurrentFlushes workers for parallel processing + p.AddStage( + "flusher", + i.cfg.ConcurrentFlushes, + func(ctx context.Context) error { + for { + select { + case <-ctx.Done(): + return ctx.Err() + case chk, ok := <-flush: + if !ok { + return nil + } + if _, err := withBackoff( + ctx, + i.cfg.Backoff, // retry forever + func() (res struct{}, err error) { + err = i.store.PutOne(ctx, chk.From, chk.Through, *chk) + if err != nil { + i.metrics.chunksFlushFailures.Inc() + return + } + appender.reportFlushedChunkStatistics(chk) + + // write flushed chunk to index + approxKB := math.Round(float64(chk.Data.UncompressedSize()) / float64(1<<10)) + meta := index.ChunkMeta{ + Checksum: chk.ChunkRef.Checksum, + MinTime: int64(chk.ChunkRef.From), + MaxTime: int64(chk.ChunkRef.Through), + KB: uint32(approxKB), + Entries: uint32(chk.Data.Entries()), + } + err = indexer.Append(chk.UserID, chk.Metric, chk.ChunkRef.Fingerprint, index.ChunkMetas{meta}) + return + }, + ); err != nil { + return err + } + } + } + }, + ) + + err = p.Run() + level.Debug(logger).Log( + "msg", "finished chunk creation", + "err", err, + ) + if err != nil { + return false, err + } + + var ( + nodeName = i.id + tableRanges = config.GetIndexStoreTableRanges(types.TSDBType, i.periodicConfigs) + ) + + built, err := indexer.create(ctx, nodeName, tableRanges) + if err != nil { + return false, err + } + + for _, db := range built { + u := newUploader(i.objStore) + if err := u.Put(ctx, db); err != nil { + level.Error(util_log.Logger).Log( + "msg", "failed to upload tsdb", + "path", db.id.Path(), + ) + + return false, err + } + + level.Debug(logger).Log( + "msg", "uploaded tsdb", + "name", db.id.Name(), + ) + } + + if lastOffset <= job.Offsets.Min { + return false, nil + } + + if err = i.jobController.part.Commit(ctx, lastOffset); err != nil { + level.Error(logger).Log( + "msg", "failed to commit offset", + "last_offset", lastOffset, + "err", err, + ) + return false, err + } + + // log success + level.Info(logger).Log( + "msg", "successfully processed and committed batch", + "last_offset", lastOffset, + ) + + return false, nil +} + +type Appender struct { + id string + cfg Config + periodicConfigs []config.PeriodConfig + + metrics *SlimgesterMetrics + logger log.Logger + + instances map[string]*instance + instancesMtx sync.RWMutex + + store stores.ChunkWriter + objStore *MultiStore +} + +// Writer is a single use construct for building chunks +// for from a set of records. It's an independent struct to ensure its +// state is not reused across jobs. +func newAppender( + id string, + cfg Config, + periodicConfigs []config.PeriodConfig, + store stores.ChunkWriter, + objStore *MultiStore, + logger log.Logger, + metrics *SlimgesterMetrics, +) *Appender { + return &Appender{ + id: id, + cfg: cfg, + periodicConfigs: periodicConfigs, + metrics: metrics, + logger: logger, + instances: make(map[string]*instance), + store: store, + objStore: objStore, + } +} + +// reportFlushedChunkStatistics calculate overall statistics of flushed chunks without compromising the flush process. +func (w *Appender) reportFlushedChunkStatistics( + ch *chunk.Chunk, +) { + byt, err := ch.Encoded() + if err != nil { + level.Error(w.logger).Log("msg", "failed to encode flushed wire chunk", "err", err) + return + } + sizePerTenant := w.metrics.chunkSizePerTenant.WithLabelValues(ch.UserID) + countPerTenant := w.metrics.chunksPerTenant.WithLabelValues(ch.UserID) + + reason := flushReasonFull + from, through := ch.From.Time(), ch.Through.Time() + if through.Sub(from) > w.cfg.MaxChunkAge { + reason = flushReasonMaxAge + } + + w.metrics.chunksFlushedPerReason.WithLabelValues(reason).Add(1) + + compressedSize := float64(len(byt)) + uncompressedSize, ok := chunkenc.UncompressedSize(ch.Data) + + if ok && compressedSize > 0 { + w.metrics.chunkCompressionRatio.Observe(float64(uncompressedSize) / compressedSize) + } + + utilization := ch.Data.Utilization() + w.metrics.chunkUtilization.Observe(utilization) + + numEntries := ch.Data.Entries() + w.metrics.chunkEntries.Observe(float64(numEntries)) + w.metrics.chunkSize.Observe(compressedSize) + sizePerTenant.Add(compressedSize) + countPerTenant.Inc() + + w.metrics.chunkAge.Observe(time.Since(from).Seconds()) + w.metrics.chunkLifespan.Observe(through.Sub(from).Hours()) + + w.metrics.flushedChunksBytesStats.Record(compressedSize) + w.metrics.flushedChunksLinesStats.Record(float64(numEntries)) + w.metrics.flushedChunksUtilizationStats.Record(utilization) + w.metrics.flushedChunksAgeStats.Record(time.Since(from).Seconds()) + w.metrics.flushedChunksLifespanStats.Record(through.Sub(from).Seconds()) + w.metrics.flushedChunksStats.Inc(1) +} + +func (w *Appender) CutRemainingChunks(ctx context.Context) ([]*chunk.Chunk, error) { + var chunks []*chunk.Chunk + w.instancesMtx.Lock() + defer w.instancesMtx.Unlock() + + for _, inst := range w.instances { + + // wrap in anonymous fn to make lock release more straightforward + if err := func() error { + inst.streams.mtx.Lock() + defer inst.streams.mtx.Unlock() + + for _, stream := range inst.streams.byLabels { + + // wrap in anonymous fn to make lock release more straightforward + if err := func() error { + stream.chunkMtx.Lock() + defer stream.chunkMtx.Unlock() + if stream.chunk != nil { + cut, err := stream.closeChunk() + if err != nil { + return err + } + encoded, err := inst.encodeChunk(ctx, stream, cut) + if err != nil { + return err + } + chunks = append(chunks, encoded) + } + return nil + + }(); err != nil { + return err + } + + } + return nil + + }(); err != nil { + return nil, err + } + + } + + return chunks, nil +} + +type AppendInput struct { + tenant string + // both labels & labelsStr are populated to prevent duplicating conversion work in multiple places + labels labels.Labels + labelsStr string + entries []push.Entry +} + +func (w *Appender) Append(ctx context.Context, input AppendInput) ([]*chunk.Chunk, error) { + // use rlock so multiple appends can be called on same instance. + // re-check after using regular lock if it didnt exist. + w.instancesMtx.RLock() + inst, ok := w.instances[input.tenant] + w.instancesMtx.RUnlock() + if !ok { + w.instancesMtx.Lock() + inst, ok = w.instances[input.tenant] + if !ok { + inst = newInstance(w.cfg, input.tenant, w.metrics, w.periodicConfigs, w.logger) + w.instances[input.tenant] = inst + } + w.instancesMtx.Unlock() + } + + closed, err := inst.Push(ctx, input) + return closed, err +} + +// instance is a slimmed down version from the ingester pkg +type instance struct { + cfg Config + tenant string + buf []byte // buffer used to compute fps. + mapper *ingester.FpMapper // using of mapper no longer needs mutex because reading from streams is lock-free + metrics *SlimgesterMetrics + streams *streamsMap + logger log.Logger + + periods []config.PeriodConfig +} + +func newInstance( + cfg Config, + tenant string, + metrics *SlimgesterMetrics, + periods []config.PeriodConfig, + logger log.Logger, +) *instance { + streams := newStreamsMap() + return &instance{ + cfg: cfg, + tenant: tenant, + buf: make([]byte, 0, 1024), + mapper: ingester.NewFPMapper(streams.getLabelsFromFingerprint), + metrics: metrics, + streams: streams, + logger: logger, + periods: periods, + } +} + +func newStreamsMap() *streamsMap { + return &streamsMap{ + byLabels: make(map[string]*stream), + byFp: make(map[model.Fingerprint]*stream), + } +} + +type streamsMap struct { + // labels -> stream + byLabels map[string]*stream + byFp map[model.Fingerprint]*stream + mtx sync.RWMutex +} + +// For performs an operation on an existing stream, creating it if it wasn't previously present. +func (m *streamsMap) For( + ls string, + createFn func() (*stream, error), + fn func(*stream) error, +) error { + // first use read lock in case the stream exists + m.mtx.RLock() + if s, ok := m.byLabels[ls]; ok { + err := fn(s) + m.mtx.RUnlock() + return err + } + m.mtx.RUnlock() + + // Stream wasn't found, acquire write lock to create it + m.mtx.Lock() + defer m.mtx.Unlock() + + // Double check it wasn't created while we were upgrading the lock + if s, ok := m.byLabels[ls]; ok { + return fn(s) + } + + // Create new stream + s, err := createFn() + if err != nil { + return err + } + + m.byLabels[ls] = s + m.byFp[s.fp] = s + return fn(s) +} + +// Return labels associated with given fingerprint. Used by fingerprint mapper. +func (m *streamsMap) getLabelsFromFingerprint(fp model.Fingerprint) labels.Labels { + + if s, ok := m.byFp[fp]; ok { + return s.ls + } + return nil +} + +func (i *instance) getHashForLabels(ls labels.Labels) model.Fingerprint { + var fp uint64 + fp, i.buf = ls.HashWithoutLabels(i.buf, []string(nil)...) + return i.mapper.MapFP(model.Fingerprint(fp), ls) +} + +// Push will iterate over the given streams present in the PushRequest and attempt to store them. +func (i *instance) Push( + ctx context.Context, + input AppendInput, +) (closed []*chunk.Chunk, err error) { + err = i.streams.For( + input.labelsStr, + func() (*stream, error) { + fp := i.getHashForLabels(input.labels) + return newStream(fp, input.labels, i.cfg, i.metrics), nil + }, + func(stream *stream) error { + xs, err := stream.Push(input.entries) + if err != nil { + return err + } + + if len(xs) > 0 { + for _, x := range xs { + // encodeChunk mutates the chunk so we must pass by reference + chk, err := i.encodeChunk(ctx, stream, x) + if err != nil { + return err + } + closed = append(closed, chk) + } + } + return err + }, + ) + + return closed, err +} + +// encodeChunk encodes a chunk.Chunk. +func (i *instance) encodeChunk(ctx context.Context, stream *stream, mc *chunkenc.MemChunk) (*chunk.Chunk, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + start := time.Now() + + firstTime, lastTime := util.RoundToMilliseconds(mc.Bounds()) + chk := chunk.NewChunk( + i.tenant, stream.fp, stream.ls, + chunkenc.NewFacade(mc, stream.blockSize, stream.targetChunkSize), + firstTime, + lastTime, + ) + + chunkBytesSize := mc.BytesSize() + 4*1024 // size + 4kB should be enough room for cortex header + if err := chk.EncodeTo(bytes.NewBuffer(make([]byte, 0, chunkBytesSize)), i.logger); err != nil { + if !errors.Is(err, chunk.ErrChunkDecode) { + return nil, fmt.Errorf("chunk encoding: %w", err) + } + + i.metrics.chunkDecodeFailures.WithLabelValues(chk.UserID).Inc() + } + i.metrics.chunkEncodeTime.Observe(time.Since(start).Seconds()) + i.metrics.chunksEncoded.WithLabelValues(chk.UserID).Inc() + return &chk, nil +} + +type stream struct { + fp model.Fingerprint + ls labels.Labels + + chunkFormat byte + codec compression.Codec + blockSize int + targetChunkSize int + + chunkMtx sync.RWMutex + chunk *chunkenc.MemChunk + metrics *SlimgesterMetrics +} + +func newStream(fp model.Fingerprint, ls labels.Labels, cfg Config, metrics *SlimgesterMetrics) *stream { + return &stream{ + fp: fp, + ls: ls, + + chunkFormat: chunkenc.ChunkFormatV4, + codec: cfg.parsedEncoding, + blockSize: cfg.BlockSize.Val(), + targetChunkSize: cfg.TargetChunkSize.Val(), + + metrics: metrics, + } +} + +func (s *stream) Push(entries []push.Entry) (closed []*chunkenc.MemChunk, err error) { + s.chunkMtx.Lock() + defer s.chunkMtx.Unlock() + + if s.chunk == nil { + s.chunk = s.NewChunk() + } + + // bytesAdded, err := s.storeEntries(ctx, toStore, usageTracker) + for i := 0; i < len(entries); i++ { + + // cut the chunk if the new addition overflows target size + if !s.chunk.SpaceFor(&entries[i]) { + cut, err := s.closeChunk() + if err != nil { + return nil, err + } + closed = append(closed, cut) + } + + if _, err = s.chunk.Append(&entries[i]); err != nil { + return closed, errors.Wrap(err, "appending entry") + } + } + + return closed, nil +} + +func (s *stream) closeChunk() (*chunkenc.MemChunk, error) { + if err := s.chunk.Close(); err != nil { + return nil, errors.Wrap(err, "closing chunk") + } + + s.metrics.samplesPerChunk.Observe(float64(s.chunk.Size())) + s.metrics.blocksPerChunk.Observe(float64(s.chunk.BlockCount())) + s.metrics.chunksCreatedTotal.Inc() + s.metrics.chunkCreatedStats.Inc(1) + + // add a chunk + res := s.chunk + s.chunk = s.NewChunk() + return res, nil +} + +func (s *stream) NewChunk() *chunkenc.MemChunk { + return chunkenc.NewMemChunk( + s.chunkFormat, + s.codec, + chunkenc.ChunkHeadFormatFor(s.chunkFormat), + s.blockSize, + s.targetChunkSize, + ) +} + +func withBackoff[T any]( + ctx context.Context, + config backoff.Config, + fn func() (T, error), +) (T, error) { + var zero T + + var boff = backoff.New(ctx, config) + for boff.Ongoing() { + res, err := fn() + if err != nil { + boff.Wait() + continue + } + return res, nil + } + + return zero, boff.ErrCause() +} diff --git a/pkg/blockbuilder/storage.go b/pkg/blockbuilder/storage.go new file mode 100644 index 0000000000000..2815b9b97ad86 --- /dev/null +++ b/pkg/blockbuilder/storage.go @@ -0,0 +1,154 @@ +package blockbuilder + +import ( + "context" + "fmt" + "io" + "sort" + + "github.com/opentracing/opentracing-go" + "github.com/prometheus/common/model" + + "github.com/grafana/loki/v3/pkg/storage" + "github.com/grafana/loki/v3/pkg/storage/chunk/client" + "github.com/grafana/loki/v3/pkg/storage/config" +) + +type MultiStore struct { + stores []*storeEntry + storageConfig storage.Config +} + +type storeEntry struct { + start model.Time + cfg config.PeriodConfig + objectClient client.ObjectClient +} + +var _ client.ObjectClient = (*MultiStore)(nil) + +func NewMultiStore( + periodicConfigs []config.PeriodConfig, + storageConfig storage.Config, + clientMetrics storage.ClientMetrics, +) (*MultiStore, error) { + store := &MultiStore{ + storageConfig: storageConfig, + } + // sort by From time + sort.Slice(periodicConfigs, func(i, j int) bool { + return periodicConfigs[i].From.Time.Before(periodicConfigs[j].From.Time) + }) + for _, periodicConfig := range periodicConfigs { + objectClient, err := storage.NewObjectClient(periodicConfig.ObjectType, "storage-rf1", storageConfig, clientMetrics) + if err != nil { + return nil, fmt.Errorf("creating object client for period %s: %w ", periodicConfig.From, err) + } + store.stores = append(store.stores, &storeEntry{ + start: periodicConfig.From.Time, + cfg: periodicConfig, + objectClient: objectClient, + }) + } + return store, nil +} + +func (m *MultiStore) GetStoreFor(ts model.Time) (client.ObjectClient, error) { + // find the schema with the lowest start _after_ tm + j := sort.Search(len(m.stores), func(j int) bool { + return m.stores[j].start > ts + }) + + // reduce it by 1 because we want a schema with start <= tm + j-- + + if 0 <= j && j < len(m.stores) { + return m.stores[j].objectClient, nil + } + + // should in theory never happen + return nil, fmt.Errorf("no store found for timestamp %s", ts) +} + +func (m *MultiStore) GetAttributes(ctx context.Context, objectKey string) (client.ObjectAttributes, error) { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return client.ObjectAttributes{}, err + } + return s.GetAttributes(ctx, objectKey) +} + +func (m *MultiStore) ObjectExists(ctx context.Context, objectKey string) (bool, error) { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return false, err + } + return s.ObjectExists(ctx, objectKey) +} + +func (m *MultiStore) PutObject(ctx context.Context, objectKey string, object io.Reader) error { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return err + } + return s.PutObject(ctx, objectKey, object) +} + +func (m *MultiStore) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, int64, error) { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return nil, 0, err + } + return s.GetObject(ctx, objectKey) +} + +func (m *MultiStore) GetObjectRange(ctx context.Context, objectKey string, off, length int64) (io.ReadCloser, error) { + sp, _ := opentracing.StartSpanFromContext(ctx, "GetObjectRange") + if sp != nil { + sp.LogKV("objectKey", objectKey, "off", off, "length", length) + } + defer sp.Finish() + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return nil, err + } + return s.GetObjectRange(ctx, objectKey, off, length) +} + +func (m *MultiStore) List(ctx context.Context, prefix string, delimiter string) ([]client.StorageObject, []client.StorageCommonPrefix, error) { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return nil, nil, err + } + return s.List(ctx, prefix, delimiter) +} + +func (m *MultiStore) DeleteObject(ctx context.Context, objectKey string) error { + s, err := m.GetStoreFor(model.Now()) + if err != nil { + return err + } + return s.DeleteObject(ctx, objectKey) +} + +func (m *MultiStore) IsObjectNotFoundErr(err error) bool { + s, _ := m.GetStoreFor(model.Now()) + if s == nil { + return false + } + return s.IsObjectNotFoundErr(err) +} + +func (m *MultiStore) IsRetryableErr(err error) bool { + s, _ := m.GetStoreFor(model.Now()) + if s == nil { + return false + } + return s.IsRetryableErr(err) +} + +func (m *MultiStore) Stop() { + for _, s := range m.stores { + s.objectClient.Stop() + } +} diff --git a/pkg/blockbuilder/storage_test.go b/pkg/blockbuilder/storage_test.go new file mode 100644 index 0000000000000..8fc6b237e132d --- /dev/null +++ b/pkg/blockbuilder/storage_test.go @@ -0,0 +1,37 @@ +package blockbuilder + +import ( + "os" + "testing" + + "github.com/prometheus/common/model" + + "github.com/grafana/loki/v3/pkg/storage" + "github.com/grafana/loki/v3/pkg/storage/chunk/client/local" + "github.com/grafana/loki/v3/pkg/storage/config" +) + +var metrics *storage.ClientMetrics + +func NewTestStorage(t testing.TB) (*MultiStore, error) { + if metrics == nil { + m := storage.NewClientMetrics() + metrics = &m + } + dir := t.TempDir() + t.Cleanup(func() { + os.RemoveAll(dir) + metrics.Unregister() + }) + cfg := storage.Config{ + FSConfig: local.FSConfig{ + Directory: dir, + }, + } + return NewMultiStore([]config.PeriodConfig{ + { + From: config.DayTime{Time: model.Now()}, + ObjectType: "filesystem", + }, + }, cfg, *metrics) +} diff --git a/pkg/blockbuilder/tsdb.go b/pkg/blockbuilder/tsdb.go new file mode 100644 index 0000000000000..8af463fcd27da --- /dev/null +++ b/pkg/blockbuilder/tsdb.go @@ -0,0 +1,328 @@ +package blockbuilder + +import ( + "bytes" + "context" + "fmt" + "io" + "sync" + "time" + + "github.com/cespare/xxhash/v2" + "github.com/go-kit/log/level" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/labels" + + "github.com/grafana/loki/v3/pkg/compression" + "github.com/grafana/loki/v3/pkg/storage/config" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" + util_log "github.com/grafana/loki/v3/pkg/util/log" +) + +// TsdbCreator accepts writes and builds TSDBs. +type TsdbCreator struct { + // Function to build a TSDB from the current state + + mtx sync.RWMutex + shards int + heads *tenantHeads +} + +// new creates a new HeadManager +func newTsdbCreator() *TsdbCreator { + m := &TsdbCreator{ + shards: 1 << 5, // 32 shards + } + m.reset() + + return m +} + +// reset updates heads +func (m *TsdbCreator) reset() { + m.heads = newTenantHeads(m.shards) +} + +// Append adds a new series for the given user +func (m *TsdbCreator) Append(userID string, ls labels.Labels, fprint uint64, chks index.ChunkMetas) error { + m.mtx.RLock() + defer m.mtx.RUnlock() + + // TODO(owen-d): safe to remove? + // Remove __name__="logs" as it's not needed in TSDB + b := labels.NewBuilder(ls) + b.Del(labels.MetricName) + ls = b.Labels() + + // Just append to heads, no WAL needed + m.heads.Append(userID, ls, fprint, chks) + return nil +} + +type chunkInfo struct { + chunkMetas index.ChunkMetas + tsdbFormat int +} + +type tsdbWithID struct { + bucket model.Time + data []byte + id tsdb.Identifier +} + +// Create builds a TSDB from the current state using the provided mkTsdb function +func (m *TsdbCreator) create(ctx context.Context, nodeName string, tableRanges []config.TableRange) ([]tsdbWithID, error) { + m.mtx.Lock() + defer m.mtx.Unlock() + + type key struct { + bucket model.Time + prefix string + } + periods := make(map[key]*tsdb.Builder) + + if err := m.heads.forAll( + func(user string, ls labels.Labels, fp uint64, chks index.ChunkMetas) error { + // chunks may overlap index period bounds, in which case they're written to multiple + pds := make(map[key]chunkInfo) + for _, chk := range chks { + idxBuckets := tsdb.IndexBuckets(chk.From(), chk.Through(), tableRanges) + + for _, bucket := range idxBuckets { + k := key{ + bucket: bucket.BucketStart, + prefix: bucket.Prefix, + } + chkinfo := pds[k] + chkinfo.chunkMetas = append(chkinfo.chunkMetas, chk) + chkinfo.tsdbFormat = bucket.TsdbFormat + pds[k] = chkinfo + } + } + + // Embed the tenant label into TSDB + lb := labels.NewBuilder(ls) + lb.Set(index.TenantLabel, user) + withTenant := lb.Labels() + + // Add the chunks to all relevant builders + for pd, chkinfo := range pds { + matchingChks := chkinfo.chunkMetas + b, ok := periods[pd] + if !ok { + b = tsdb.NewBuilder(chkinfo.tsdbFormat) + periods[pd] = b + } + + b.AddSeries( + withTenant, + // use the fingerprint without the added tenant label + // so queries route to the chunks which actually exist. + model.Fingerprint(fp), + matchingChks, + ) + } + + return nil + }, + ); err != nil { + level.Error(util_log.Logger).Log("err", err.Error(), "msg", "building TSDB") + return nil, err + } + + now := time.Now() + res := make([]tsdbWithID, 0, len(periods)) + + for p, b := range periods { + + level.Debug(util_log.Logger).Log( + "msg", "building tsdb for period", + "pd", p, + ) + + // build+move tsdb to multitenant dir + start := time.Now() + dst, data, err := b.BuildInMemory( + ctx, + func(_, _ model.Time, _ uint32) tsdb.Identifier { + return tsdb.NewPrefixedIdentifier( + tsdb.MultitenantTSDBIdentifier{ + NodeName: nodeName, + Ts: now, + }, + p.prefix, + "", + ) + }, + ) + + if err != nil { + return nil, err + } + + level.Debug(util_log.Logger).Log( + "msg", "finished building tsdb for period", + "pd", p, + "dst", dst.Path(), + "duration", time.Since(start), + ) + res = append(res, tsdbWithID{ + bucket: p.bucket, + id: dst, + data: data, + }) + } + + m.reset() + return res, nil +} + +// tenantHeads manages per-tenant series +type tenantHeads struct { + shards int + locks []sync.RWMutex + tenants []map[string]*Head +} + +func newTenantHeads(shards int) *tenantHeads { + t := &tenantHeads{ + shards: shards, + locks: make([]sync.RWMutex, shards), + tenants: make([]map[string]*Head, shards), + } + for i := range t.tenants { + t.tenants[i] = make(map[string]*Head) + } + return t +} + +func (t *tenantHeads) Append(userID string, ls labels.Labels, fprint uint64, chks index.ChunkMetas) { + head := t.getOrCreateTenantHead(userID) + head.Append(ls, fprint, chks) +} + +func (t *tenantHeads) getOrCreateTenantHead(userID string) *Head { + idx := t.shardForTenant(userID) + mtx := &t.locks[idx] + + // Fast path: return existing head + mtx.RLock() + head, ok := t.tenants[idx][userID] + mtx.RUnlock() + if ok { + return head + } + + // Slow path: create new head + mtx.Lock() + defer mtx.Unlock() + + head, ok = t.tenants[idx][userID] + if !ok { + head = NewHead(userID) + t.tenants[idx][userID] = head + } + return head +} + +func (t *tenantHeads) shardForTenant(userID string) uint64 { + return xxhash.Sum64String(userID) & uint64(t.shards-1) +} + +// forAll iterates through all series in all tenant heads +func (t *tenantHeads) forAll(fn func(user string, ls labels.Labels, fp uint64, chks index.ChunkMetas) error) error { + for i, shard := range t.tenants { + t.locks[i].RLock() + defer t.locks[i].RUnlock() + + for user, tenant := range shard { + if err := tenant.forAll(func(ls labels.Labels, fp uint64, chks index.ChunkMetas) error { + return fn(user, ls, fp, chks) + }); err != nil { + return err + } + } + } + return nil +} + +// Head manages series for a single tenant +type Head struct { + userID string + series map[uint64]*series + mtx sync.RWMutex +} + +type series struct { + labels labels.Labels + chks []index.ChunkMeta +} + +func NewHead(userID string) *Head { + return &Head{ + userID: userID, + series: make(map[uint64]*series), + } +} + +func (h *Head) Append(ls labels.Labels, fp uint64, chks index.ChunkMetas) { + h.mtx.Lock() + defer h.mtx.Unlock() + + s, ok := h.series[fp] + if !ok { + s = &series{labels: ls} + h.series[fp] = s + } + s.chks = append(s.chks, chks...) +} + +func (h *Head) forAll(fn func(ls labels.Labels, fp uint64, chks index.ChunkMetas) error) error { + h.mtx.RLock() + defer h.mtx.RUnlock() + + for fp, s := range h.series { + if err := fn(s.labels, fp, s.chks); err != nil { + return err + } + } + return nil +} + +type uploader struct { + store *MultiStore +} + +func newUploader(store *MultiStore) *uploader { + return &uploader{store: store} +} + +func (u *uploader) Put(ctx context.Context, db tsdbWithID) error { + client, err := u.store.GetStoreFor(db.bucket) + if err != nil { + return err + } + + reader := bytes.NewReader(db.data) + gzipPool := compression.GetWriterPool(compression.GZIP) + buf := bytes.NewBuffer(make([]byte, 0, 1<<20)) + compressedWriter := gzipPool.GetWriter(buf) + defer gzipPool.PutWriter(compressedWriter) + + _, err = io.Copy(compressedWriter, reader) + if err != nil { + return err + } + + err = compressedWriter.Close() + if err != nil { + return err + } + + return client.PutObject(ctx, db.id.Path(), buf) +} + +func buildFileName(indexName string) string { + return fmt.Sprintf("%s.gz", indexName) +} diff --git a/pkg/kafka/partition/reader.go b/pkg/kafka/partition/reader.go index 827ed079d56a0..a0d360c4a065f 100644 --- a/pkg/kafka/partition/reader.go +++ b/pkg/kafka/partition/reader.go @@ -16,6 +16,10 @@ import ( "github.com/twmb/franz-go/pkg/kerr" "github.com/twmb/franz-go/pkg/kgo" "github.com/twmb/franz-go/pkg/kmsg" + + "github.com/grafana/loki/v3/pkg/kafka" + + "github.com/grafana/loki/v3/pkg/kafka/client" ) type SpecialOffset int @@ -97,6 +101,35 @@ type Reader struct { logger log.Logger } +func NewReader( + cfg kafka.Config, + partitionID int32, + instanceID string, + logger log.Logger, + reg prometheus.Registerer, +) (*Reader, error) { + // Create a new Kafka client for this reader + clientMetrics := client.NewReaderClientMetrics("partition-reader", reg) + c, err := client.NewReaderClient( + cfg, + clientMetrics, + log.With(logger, "component", "kafka-client"), + ) + if err != nil { + return nil, fmt.Errorf("creating kafka client: %w", err) + } + + // Create the reader + return newReader( + c, + cfg.Topic, + partitionID, + cfg.GetConsumerGroup(instanceID, partitionID), + logger, + reg, + ), nil +} + // NewReader creates a new Reader instance func newReader( client *kgo.Client, diff --git a/pkg/kafka/partition/reader_service.go b/pkg/kafka/partition/reader_service.go index 76898f1b9ef45..49dcda1c928b3 100644 --- a/pkg/kafka/partition/reader_service.go +++ b/pkg/kafka/partition/reader_service.go @@ -15,7 +15,6 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/grafana/loki/v3/pkg/kafka" - "github.com/grafana/loki/v3/pkg/kafka/client" ) var errWaitTargetLagDeadlineExceeded = errors.New("waiting for target lag deadline exceeded") @@ -81,27 +80,20 @@ func NewReaderService( logger log.Logger, reg prometheus.Registerer, ) (*ReaderService, error) { - // Create a new Kafka client for this reader - clientMetrics := client.NewReaderClientMetrics("partition-reader", reg) - c, err := client.NewReaderClient( - kafkaCfg, - clientMetrics, - log.With(logger, "component", "kafka-client"), - ) - if err != nil { - return nil, fmt.Errorf("creating kafka client: %w", err) - } // Create the reader - reader := newReader( - c, - kafkaCfg.Topic, + reader, err := NewReader( + kafkaCfg, partitionID, - kafkaCfg.GetConsumerGroup(instanceID, partitionID), + instanceID, logger, reg, ) + if err != nil { + return nil, errors.Wrap(err, "creating kafka reader") + } + return newReaderServiceFromIfc( ReaderConfig{ TargetConsumerLagAtStartup: kafkaCfg.TargetConsumerLagAtStartup, diff --git a/pkg/loki/loki.go b/pkg/loki/loki.go index 3586e21b541d7..ff5c6de1565bd 100644 --- a/pkg/loki/loki.go +++ b/pkg/loki/loki.go @@ -31,6 +31,7 @@ import ( "google.golang.org/grpc/health/grpc_health_v1" "github.com/grafana/loki/v3/pkg/analytics" + "github.com/grafana/loki/v3/pkg/blockbuilder" "github.com/grafana/loki/v3/pkg/bloombuild" "github.com/grafana/loki/v3/pkg/bloomgateway" "github.com/grafana/loki/v3/pkg/compactor" @@ -89,6 +90,7 @@ type Config struct { RulerStorage rulestore.Config `yaml:"ruler_storage,omitempty" doc:"hidden"` IngesterClient ingester_client.Config `yaml:"ingester_client,omitempty"` Ingester ingester.Config `yaml:"ingester,omitempty"` + BlockBuilder blockbuilder.Config `yaml:"block_builder,omitempty"` Pattern pattern.Config `yaml:"pattern_ingester,omitempty"` IndexGateway indexgateway.Config `yaml:"index_gateway"` BloomBuild bloombuild.Config `yaml:"bloom_build,omitempty" category:"experimental"` @@ -183,6 +185,7 @@ func (c *Config) RegisterFlags(f *flag.FlagSet) { c.OperationalConfig.RegisterFlags(f) c.Profiling.RegisterFlags(f) c.KafkaConfig.RegisterFlags(f) + c.BlockBuilder.RegisterFlags(f) } func (c *Config) registerServerFlagsWithChangedDefaultValues(fs *flag.FlagSet) { @@ -258,6 +261,9 @@ func (c *Config) Validate() error { if err := c.Ingester.Validate(); err != nil { errs = append(errs, errors.Wrap(err, "CONFIG ERROR: invalid ingester config")) } + if err := c.BlockBuilder.Validate(); err != nil { + errs = append(errs, errors.Wrap(err, "CONFIG ERROR: invalid block_builder config")) + } if err := c.LimitsConfig.Validate(); err != nil { errs = append(errs, errors.Wrap(err, "CONFIG ERROR: invalid limits_config config")) } @@ -372,6 +378,7 @@ type Loki struct { indexGatewayRingManager *lokiring.RingManager partitionRingWatcher *ring.PartitionRingWatcher partitionRing *ring.PartitionInstanceRing + blockBuilder *blockbuilder.BlockBuilder ClientMetrics storage.ClientMetrics deleteClientMetrics *deletion.DeleteRequestClientMetrics @@ -682,6 +689,7 @@ func (t *Loki) setupModuleManager() error { mm.RegisterModule(PatternIngesterTee, t.initPatternIngesterTee, modules.UserInvisibleModule) mm.RegisterModule(PatternIngester, t.initPatternIngester) mm.RegisterModule(PartitionRing, t.initPartitionRing, modules.UserInvisibleModule) + mm.RegisterModule(BlockBuilder, t.initBlockBuilder) mm.RegisterModule(All, nil) mm.RegisterModule(Read, nil) @@ -719,6 +727,7 @@ func (t *Loki) setupModuleManager() error { IndexGatewayRing: {Overrides, MemberlistKV}, PartitionRing: {MemberlistKV, Server, Ring}, MemberlistKV: {Server}, + BlockBuilder: {PartitionRing, Store, Server}, Read: {QueryFrontend, Querier}, Write: {Ingester, Distributor, PatternIngester}, diff --git a/pkg/loki/modules.go b/pkg/loki/modules.go index b8ebc89b64752..726c8cfe52a69 100644 --- a/pkg/loki/modules.go +++ b/pkg/loki/modules.go @@ -35,6 +35,7 @@ import ( "github.com/prometheus/common/model" "github.com/grafana/loki/v3/pkg/analytics" + "github.com/grafana/loki/v3/pkg/blockbuilder" "github.com/grafana/loki/v3/pkg/bloombuild/builder" "github.com/grafana/loki/v3/pkg/bloombuild/planner" bloomprotos "github.com/grafana/loki/v3/pkg/bloombuild/protos" @@ -47,6 +48,8 @@ import ( "github.com/grafana/loki/v3/pkg/distributor" "github.com/grafana/loki/v3/pkg/indexgateway" "github.com/grafana/loki/v3/pkg/ingester" + "github.com/grafana/loki/v3/pkg/kafka/partition" + "github.com/grafana/loki/v3/pkg/kafka/partitionring" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql" "github.com/grafana/loki/v3/pkg/logqlmodel/stats" @@ -134,6 +137,7 @@ const ( Analytics string = "analytics" InitCodec string = "init-codec" PartitionRing string = "partition-ring" + BlockBuilder string = "block-builder" ) const ( @@ -875,6 +879,12 @@ func (t *Loki) updateConfigForShipperStore() { t.Cfg.StorageConfig.BoltDBShipperConfig.Mode = indexshipper.ModeReadOnly t.Cfg.StorageConfig.TSDBShipperConfig.Mode = indexshipper.ModeReadOnly + case t.Cfg.isTarget(BlockBuilder): + // Blockbuilder handles index creation independently of the shipper. + // TODO: introduce Disabled mode for boltdb shipper and set it here. + t.Cfg.StorageConfig.BoltDBShipperConfig.Mode = indexshipper.ModeReadOnly + t.Cfg.StorageConfig.TSDBShipperConfig.Mode = indexshipper.ModeDisabled + default: // All other targets use the shipper store in RW mode t.Cfg.StorageConfig.BoltDBShipperConfig.Mode = indexshipper.ModeReadWrite @@ -1770,6 +1780,61 @@ func (t *Loki) initPartitionRing() (services.Service, error) { return t.partitionRingWatcher, nil } +func (t *Loki) initBlockBuilder() (services.Service, error) { + logger := log.With(util_log.Logger, "component", "block_builder") + + // TODO(owen-d): perhaps refactor to not use the ingester config? + id := t.Cfg.Ingester.LifecyclerConfig.ID + + ingestPartitionID, err := partitionring.ExtractIngesterPartitionID(id) + if err != nil { + return nil, fmt.Errorf("calculating block builder partition ID: %w", err) + } + + reader, err := partition.NewReader( + t.Cfg.KafkaConfig, + ingestPartitionID, + id, + logger, + prometheus.DefaultRegisterer, + ) + if err != nil { + return nil, err + } + + controller, err := blockbuilder.NewPartitionJobController( + reader, + t.Cfg.BlockBuilder.Backoff, + ) + + if err != nil { + return nil, err + } + + objectStore, err := blockbuilder.NewMultiStore(t.Cfg.SchemaConfig.Configs, t.Cfg.StorageConfig, t.ClientMetrics) + if err != nil { + return nil, err + } + + bb, err := blockbuilder.NewBlockBuilder( + id, + t.Cfg.BlockBuilder, + t.Cfg.SchemaConfig.Configs, + t.Store, + objectStore, + logger, + prometheus.DefaultRegisterer, + controller, + ) + + if err != nil { + return nil, err + } + + t.blockBuilder = bb + return t.blockBuilder, nil +} + func (t *Loki) deleteRequestsClient(clientType string, limits limiter.CombinedLimits) (deletion.DeleteRequestsClient, error) { if !t.supportIndexDeleteRequest() || !t.Cfg.CompactorConfig.RetentionEnabled { return deletion.NewNoOpDeleteRequestsStore(), nil diff --git a/pkg/storage/stores/shipper/indexshipper/shipper.go b/pkg/storage/stores/shipper/indexshipper/shipper.go index 5b3037c45b086..2917b1fc7974f 100644 --- a/pkg/storage/stores/shipper/indexshipper/shipper.go +++ b/pkg/storage/stores/shipper/indexshipper/shipper.go @@ -33,6 +33,9 @@ const ( ModeReadOnly = Mode("RO") // ModeWriteOnly is to allow only write operations ModeWriteOnly = Mode("WO") + // ModeDisabled is a no-op implementation which does nothing & does not error. + // It's used by the blockbuilder which handles index operations independently. + ModeDisabled = Mode("NO") // FilesystemObjectStoreType holds the periodic config type for the filesystem store FilesystemObjectStoreType = "filesystem" @@ -142,6 +145,8 @@ type indexShipper struct { func NewIndexShipper(prefix string, cfg Config, storageClient client.ObjectClient, limits downloads.Limits, tenantFilter downloads.TenantFilter, open index.OpenIndexFileFunc, tableRangeToHandle config.TableRange, reg prometheus.Registerer, logger log.Logger) (IndexShipper, error) { switch cfg.Mode { + case ModeDisabled: + return Noop{}, nil case ModeReadOnly, ModeWriteOnly, ModeReadWrite: default: return nil, fmt.Errorf("invalid mode: %v", cfg.Mode) diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go b/pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go index 23a951deacbd6..be0a343309c5c 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go @@ -134,8 +134,8 @@ func setupMultiTenantIndex(t *testing.T, indexFormat int, userStreams map[string dst := NewPrefixedIdentifier( MultitenantTSDBIdentifier{ - nodeName: "test", - ts: ts, + NodeName: "test", + Ts: ts, }, destDir, "", @@ -239,7 +239,7 @@ func TestCompactor_Compact(t *testing.T) { PeriodicTableConfig: config.PeriodicTableConfig{Period: config.ObjectStorageIndexRequiredPeriod}}, Schema: "v12", } - indexBkts := indexBuckets(now, now, []config.TableRange{periodConfig.GetIndexTableNumberRange(config.DayTime{Time: now})}) + indexBkts := IndexBuckets(now, now, []config.TableRange{periodConfig.GetIndexTableNumberRange(config.DayTime{Time: now})}) tableName := indexBkts[0] lbls1 := mustParseLabels(`{foo="bar", a="b"}`) @@ -497,8 +497,8 @@ func TestCompactor_Compact(t *testing.T) { t.Run(name, func(t *testing.T) { tempDir := t.TempDir() objectStoragePath := filepath.Join(tempDir, objectsStorageDirName) - tablePathInStorage := filepath.Join(objectStoragePath, tableName.prefix) - tableWorkingDirectory := filepath.Join(tempDir, workingDirName, tableName.prefix) + tablePathInStorage := filepath.Join(objectStoragePath, tableName.Prefix) + tableWorkingDirectory := filepath.Join(tempDir, workingDirName, tableName.Prefix) require.NoError(t, util.EnsureDirectory(objectStoragePath)) require.NoError(t, util.EnsureDirectory(tablePathInStorage)) @@ -551,7 +551,7 @@ func TestCompactor_Compact(t *testing.T) { objectClient, err := local.NewFSObjectClient(local.FSConfig{Directory: objectStoragePath}) require.NoError(t, err) - _, commonPrefixes, err := objectClient.List(context.Background(), tableName.prefix, "/") + _, commonPrefixes, err := objectClient.List(context.Background(), tableName.Prefix, "/") require.NoError(t, err) initializedIndexSets := map[string]compactor.IndexSet{} @@ -559,19 +559,19 @@ func TestCompactor_Compact(t *testing.T) { existingUserIndexSets := make(map[string]compactor.IndexSet, len(commonPrefixes)) for _, commonPrefix := range commonPrefixes { userID := path.Base(string(commonPrefix)) - idxSet, err := newMockIndexSet(userID, tableName.prefix, filepath.Join(tableWorkingDirectory, userID), objectClient) + idxSet, err := newMockIndexSet(userID, tableName.Prefix, filepath.Join(tableWorkingDirectory, userID), objectClient) require.NoError(t, err) existingUserIndexSets[userID] = idxSet initializedIndexSets[userID] = idxSet } - commonIndexSet, err := newMockIndexSet("", tableName.prefix, tableWorkingDirectory, objectClient) + commonIndexSet, err := newMockIndexSet("", tableName.Prefix, tableWorkingDirectory, objectClient) require.NoError(t, err) // build TableCompactor and compact the index tCompactor := newTableCompactor(context.Background(), commonIndexSet, existingUserIndexSets, func(userID string) (compactor.IndexSet, error) { - idxSet, err := newMockIndexSet(userID, tableName.prefix, filepath.Join(tableWorkingDirectory, userID), objectClient) + idxSet, err := newMockIndexSet(userID, tableName.Prefix, filepath.Join(tableWorkingDirectory, userID), objectClient) require.NoError(t, err) initializedIndexSetsMtx.Lock() @@ -875,9 +875,9 @@ func setupCompactedIndex(t *testing.T) *testContext { schemaCfg := config.SchemaConfig{ Configs: []config.PeriodConfig{periodConfig}, } - indexBuckets := indexBuckets(now, now, []config.TableRange{periodConfig.GetIndexTableNumberRange(config.DayTime{Time: now})}) + indexBuckets := IndexBuckets(now, now, []config.TableRange{periodConfig.GetIndexTableNumberRange(config.DayTime{Time: now})}) tableName := indexBuckets[0] - tableInterval := retention.ExtractIntervalFromTableName(tableName.prefix) + tableInterval := retention.ExtractIntervalFromTableName(tableName.Prefix) // shiftTableStart shift tableInterval.Start by the given amount of milliseconds. // It is used for building chunkmetas relative to start time of the table. shiftTableStart := func(ms int64) int64 { @@ -900,7 +900,7 @@ func setupCompactedIndex(t *testing.T) *testContext { builder.FinalizeChunks() - return newCompactedIndex(context.Background(), tableName.prefix, buildUserID(0), t.TempDir(), periodConfig, builder) + return newCompactedIndex(context.Background(), tableName.Prefix, buildUserID(0), t.TempDir(), periodConfig, builder) } expectedChunkEntries := map[string][]retention.ChunkEntry{ diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/identifier.go b/pkg/storage/stores/shipper/indexshipper/tsdb/identifier.go index 149d41bfa9441..eab26fe643d54 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/identifier.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/identifier.go @@ -161,13 +161,13 @@ func ParseSingleTenantTSDBPath(p string) (id SingleTenantTSDBIdentifier, ok bool } type MultitenantTSDBIdentifier struct { - nodeName string - ts time.Time + NodeName string + Ts time.Time } // Name builds filename with format <file-creation-ts> + `-` + `<nodeName> func (id MultitenantTSDBIdentifier) Name() string { - return fmt.Sprintf("%d-%s.tsdb", id.ts.Unix(), id.nodeName) + return fmt.Sprintf("%d-%s.tsdb", id.Ts.Unix(), id.NodeName) } func (id MultitenantTSDBIdentifier) Path() string { @@ -200,7 +200,7 @@ func parseMultitenantTSDBNameFromBase(name string) (res MultitenantTSDBIdentifie } return MultitenantTSDBIdentifier{ - ts: time.Unix(int64(ts), 0), - nodeName: strings.Join(xs[1:], "-"), + Ts: time.Unix(int64(ts), 0), + NodeName: strings.Join(xs[1:], "-"), }, true } diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go b/pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go index 756d354d1ed61..0766bd058fdf4 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go @@ -62,6 +62,10 @@ const ( fingerprintInterval = 1 << 10 millisecondsInHour = int64(time.Hour / time.Millisecond) + + // reserved; used in multitenant indices to signal the tenant. Eventually compacted away when + // single tenant indices are created. + TenantLabel = "__loki_tenant__" ) type indexWriterStage uint8 diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/index_shipper_querier.go b/pkg/storage/stores/shipper/indexshipper/tsdb/index_shipper_querier.go index b0d1824936d59..6ca252770169e 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/index_shipper_querier.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/index_shipper_querier.go @@ -40,9 +40,9 @@ func (i indexIterFunc) For(_ context.Context, _ int, f func(context.Context, Ind func (i *indexShipperQuerier) indices(ctx context.Context, from, through model.Time, user string) (Index, error) { itr := indexIterFunc(func(f func(context.Context, Index) error) error { // Ensure we query both per tenant and multitenant TSDBs - idxBuckets := indexBuckets(from, through, []config.TableRange{i.tableRange}) + idxBuckets := IndexBuckets(from, through, []config.TableRange{i.tableRange}) for _, bkt := range idxBuckets { - if err := i.shipper.ForEachConcurrent(ctx, bkt.prefix, user, func(multitenant bool, idx shipperindex.Index) error { + if err := i.shipper.ForEachConcurrent(ctx, bkt.Prefix, user, func(multitenant bool, idx shipperindex.Index) error { impl, ok := idx.(Index) if !ok { return fmt.Errorf("unexpected shipper index type: %T", idx) diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/manager.go b/pkg/storage/stores/shipper/indexshipper/tsdb/manager.go index 96f56d7021f45..84c250eb7464c 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/manager.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/manager.go @@ -165,13 +165,13 @@ func (m *tsdbManager) buildFromHead(heads *tenantHeads, indexShipper indexshippe // chunks may overlap index period bounds, in which case they're written to multiple pds := make(map[string]chunkInfo) for _, chk := range chks { - idxBuckets := indexBuckets(chk.From(), chk.Through(), tableRanges) + idxBuckets := IndexBuckets(chk.From(), chk.Through(), tableRanges) for _, bucket := range idxBuckets { - chkinfo := pds[bucket.prefix] + chkinfo := pds[bucket.Prefix] chkinfo.chunkMetas = append(chkinfo.chunkMetas, chk) - chkinfo.tsdbFormat = bucket.tsdbFormat - pds[bucket.prefix] = chkinfo + chkinfo.tsdbFormat = bucket.TsdbFormat + pds[bucket.Prefix] = chkinfo } } @@ -208,8 +208,8 @@ func (m *tsdbManager) buildFromHead(heads *tenantHeads, indexShipper indexshippe dstDir := filepath.Join(managerMultitenantDir(m.dir), fmt.Sprint(p)) dst := NewPrefixedIdentifier( MultitenantTSDBIdentifier{ - nodeName: m.nodeName, - ts: heads.start, + NodeName: m.nodeName, + Ts: heads.start, }, dstDir, "", @@ -300,19 +300,24 @@ func (m *tsdbManager) BuildFromWALs(t time.Time, ids []WALIdentifier, legacy boo return nil } -type indexInfo struct { - prefix string - tsdbFormat int +type IndexInfo struct { + BucketStart model.Time + Prefix string + TsdbFormat int } -func indexBuckets(from, through model.Time, tableRanges config.TableRanges) (res []indexInfo) { +func IndexBuckets(from, through model.Time, tableRanges config.TableRanges) (res []IndexInfo) { start := from.Time().UnixNano() / int64(config.ObjectStorageIndexRequiredPeriod) end := through.Time().UnixNano() / int64(config.ObjectStorageIndexRequiredPeriod) for cur := start; cur <= end; cur++ { cfg := tableRanges.ConfigForTableNumber(cur) if cfg != nil { tsdbFormat, _ := cfg.TSDBFormat() // Ignoring error, as any valid period config should return valid format. - res = append(res, indexInfo{prefix: cfg.IndexTables.Prefix + strconv.Itoa(int(cur)), tsdbFormat: tsdbFormat}) + res = append(res, IndexInfo{ + BucketStart: model.TimeFromUnixNano(cur * int64(config.ObjectStorageIndexRequiredPeriod)), + Prefix: cfg.IndexTables.Prefix + strconv.Itoa(int(cur)), + TsdbFormat: tsdbFormat, + }) } } if len(res) == 0 { diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/manager_test.go b/pkg/storage/stores/shipper/indexshipper/tsdb/manager_test.go new file mode 100644 index 0000000000000..6816b0aeb2085 --- /dev/null +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/manager_test.go @@ -0,0 +1,71 @@ +package tsdb + +import ( + "testing" + "time" + + "github.com/prometheus/common/model" + "github.com/stretchr/testify/require" + + "github.com/grafana/loki/v3/pkg/storage/config" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" + "github.com/grafana/loki/v3/pkg/storage/types" +) + +func TestIndexBuckets(t *testing.T) { + var ( + day0 = model.Time(0) + day1 = day0.Add(24 * time.Hour) + day2 = day1.Add(24 * time.Hour) + periods = []config.PeriodConfig{ + { + From: config.NewDayTime(day0), + Schema: "v12", + IndexType: "tsdb", + IndexTables: config.IndexPeriodicTableConfig{ + PeriodicTableConfig: config.PeriodicTableConfig{ + Prefix: "index/", + Period: 24 * time.Hour, + }, + }, + }, + { + From: config.NewDayTime(day2), + Schema: "v13", + IndexType: "tsdb", + IndexTables: config.IndexPeriodicTableConfig{ + PeriodicTableConfig: config.PeriodicTableConfig{ + Prefix: "index2/", + Period: 24 * time.Hour, + }, + }, + }, + } + + tableRanges = config.GetIndexStoreTableRanges(types.TSDBType, periods) + ) + tests := []struct { + name string + from model.Time + through model.Time + expectedInfo []IndexInfo + }{ + { + name: "single table range", + from: day0, + through: day2, + expectedInfo: []IndexInfo{ + {BucketStart: day0, TsdbFormat: index.FormatV2, Prefix: "index/0"}, + {BucketStart: day1, TsdbFormat: index.FormatV2, Prefix: "index/1"}, + {BucketStart: day2, TsdbFormat: index.FormatV3, Prefix: "index2/2"}, + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := IndexBuckets(tc.from, tc.through, tableRanges) + require.Equal(t, tc.expectedInfo, res) + }) + } +} diff --git a/pkg/storage/stores/shipper/indexshipper/tsdb/store.go b/pkg/storage/stores/shipper/indexshipper/tsdb/store.go index 1ef58c32a1e56..8ca8a2489e6d3 100644 --- a/pkg/storage/stores/shipper/indexshipper/tsdb/store.go +++ b/pkg/storage/stores/shipper/indexshipper/tsdb/store.go @@ -85,6 +85,13 @@ func (s *store) init(name, prefix string, indexShipperCfg indexshipper.Config, s var indices []Index opts := DefaultIndexClientOptions() + // early return in case index shipper is disabled. + if indexShipperCfg.Mode == indexshipper.ModeDisabled { + s.indexWriter = noopIndexWriter{} + s.Reader = NewIndexClient(NoopIndex{}, opts, limits) + return nil + } + if indexShipperCfg.Mode == indexshipper.ModeWriteOnly { // We disable bloom filters on write nodes // for the Stats() methods as it's of relatively little @@ -172,3 +179,9 @@ type failingIndexWriter struct{} func (f failingIndexWriter) Append(_ string, _ labels.Labels, _ uint64, _ tsdbindex.ChunkMetas) error { return fmt.Errorf("index writer is not initialized due to tsdb store being initialized in read-only mode") } + +type noopIndexWriter struct{} + +func (f noopIndexWriter) Append(_ string, _ labels.Labels, _ uint64, _ tsdbindex.ChunkMetas) error { + return nil +}
feat
blockbuilder component (#14621)
5d5affae3b28b5d3a94543a9b88ccba76843b730
2024-11-25 14:39:56
George Robinson
chore: Add context to logger once (#15083)
false
diff --git a/pkg/kafka/partition/reader_service.go b/pkg/kafka/partition/reader_service.go index 6a8d64a6109ca..7e2c3bc3a381c 100644 --- a/pkg/kafka/partition/reader_service.go +++ b/pkg/kafka/partition/reader_service.go @@ -118,7 +118,7 @@ func newReaderService( cfg: cfg, reader: reader, consumerFactory: consumerFactory, - logger: logger, + logger: log.With(logger, "partition", reader.Partition(), "consumer_group", reader.ConsumerGroup()), metrics: newServiceMetrics(reg), lastProcessedOffset: -1, } @@ -131,11 +131,7 @@ func newReaderService( } func (s *ReaderService) starting(ctx context.Context) error { - level.Info(s.logger).Log( - "msg", "starting reader service", - "partition", s.reader.Partition(), - "consumer_group", s.reader.ConsumerGroup(), - ) + level.Info(s.logger).Log("msg", "starting reader service") s.metrics.reportOwnerOfPartition(s.reader.Partition()) s.metrics.reportStarting() @@ -146,11 +142,7 @@ func (s *ReaderService) starting(ctx context.Context) error { } if lastCommittedOffset == int64(KafkaEndOffset) { - level.Warn(s.logger).Log( - "msg", "no committed offset found for partition, starting from the beginning", - "partition", s.reader.Partition(), - "consumer_group", s.reader.ConsumerGroup(), - ) + level.Warn(s.logger).Log("msg", fmt.Sprintf("no committed offset found, starting from %d", kafkaStartOffset)) lastCommittedOffset = int64(KafkaStartOffset) } @@ -178,12 +170,7 @@ func (s *ReaderService) starting(ctx context.Context) error { err = s.processNextFetchesUntilTargetOrMaxLagHonored(ctx, maxLag, targetLag, recordsChan) if err != nil { - level.Error(s.logger).Log( - "msg", "failed to catch up to max lag", - "partition", s.reader.Partition(), - "consumer_group", s.reader.ConsumerGroup(), - "err", err, - ) + level.Error(s.logger).Log("msg", "failed to catch up to max lag", "err", err) return err } } @@ -192,11 +179,7 @@ func (s *ReaderService) starting(ctx context.Context) error { } func (s *ReaderService) running(ctx context.Context) error { - level.Info(s.logger).Log( - "msg", "reader service running", - "partition", s.reader.Partition(), - "consumer_group", s.reader.ConsumerGroup(), - ) + level.Info(s.logger).Log("msg", "reader service running") s.metrics.reportRunning() consumer, err := s.consumerFactory(s.committer)
chore
Add context to logger once (#15083)
9d84a6868b4327a243c6f26e0c5c9954402ada23
2025-02-04 19:40:12
sherinabr
fix: export ExcludedMetadataLabels so it can be extended in GEL (#16083)
false
diff --git a/pkg/util/entry_size.go b/pkg/util/entry_size.go index 4f2c8f0bf82dc..91f0b300010a6 100644 --- a/pkg/util/entry_size.go +++ b/pkg/util/entry_size.go @@ -20,12 +20,12 @@ func EntryTotalSize(entry *push.Entry) int { return len(entry.Line) + StructuredMetadataSize(entry.StructuredMetadata) } -var excludedStructuredMetadataLabels = []string{constants.LevelLabel} +var ExcludedStructuredMetadataLabels = []string{constants.LevelLabel} func StructuredMetadataSize(metas push.LabelsAdapter) int { size := 0 for _, meta := range metas { - if slices.Contains(excludedStructuredMetadataLabels, meta.Name) { + if slices.Contains(ExcludedStructuredMetadataLabels, meta.Name) { continue } size += len(meta.Name) + len(meta.Value)
fix
export ExcludedMetadataLabels so it can be extended in GEL (#16083)
e6e8cbfa13e56bf6cf6f451bd6d9b9e79260ebbd
2021-10-05 22:12:05
Karen Miller
docs: introduce a fundamentals section (#4403)
false
diff --git a/docs/sources/fundamentals/_index.md b/docs/sources/fundamentals/_index.md new file mode 100644 index 0000000000000..14ec169518832 --- /dev/null +++ b/docs/sources/fundamentals/_index.md @@ -0,0 +1,6 @@ +--- +title: Fundamentals +weight: 150 +--- +# Grafana Loki Fundamentals + diff --git a/docs/sources/architecture/_index.md b/docs/sources/fundamentals/architecture/_index.md similarity index 98% rename from docs/sources/architecture/_index.md rename to docs/sources/fundamentals/architecture/_index.md index 27a55844ba5ec..76b40e9071e21 100644 --- a/docs/sources/architecture/_index.md +++ b/docs/sources/fundamentals/architecture/_index.md @@ -1,6 +1,8 @@ --- title: Architecture -weight: 1000 +weight: 200 +aliases: + - /docs/loki/latest/architecture/ --- # Loki's Architecture @@ -173,7 +175,7 @@ Logs from each unique set of labels are built up into "chunks" in memory and then flushed to the backing storage backend. If an ingester process crashes or exits abruptly, all the data that has not yet -been flushed could be lost. Loki is usually configured with a [Write Ahead Log](../operations/storage/wal) which can be _replayed_ on restart as well as with a `replication_factor` (usually 3) of each log to mitigate this risk. +been flushed could be lost. Loki is usually configured with a [Write Ahead Log](../../operations/storage/wal) which can be _replayed_ on restart as well as with a `replication_factor` (usually 3) of each log to mitigate this risk. When not configured to accept out-of-order writes, all lines pushed to Loki for a given stream (unique combination of @@ -189,7 +191,7 @@ nanosecond timestamps: different content, the log line is accepted. This means it is possible to have two different log lines for the same timestamp. -#### Handoff - Deprecated in favor of the [WAL](../operations/storage/wal) +#### Handoff - Deprecated in favor of the [WAL](../../operations/storage/wal) By default, when an ingester is shutting down and tries to leave the hash ring, it will wait to see if a new ingester tries to enter before flushing and will @@ -243,7 +245,7 @@ Caching log (filter, regexp) queries are under active development. ### Querier -The **querier** service handles queries using the [LogQL](../logql/) query +The **querier** service handles queries using the [LogQL](../../logql/) query language, fetching logs both from the ingesters and from long-term storage. Queriers query all ingesters for in-memory data before falling back to diff --git a/docs/sources/architecture/chunks_diagram.png b/docs/sources/fundamentals/architecture/chunks_diagram.png similarity index 100% rename from docs/sources/architecture/chunks_diagram.png rename to docs/sources/fundamentals/architecture/chunks_diagram.png diff --git a/docs/sources/architecture/distributor.md b/docs/sources/fundamentals/architecture/distributor.md similarity index 97% rename from docs/sources/architecture/distributor.md rename to docs/sources/fundamentals/architecture/distributor.md index f0ed888c30cea..2bcbda2bb8b65 100644 --- a/docs/sources/architecture/distributor.md +++ b/docs/sources/fundamentals/architecture/distributor.md @@ -4,8 +4,6 @@ weight: 1000 --- # Distributor Component -This document builds upon the information in the [Loki Architecture](./) page. - Distributors are stateless and communicate with ingesters via [gRPC](https://grpc.io). The quantity of distributors can be increased or decreased as needed. ## Where does it live? @@ -26,7 +24,7 @@ Currently the only way the distributor mutates incoming data is by normalizing l The distributor can also rate limit incoming logs based on the maximum per-tenant bitrate. It does this by checking a per tenant limit and dividing it by the current number of distributors. This allows the rate limit to be specified per tenant at the cluster level and enables us to scale the distributors up or down and have the per-distributor limit adjust accordingly. For instance, say we have 10 distributors and tenant A has a 10MB rate limit. Each distributor will allow up to 1MB/second before limiting. Now, say another large tenant joins the cluster and we need to spin up 10 more distributors. The now 20 distributors will adjust their rate limits for tenant A to `(10MB / 20 distributors) = 500KB/s`! This is how global limits allow much simpler and safer operation of the Loki cluster. -**Note: The distributor uses the `ring` component under the hood to register itself amongst it's peers and get the total number of active distributors. This is a different "key" than the ingesters use in the ring and comes from the distributor's own [ring config](../../configuration#distributor_config).** +**Note: The distributor uses the `ring` component under the hood to register itself amongst it's peers and get the total number of active distributors. This is a different "key" than the ingesters use in the ring and comes from the distributor's own [ring configuration](../../../configuration#distributor_config).** ### Forwarding diff --git a/docs/sources/architecture/loki_architecture_components.svg b/docs/sources/fundamentals/architecture/loki_architecture_components.svg similarity index 100% rename from docs/sources/architecture/loki_architecture_components.svg rename to docs/sources/fundamentals/architecture/loki_architecture_components.svg diff --git a/docs/sources/architecture/modes_of_operation.png b/docs/sources/fundamentals/architecture/modes_of_operation.png similarity index 100% rename from docs/sources/architecture/modes_of_operation.png rename to docs/sources/fundamentals/architecture/modes_of_operation.png diff --git a/docs/sources/getting-started/labels.md b/docs/sources/fundamentals/labels.md similarity index 98% rename from docs/sources/getting-started/labels.md rename to docs/sources/fundamentals/labels.md index 87e8cc3a5c35e..e11bb2b7c2c5e 100644 --- a/docs/sources/getting-started/labels.md +++ b/docs/sources/fundamentals/labels.md @@ -1,5 +1,8 @@ --- title: Labels +weight: 300 +aliases: + - /docs/loki/latest/getting-started/labels/ --- # Labels @@ -189,7 +192,7 @@ Now let's talk about Loki, where the index is typically an order of magnitude sm Loki will effectively keep your static costs as low as possible (index size and memory requirements as well as static log storage) and make the query performance something you can control at runtime with horizontal scaling. -To see how this works, let's look back at our example of querying your access log data for a specific IP address. We don't want to use a label to store the IP. Instead we use a [filter expression](../../logql#filter-expression) to query for it: +To see how this works, let's look back at our example of querying your access log data for a specific IP address. We don't want to use a label to store the IP address. Instead we use a [filter expression](../../logql/log_queries#line-filter-expression) to query for it: ``` {job="apache"} |= "11.11.11.11" diff --git a/docs/sources/overview/_index.md b/docs/sources/fundamentals/overview/_index.md similarity index 92% rename from docs/sources/overview/_index.md rename to docs/sources/fundamentals/overview/_index.md index a0ed54d47d866..06f9f5dd6fab4 100644 --- a/docs/sources/overview/_index.md +++ b/docs/sources/fundamentals/overview/_index.md @@ -1,6 +1,8 @@ --- title: Overview -weight: 150 +weight: 100 +aliases: + - /docs/loki/latest/overview/ --- # Overview @@ -19,7 +21,7 @@ An agent (also called a client) acquires logs, turns the logs into streams, and pushes the streams to Loki through an HTTP API. The Promtail agent is designed for Loki installations, -but many other [Agents](../clients/) seamlessly integrate with Loki. +but many other [Agents](../../clients/) seamlessly integrate with Loki. ![Loki agent interaction](loki-overview-2.png) @@ -28,7 +30,7 @@ Each stream identifies a set of logs associated with a unique set of labels. A quality set of labels is key to the creation of an index that is both compact and allows for efficient query execution. -[LogQL](../logql) is the query language for Loki. +[LogQL](../../logql) is the query language for Loki. ## Loki features diff --git a/docs/sources/overview/comparisons.md b/docs/sources/fundamentals/overview/comparisons.md similarity index 99% rename from docs/sources/overview/comparisons.md rename to docs/sources/fundamentals/overview/comparisons.md index 54338b92fbdc2..11aab75c45a4f 100644 --- a/docs/sources/overview/comparisons.md +++ b/docs/sources/fundamentals/overview/comparisons.md @@ -18,7 +18,7 @@ horizontally-scalable mode data is stored in a cloud storage system such as S3, GCS, or Cassandra. Logs are stored in plaintext form tagged with a set of label names and values, where only the label pairs are indexed. This tradeoff makes it cheaper to operate than a full index and allows developers to aggressively log -from their applications. Logs in Loki are queried using [LogQL](../../logql). +from their applications. Logs in Loki are queried using [LogQL](../../../logql). However, because of this design tradeoff, LogQL queries that filter based on content (i.e., text within the log lines) require loading all chunks within the search window that match the labels defined in the query. diff --git a/docs/sources/overview/loki-overview-1.png b/docs/sources/fundamentals/overview/loki-overview-1.png similarity index 100% rename from docs/sources/overview/loki-overview-1.png rename to docs/sources/fundamentals/overview/loki-overview-1.png diff --git a/docs/sources/overview/loki-overview-2.png b/docs/sources/fundamentals/overview/loki-overview-2.png similarity index 100% rename from docs/sources/overview/loki-overview-2.png rename to docs/sources/fundamentals/overview/loki-overview-2.png
docs
introduce a fundamentals section (#4403)
1115a7743cec6897bee5a00c660dfba5cfba4547
2025-02-17 02:16:07
renovate[bot]
fix(deps): update dependency @radix-ui/react-select to v2.1.6 (main) (#16310)
false
diff --git a/pkg/ui/frontend/package-lock.json b/pkg/ui/frontend/package-lock.json index 78cea544371de..9bc37fb8a3de6 100644 --- a/pkg/ui/frontend/package-lock.json +++ b/pkg/ui/frontend/package-lock.json @@ -1403,31 +1403,6 @@ } } }, - "node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-focus-scope": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz", - "integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.1", - "@radix-ui/react-primitive": "2.0.2", - "@radix-ui/react-use-callback-ref": "1.1.0" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, "node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-portal": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.4.tgz", @@ -1621,13 +1596,13 @@ } }, "node_modules/@radix-ui/react-focus-scope": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.1.tgz", - "integrity": "sha512-01omzJAYRxXdG2/he/+xy+c8a8gCydoQ1yOxnWNcRhrrBW5W+RQJ22EK1SaO8tb3WoUsuEw7mJjBozPzihDFjA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz", + "integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==", "license": "MIT", "dependencies": { "@radix-ui/react-compose-refs": "1.1.1", - "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-primitive": "2.0.2", "@radix-ui/react-use-callback-ref": "1.1.0" }, "peerDependencies": { @@ -1645,6 +1620,47 @@ } } }, + "node_modules/@radix-ui/react-focus-scope/node_modules/@radix-ui/react-primitive": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.2.tgz", + "integrity": "sha512-Ec/0d38EIuvDF+GZjcMU/Ze6MxntVJYO/fRlCPhCaVUyPY9WTalHJw54tp9sXeJo3tlShWpy41vQRgLRGOuz+w==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope/node_modules/@radix-ui/react-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.2.tgz", + "integrity": "sha512-YAKxaiGsSQJ38VzKH86/BPRC4rh+b1Jpa+JneA5LRE7skmLPNAyeG8kPJj/oo4STLvlrs8vkf/iYyc3A5stYCQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-hover-card": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.6.tgz", @@ -2021,31 +2037,6 @@ } } }, - "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-focus-scope": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz", - "integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.1", - "@radix-ui/react-primitive": "2.0.2", - "@radix-ui/react-use-callback-ref": "1.1.0" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-popper": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.2.tgz", @@ -2261,31 +2252,6 @@ } } }, - "node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-focus-scope": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz", - "integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.1", - "@radix-ui/react-primitive": "2.0.2", - "@radix-ui/react-use-callback-ref": "1.1.0" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, "node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-popper": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.2.tgz", @@ -2655,32 +2621,228 @@ } }, "node_modules/@radix-ui/react-select": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.1.5.tgz", - "integrity": "sha512-eVV7N8jBXAXnyrc+PsOF89O9AfVgGnbLxUtBb0clJ8y8ENMWLARGMI/1/SBRLz7u4HqxLgN71BJ17eono3wcjA==", + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.1.6.tgz", + "integrity": "sha512-T6ajELxRvTuAMWH0YmRJ1qez+x4/7Nq7QIx7zJ0VK3qaEWdnWpNbEDnmWldG1zBDwqrLy5aLMUWcoGirVj5kMg==", "license": "MIT", "dependencies": { "@radix-ui/number": "1.1.0", "@radix-ui/primitive": "1.1.1", - "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-collection": "1.1.2", "@radix-ui/react-compose-refs": "1.1.1", "@radix-ui/react-context": "1.1.1", "@radix-ui/react-direction": "1.1.0", - "@radix-ui/react-dismissable-layer": "1.1.4", + "@radix-ui/react-dismissable-layer": "1.1.5", "@radix-ui/react-focus-guards": "1.1.1", - "@radix-ui/react-focus-scope": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.2", "@radix-ui/react-id": "1.1.0", - "@radix-ui/react-popper": "1.2.1", - "@radix-ui/react-portal": "1.1.3", - "@radix-ui/react-primitive": "2.0.1", - "@radix-ui/react-slot": "1.1.1", + "@radix-ui/react-popper": "1.2.2", + "@radix-ui/react-portal": "1.1.4", + "@radix-ui/react-primitive": "2.0.2", + "@radix-ui/react-slot": "1.1.2", "@radix-ui/react-use-callback-ref": "1.1.0", "@radix-ui/react-use-controllable-state": "1.1.0", "@radix-ui/react-use-layout-effect": "1.1.0", "@radix-ui/react-use-previous": "1.1.0", - "@radix-ui/react-visually-hidden": "1.1.1", + "@radix-ui/react-visually-hidden": "1.1.2", "aria-hidden": "^1.2.4", - "react-remove-scroll": "^2.6.2" + "react-remove-scroll": "^2.6.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-arrow": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.2.tgz", + "integrity": "sha512-G+KcpzXHq24iH0uGG/pF8LyzpFJYGD4RfLjCIBfGdSLXvjLHST31RUiRVrupIBMvIppMgSzQ6l66iAxl03tdlg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-collection": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.2.tgz", + "integrity": "sha512-9z54IEKRxIa9VityapoEYMuByaG42iSy1ZXlY2KcuLSEtq8x4987/N6m15ppoMffgZX72gER2uHe1D9Y6Unlcw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.2", + "@radix-ui/react-slot": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.5.tgz", + "integrity": "sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-primitive": "2.0.2", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-escape-keydown": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-popper": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.2.tgz", + "integrity": "sha512-Rvqc3nOpwseCyj/rgjlJDYAgyfw7OC1tTkKn2ivhaMGcYt8FSBlahHOZak2i3QwkRXUXgGgzeEe2RuqeEHuHgA==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.2", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.2", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-rect": "1.1.0", + "@radix-ui/react-use-size": "1.1.0", + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-portal": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.4.tgz", + "integrity": "sha512-sn2O9k1rPFYVyKd5LAJfo96JlSGVFpa1fS6UuBJfrZadudiw5tAmru+n1x7aMRQ84qDM71Zh1+SzK5QwU0tJfA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.2", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-primitive": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.2.tgz", + "integrity": "sha512-Ec/0d38EIuvDF+GZjcMU/Ze6MxntVJYO/fRlCPhCaVUyPY9WTalHJw54tp9sXeJo3tlShWpy41vQRgLRGOuz+w==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.2.tgz", + "integrity": "sha512-YAKxaiGsSQJ38VzKH86/BPRC4rh+b1Jpa+JneA5LRE7skmLPNAyeG8kPJj/oo4STLvlrs8vkf/iYyc3A5stYCQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-visually-hidden": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.1.2.tgz", + "integrity": "sha512-1SzA4ns2M1aRlvxErqhLHsBHoS5eI5UUcI2awAMgGUp4LoaoWOKYmvqDY2s/tltuPkh3Yk77YF/r3IRj+Amx4Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.2" }, "peerDependencies": { "@types/react": "*",
fix
update dependency @radix-ui/react-select to v2.1.6 (main) (#16310)
feee240f46c0d09a7ea8fcba19910e9fc96588ed
2024-08-16 16:09:36
Travis Patterson
chore: remove unused pattern tokenization form Loki (#13783)
false
diff --git a/pkg/pattern/tokenization/replacer.go b/pkg/pattern/tokenization/replacer.go deleted file mode 100644 index cc725cb5b9874..0000000000000 --- a/pkg/pattern/tokenization/replacer.go +++ /dev/null @@ -1,900 +0,0 @@ -package tokenization - -import ( - "bytes" - "slices" -) - -var ( - placeholderNumber = []byte("<NUM>") - placeholderHex = []byte("<HEX>") - placeholderUUID = []byte("<UUID>") - placeholderTimestamp = []byte("<TIMESTAMP>") - placeholderDuration = []byte("<DURATION>") - placeholderBytesize = []byte("<BYTESIZE>") - placeholderIP = []byte("<IP>") -) - -// Integer numbers after these words won't be replaced by `<NUM>`. -var numPreservingKeys = [][]byte{[]byte("status"), []byte("status_code"), []byte("httpStatus")} - -const ( - maxYear = 2100 // anything above that is unlikely to be a timestamp... - minHexLen = 12 // 48 bits min for free-standing hex strings (e.g "0123456789ab") or 42 bits for "0xABCDEF1234" strings -) - -var boundaryChars = [256]bool{} - -func init() { - for i := 0; i < 128; i++ { // for now, we don't consider non-ASCII chars as boundary - if i < '0' || (i > '9' && i < 'A') || (i > 'Z' && i < 'a') || i > 'z' { - boundaryChars[i] = true - } - } - - // We need these keys sorted in an ascending length to efficiently compare them. - slices.SortStableFunc(numPreservingKeys, func(a, b []byte) int { - return len(a) - len(b) - }) -} - -type replacer struct { - source, dest []byte - - // This is the last position that was copied to the destination buffer. - tail int - // This is the current position we are working with - cur int - // This is essentially used for lookahed operations - head int - - // Here's some ASCII art to visualize that (the long string of dashes - // visualizes the log line: - // - // 0 <already in dest, copied or replaced > `tail` <about to be copied or replaced> `cur` <lookahead> `head` <remaining unprocessed log> `len(source)` - // |---------------------------------------------|------------------------------------------|---------------------|------------------------------------------| - - // A somewhat hacky solution that allows us to preserve specific numeric - // values we care about, like status and status_code. - preserveNextNumbers bool -} - -// commit advances the current position marker to the lookahead position, i.e. -// we are committing to consume everything we've looked ahead so far. -func (r *replacer) commit() { - r.cur = r.head -} - -func (r *replacer) resetHead() { - r.head = r.cur -} - -func (r *replacer) resetHeadExpr() bool { - r.head = r.cur - return true // useful when included in boolean expressions with advance() -} - -func (r *replacer) backtrack() { - r.head-- -} - -func (r *replacer) consumeUpToCurrent() { - r.tail = r.cur -} - -// advanceUintRet returns the actual value of the number we read, as well as its -// length. The value might overflow for large numbers, so it's also important to -// check the length! -func (r *replacer) advanceUintRet() (val uint, length uint) { - var c byte - for ; r.head < len(r.source); r.head++ { - c = r.source[r.head] - if c < '0' || '9' < c { - break - } - length++ - val = val*10 + uint(c-'0') // TODO: use bitwise trick? - } - - return val, length -} - -func (r *replacer) advanceUintOrRangeRet(lc, hc byte) (length uint) { - var c byte - for ; r.head < len(r.source); r.head++ { - c = r.source[r.head] - if !(('0' <= c && c <= '9') || (lc <= c && c <= hc)) { - break - } - length++ - } - - return length -} - -func (r *replacer) advanceUint() bool { - _, l := r.advanceUintRet() - return l > 0 -} - -func (r *replacer) advanceUintUpTo(val uint, length uint) bool { - foundVal, foundLength := r.advanceUintRet() - return foundLength > 0 && foundVal <= val && foundLength <= length -} - -func (r *replacer) advanceYear() bool { - return r.advanceUintUpTo(maxYear, 4) -} - -func (r *replacer) advanceChar(c byte) bool { - if r.head < len(r.source) && r.source[r.head] == c { - r.head++ - return true - } - return false -} - -func (r *replacer) peekNextIsBoundary() bool { - if r.head >= len(r.source) { - return true // we are at the end of the line - } - return boundaryChars[r.source[r.head]] -} - -func (r *replacer) peekFirstNonInt() (c byte) { - for i := r.head; i < len(r.source); i++ { - c = r.source[i] - if c < '0' || '9' < c { - return c - } - } - return 0 // we can return the 0 value here! -} - -func (r *replacer) peekNext4() (result [4]byte) { - overhead := len(r.source) - r.head - switch { - case overhead > 3: - result[3] = r.source[r.head+3] - fallthrough - case overhead > 2: - result[2] = r.source[r.head+2] - fallthrough - case overhead > 1: - result[1] = r.source[r.head+1] - fallthrough - case overhead > 0: - result[0] = r.source[r.head+0] - } - return result -} - -func (r *replacer) advanceTimeZoneLetters() bool { - UCLetters := 0 - for { - nc, ok := r.advance() - if !ok { - break - } - if nc < 'A' || nc > 'Z' { - r.backtrack() - break - } - UCLetters++ - } - - return UCLetters >= 2 && UCLetters <= 5 -} - -func (r *replacer) advanceNumericTimeZone() bool { - // See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - return r.advanceOneOf('+', '-') && r.advanceUintUpTo(14000, 5) -} - -// helper for handleWeirdTimestamp() -func (r *replacer) advanceStringOrNumericTimeZone(isOptional bool) bool { - curHead := r.head - if r.advanceChar(' ') && r.advanceNumericTimeZone() { - return true - } - r.head = curHead - if r.advanceChar(' ') && r.advanceTimeZoneLetters() { - return true - } - r.head = curHead - return isOptional -} - -func (r *replacer) advanceOneOf(chars ...byte) bool { - if r.head >= len(r.source) { - return false - } - c := r.source[r.head] - - for _, ec := range chars { - if c == ec { - r.head++ - return true - } - } - return false -} - -func (r *replacer) advanceTime(secondsOptional bool) bool { - return r.advanceUintUpTo(24, 2) && r.advanceChar(':') && r.advanceUintUpTo(60, 2) && (secondsOptional || (r.advanceChar(':') && r.advanceUintUpTo(60, 2))) -} - -// Mon|Tue|Wed|Thu|Fri|Sat|Sun -func (r *replacer) advanceDayOfTheWeek() bool { - c1, ok1 := r.advance() - c2, ok2 := r.advance() - c3, ok3 := r.advance() - if !ok1 || !ok2 || !ok3 { - return false - } - return (c1 == 'S' && ((c2 == 'a' && c3 == 't') || (c2 == 'u' && c3 == 'n'))) || // Sat, Sun - (c1 == 'M' && c2 == 'o' && c3 == 'n') || - (c1 == 'T' && c2 == 'u' && c3 == 'e') || - (c1 == 'W' && c2 == 'e' && c3 == 'd') || - (c1 == 'T' && c2 == 'h' && c3 == 'u') || - (c1 == 'F' && c2 == 'r' && c3 == 'i') -} - -// Jan|Feb|Mar|Apr|May|Jul|Jun|Aug|Sep|Oct|Nov|Dec -func (r *replacer) advanceMonthName() bool { - c1, ok1 := r.advance() - c2, ok2 := r.advance() - c3, ok3 := r.advance() - if !ok1 || !ok2 || !ok3 { - return false - } - - return (c1 == 'J' && ((c2 == 'u' && (c3 == 'n' || c3 == 'l')) || // Jun, Jul - (c2 == 'a' && c3 == 'n'))) || // Jan - (c1 == 'M' && c2 == 'a' && (c3 == 'r' || c3 == 'y')) || // Mar, May - (c2 == 'e' && ((c1 == 'F' && c3 == 'b') || (c1 == 'S' && c3 == 'p') || (c1 == 'D' && c3 == 'c'))) || // Feb, Sep, Dec - (c1 == 'A' && ((c2 == 'p' && c3 == 'r') || // Apr - (c2 == 'u' && c3 == 'g'))) || // Aug - (c1 == 'O' && c2 == 'c' && c3 == 't') || // Oct - (c1 == 'N' && c2 == 'o' && c3 == 'v') // Nov -} - -// Check if we in the middle of an UUID, exactly after the first 8 characters -// and the dash after them, e.g after "abcd0123-": -func (r *replacer) advanceUUIDAfterFirstDash(lc, hc byte) (endsWithBoundary bool) { - return (r.advanceUintOrRangeRet(lc, hc) == 4) && r.advanceChar('-') && - (r.advanceUintOrRangeRet(lc, hc) == 4) && r.advanceChar('-') && - (r.advanceUintOrRangeRet(lc, hc) == 4) && r.advanceChar('-') && - (r.advanceUintOrRangeRet(lc, hc) == 12) && r.peekNextIsBoundary() -} - -// Only moves the head forward if it successfully matches a duration -func (r *replacer) advanceDuration() (matched bool) { - curHead := r.head - - var secsLen int - n := r.peekNext4() - if n[0] == 'h' { - r.head++ - if boundaryChars[n[1]] { - return true // e.g. "1h", "123h" - } - if !r.advanceUintUpTo(60, 2) { - goto restore - } - n = r.peekNext4() - } - if n[0] == 'm' && (boundaryChars[n[1]] || n[1] != 's') { // we don't want to match 'ms' here - r.head++ - if boundaryChars[n[1]] { - return true // e.g. "2h21m", "121m" - } - if !(r.advanceUintUpTo(60, 2) && ((r.advanceChar('.') && r.advanceUint()) || true)) { - goto restore - } - n = r.peekNext4() - } - - if n[0] == 's' && boundaryChars[n[1]] { - secsLen = 1 - } else if n[1] == 's' && (n[0] == 'm' || n[0] == 'n' || n[0] == 'u') && boundaryChars[n[2]] { - secsLen = 2 - } else if n[2] == 's' && ((n[0] == 0xC2 && n[1] == 0xB5) || (n[0] == 0xCE && n[1] == 0xBC)) && boundaryChars[n[3]] { - // This checks for the unicode "µs" (U+00B5 = micro symbol) and "μs" (U+03BC = Greek letter mu) - secsLen = 3 - } else { - goto restore - } - - r.head += secsLen - return true - -restore: // should be faster than a defer - r.head = curHead - return false -} - -// 'b' and 'B' are not present here because of the way we check for byte size -// units below. If they were present, then suffixes like 'Bb', 'bb', etc. would -// be considered valid byte sizes. Also, only integer numbers are accepted as -// valid bytesizes in bytes, so we handle bytes with special cases instead. -var byteSizes = [256]bool{'k': true, 'K': true, 'm': true, 'M': true, 'g': true, 'G': true, 't': true, 'T': true, 'p': true, 'P': true} - -// Only moves the head forward if it successfully matches a duration -func (r *replacer) advanceBytesize(c1 byte) (matched bool) { - if !byteSizes[c1] { - return false - } - n := r.peekNext4() - - var unitLen int // not counting the first character c1, which is already advanced to - if (n[0] == 'b' || n[0] == 'B') && boundaryChars[n[1]] { - unitLen = 1 - } else if n[0] == 'i' && (n[1] == 'b' || n[1] == 'B') && boundaryChars[n[2]] { - unitLen = 2 - } else if ((n[0] == 'b' && n[1] == 'p' && n[2] == 's') || (n[0] == 'b' && n[1] == 'i' && n[2] == 't')) && boundaryChars[n[3]] { - unitLen = 3 - } - - if unitLen > 0 { - r.head += unitLen - return true - } - return false -} - -func (r *replacer) advanceSpacedBytesize(canBeBytes bool) (matched bool) { - // Get the next character after the space - c1, hasNext := r.advance() - if !hasNext { - return false - } - if canBeBytes && (c1 == 'b' || c1 == 'B') && r.peekNextIsBoundary() { - return true - } - if r.advanceBytesize(c1) { - return true - } - r.backtrack() - return false -} - -func (r *replacer) advance() (c byte, advanced bool) { - if r.head >= len(r.source) { - return 0, false - } - - c = r.source[r.head] - r.head++ - return c, true -} - -func (r *replacer) emitNumber() { - r.commit() - r.dest = append(r.dest, placeholderNumber...) - r.consumeUpToCurrent() -} - -func (r *replacer) emitNumberOrCopyText(hasMinusPrefix bool) { - r.commit() - if !r.preserveNextNumbers { - r.dest = append(r.dest, placeholderNumber...) - r.consumeUpToCurrent() - } else { - r.maybeEmitDash(hasMinusPrefix) - r.copyUpToCurrent() - } -} - -func (r *replacer) emit(hasMinusPrefix bool, placeholder []byte) { - r.commit() - r.maybeEmitDash(hasMinusPrefix) - r.dest = append(r.dest, placeholder...) - r.consumeUpToCurrent() -} - -func (r *replacer) maybeEmitDash(hasMinusPrefix bool) { - // This minus was actually a dash, so we just copy it to the result - if hasMinusPrefix { - r.dest = append(r.dest, '-') - } -} - -func (r *replacer) copyUpToCurrent() { - r.dest = append(r.dest, r.source[r.tail:r.cur]...) - r.consumeUpToCurrent() -} - -func (r *replacer) handleHexOrUnit(hasMinusPrefix bool, n1, l1 uint, c1 byte) (endsWithBoundary bool) { - // Special case that is likely a hex string of the format "0x", but we don't - // know whether the rest is upper case or lower case yet. - zeroHex := false - if n1 == 0 && l1 == 1 && c1 == 'x' { - zeroHex = true // these cannot be the start of an UUID - c1 = r.peekFirstNonInt() - } - - // Special case, this might be a byte size - if (c1 == 'b' || c1 == 'B') && r.peekNextIsBoundary() { - // We do not subsume a minus sign - byte sizes are unlikely to be - // negative, it's more likely this is a dash as a part of a range - r.emit(hasMinusPrefix, placeholderBytesize) - return true - } - - // Maybe we are at the start of a hex string, either something like - // "[0-9]+[a-f]", "[0-9]+[A-F]", or "0x". We support both lower and upper - // case letters, but to avoid false positives, we want hex replacements to - // happen only if the strings are fully lower case or fully upper case. - if 'a' <= c1 && c1 <= 'f' { - return r.handleHex(hasMinusPrefix, l1+1, 'a', 'f', !zeroHex) - } else if 'A' <= c1 && c1 <= 'F' { - return r.handleHex(hasMinusPrefix, l1+1, 'A', 'F', !zeroHex) - } else if zeroHex { - // Well, it probably wasn't a zero-hex after all, or it contained only - // digits, so try to handle that or emit what we absorbed - _, l2 := r.advanceUintRet() - if l2+2 >= minHexLen { // We consider "0x" to be part of the hex string when comparing with minHexLen - r.emit(hasMinusPrefix, placeholderHex) - } else { - r.maybeEmitDash(hasMinusPrefix) - r.commit() - r.copyUpToCurrent() - } - return r.peekNextIsBoundary() - } - - return r.handlePotentialUnitWithDecimal(hasMinusPrefix, c1) -} - -func (r *replacer) handleHex(hasMinusPrefix bool, l1 uint, lc, hc byte, canBeUUID bool) (endsWithBoundary bool) { - totalLen := l1 + r.advanceUintOrRangeRet(lc, hc) - r.commit() - - if totalLen == 8 && canBeUUID { - // We might be at the first part of a UUID, right before the first dash - if r.advanceChar('-') && r.advanceUUIDAfterFirstDash(lc, hc) { - r.emit(hasMinusPrefix, placeholderUUID) - return true - } - r.resetHead() - } - - if totalLen >= minHexLen && r.peekNextIsBoundary() { - r.emit(hasMinusPrefix, placeholderHex) - return true - } - - r.copyUpToCurrent() - return r.peekNextIsBoundary() -} - -func (r *replacer) handlePotentialUnitWithDecimal(hasMinusPrefix bool, c1 byte) (endsWithBoundary bool) { - if r.advanceBytesize(c1) { - // We do not subsume a minus sign - byte sizes are unlikely to be - // negative, it's more likely this is a dash as a part of a range - r.emit(hasMinusPrefix, placeholderBytesize) - return true - } - - r.backtrack() - if r.advanceDuration() { - // We subsume hasMinusPrefix, since durations can be negative - r.emit(false, placeholderDuration) - return true - } - - // We couldn't match anything, so just copy what existed. - r.maybeEmitDash(hasMinusPrefix) - r.copyUpToCurrent() - return false -} - -func (r *replacer) handleNumberWithDecimal(hasMinusPrefix bool, n1 uint, l1 uint) (endsWithBoundary bool) { - n2, l2 := r.advanceUintRet() - if l2 == 0 { - // The dot wasn't followed by another number, so emit everything before it. - r.backtrack() - r.emitNumberOrCopyText(hasMinusPrefix) - return false - } - - // See if the number after the decimal is also followed by a boundary - b2, hasNext := r.advance() - - // We are at the end of the string, which is a boundary, replace evertything - // up to now with a number - if !hasNext { - r.emitNumber() // this also subsumes any minus sign we had - return true - } - - // The decimal number isn't followed by a boundary char (which include - // things like '.', ':', '/', etc.), so the part after the decimal is either - // not a real number, or it's some sort of a unit that can support decimals - // like size (e.g. 12KB, 3MiB) or durations (e.g. 3.5124s), etc. - if !boundaryChars[b2] { - return r.handlePotentialUnitWithDecimal(hasMinusPrefix, b2) - } - - // This can be a byte size with a space, e.g. "3.14 GiB" - if b2 == ' ' && r.advanceSpacedBytesize(false) { - // We do not subsume a minus sign - byte sizes are unlikely to be - // negative, it's more likely this is a dash as a part of a range - r.emit(hasMinusPrefix, placeholderBytesize) - return true - } - - // We have a decimal number followed by a non-dot boundary, so this is not - // an IP or a version number or anything like that. - if b2 != '.' { - r.backtrack() - r.emitNumber() - return true - } - - n3, l3 := r.advanceUintRet() - if l3 == 0 || !r.peekNextIsBoundary() { - // The second dot wasn't followed by another number and a boundary, so - // emit just the first number. - r.resetHead() - r.emitNumber() - return true - } - - // We have "<NUM>.<NUM>.<NUM>" at this point, so we either have something - // like a version number, or an IP address, but certainly not a simple - // decimal number we can just emit. - r.commit() - - // Check if this is an IP address... - if n1 <= 255 && l1 <= 3 && n2 <= 255 && l2 <= 3 && n3 <= 255 && l3 <= 3 && r.advanceChar('.') && r.advanceUintUpTo(255, 3) && r.peekNextIsBoundary() { - r.emit(hasMinusPrefix, placeholderIP) - return true - } - - // This wasn't an IP after all, so just emit "<NUM>.<NUM>.<NUM>". We don't - // want to assume this is a simple decimal number because of the second dot, - // e.g. this might be something like a version number. - r.resetHead() - r.maybeEmitDash(hasMinusPrefix) // we preserve the dashes here, since it's likely not a minus - r.dest = append(r.dest, placeholderNumber...) - r.dest = append(r.dest, '.') - r.dest = append(r.dest, placeholderNumber...) - r.dest = append(r.dest, '.') - r.dest = append(r.dest, placeholderNumber...) - r.consumeUpToCurrent() - return true -} - -func (r *replacer) handleSaneTimestamp(hasMinusPrefix bool, n1 uint, delim byte) (endsWithBoundary bool) { - if r.advanceUintUpTo(12, 2) && r.advanceChar(delim) && r.advanceUintUpTo(31, 2) && r.advanceOneOf('T', ' ') && r.advanceTime(false) { - r.commit() - // continue down to parsing sub-second and timezone values - } else if r.resetHeadExpr() && n1 <= 31 && r.advanceChar(delim) && r.advanceMonthName() && r.advanceChar(delim) && r.advanceYear() && r.advanceChar(':') && r.advanceTime(false) && r.advanceChar(' ') && r.advanceNumericTimeZone() && r.peekNextIsBoundary() { - // We might not have a sane timestamp, but apparently a not-so-sane - // timestamp format first, e.g. "27/Mar/2024:14:34:37 +0000"... - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } else { - // Apparently that wasn't it either, we probably just have a dash or - // forward slash after a number, so we backtrack and emit the number. - r.resetHead() - r.emitNumberOrCopyText(hasMinusPrefix) - return true - } - - // We have a date that looks like `YY[YY]-MM-DD hh:mm:ss` or - // `YY[YY]/MM/DDZhh:mm:ss` - r.commit() // we want to keep this - - // Now we need to also check for sub-second precision and time zones: - c, canAdvance := r.advance() - if !canAdvance { - // End of the string - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } - if c == '.' { - _, intl := r.advanceUintRet() - if intl == 0 { - // No sub-second precision, the dot was not part of the timestamp - r.backtrack() - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } - - // We had sub-second precision, capture that too - r.commit() - - // Get the next char to see if we have time zone - c, canAdvance = r.advance() - if !canAdvance { - // We are at the end of the sting after we captured the - // sub-second value. - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } - } - - if c == 'Z' || c == 'z' { - //UTC string, nothing to do after that - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } - // See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - if (c == '+' || c == '-') && r.advanceUintUpTo(14, 2) && r.advanceChar(':') && r.advanceUintUpTo(60, 2) { - // e.g. "2020-09-30T00:00:59.9999+03:00" - r.commit() - } else if r.resetHeadExpr() && r.advanceChar(' ') && r.advanceNumericTimeZone() && r.advanceChar(' ') && r.advanceTimeZoneLetters() && r.peekNextIsBoundary() { - // e.g. "2023-09-05 23:20:28.030285153 +0000 UTC" - r.commit() - } else { - r.resetHead() - } - r.emit(hasMinusPrefix, placeholderTimestamp) - return true -} - -func (r *replacer) handleNumberStart(hasMinusPrefix bool) (endsWithBoundary bool) { - r.resetHead() // keep the head pos in sync with the current pos - // We know we were at a digit due to how handleNumber() is called - n1, l1 := r.advanceUintRet() - r.commit() // we will consume this one way or another for sure - - // See if the number is followed by a boundary - b1, hasNext := r.advance() - - switch { - // We are at the end of the string, which is a boundary, replace evertything - // up to now with a number - case !hasNext: - r.emitNumberOrCopyText(hasMinusPrefix) // this also may subsume any minus sign we had - return true - - // The number isn't followed by a boundary char (which include things like - // '.', ' ', '/', etc.), so it's either not a real number or date, or it's - // some sort of a unit like a duration (e.g. 3h5m2s), size, (e.g. 12KB, - // 3MiB), etc. - case !boundaryChars[b1]: - return r.handleHexOrUnit(hasMinusPrefix, n1, l1, b1) - - // We have a decimal point, so this can either be a plain number, a unit - // that can have a float value, or an IP address. - case b1 == '.': - return r.handleNumberWithDecimal(hasMinusPrefix, n1, l1) - - // This might be a timestamp that looks like '2024-04-01...' or - // `2024/03/27...`; timestamps in the far future are not supported :) - case n1 <= maxYear && l1 <= 4 && (b1 == '-' || b1 == '/'): - return r.handleSaneTimestamp(hasMinusPrefix, n1, b1) - - // This might be a byte size with a space, e.g. "2 b", "3 GiB" - case b1 == ' ' && r.advanceSpacedBytesize(true): - r.emit(hasMinusPrefix, placeholderBytesize) - return true - - // Weird RFC822 dates like "02 Jan 06 15:04 MST" - case n1 <= 31 && l1 <= 2 && b1 == ' ': - if r.advanceMonthName() && r.advanceChar(' ') && r.advanceYear() && r.advanceChar(' ') && r.advanceTime(true) && r.advanceStringOrNumericTimeZone(false) { - r.commit() - r.emit(hasMinusPrefix, placeholderTimestamp) - return true - } - // if not, go to default handler after switch statement - - // It could be a UUID that starts with 8 digits - case l1 == 8 && b1 == '-': - if r.advanceUUIDAfterFirstDash('a', 'f') || (r.resetHeadExpr() && r.advanceChar('-') && r.advanceUUIDAfterFirstDash('A', 'F')) { - r.emit(hasMinusPrefix, placeholderUUID) - return true - } - // if not, go to default handler after switch statement - } - - // Number with an unknown boundary - emit the number and leave the boundary - // for the following passes. - r.resetHead() - r.emitNumberOrCopyText(hasMinusPrefix) - return true -} - -var longDayNames = [...][]byte{ - []byte("Sunday"), - []byte("Monday"), - []byte("Tuesday"), - []byte("Wednesday"), - []byte("Thursday"), - []byte("Friday"), - []byte("Saturday"), -} - -func (r *replacer) handleWeirdTimestamp() (endsWithBoundary bool) { - r.resetHead() - - if r.advanceDayOfTheWeek() { - r.commit() // we will always consume this - - // RFC1123 and RFC1123Z, e.g.: - // - "Mon, 02 Jan 2006 15:04:05 MST" - // - "Mon, 02 Jan 2006 15:04:05 -0700" - if r.advanceChar(',') && r.advanceChar(' ') && r.advanceUintUpTo(31, 2) && r.advanceChar(' ') && r.advanceMonthName() && r.advanceChar(' ') && r.advanceYear() && r.advanceChar(' ') && r.advanceTime(false) && r.advanceStringOrNumericTimeZone(false) { - r.emit(false, placeholderTimestamp) - return true - } - r.resetHead() - - // ANSIC, UnixDatem, RubyDate e.g - // - "Mon Jan 2 15:04:05 2006" - // - "Mon Jan 2 15:04:05 MST 2006" - // - "Mon Jan 02 15:04:05 -0700 2006" - if r.advanceChar(' ') && r.advanceMonthName() && r.advanceChar(' ') && (r.advanceChar(' ') || true) && r.advanceUintUpTo(31, 2) && r.advanceChar(' ') && r.advanceTime(false) && r.advanceStringOrNumericTimeZone(true) && r.advanceChar(' ') && r.advanceYear() { - r.emit(false, placeholderTimestamp) - return true - } - r.resetHead() - - // Linux, e.g. - // - "Mon 2 Jan 15:04:05 MST 2006" - // - "Tue 23 Jan 15:04:05 -0700 2023" - if r.advanceChar(' ') && (r.advanceChar(' ') || true) && r.advanceUintUpTo(31, 2) && r.advanceChar(' ') && r.advanceMonthName() && r.advanceChar(' ') && r.advanceTime(false) && r.advanceStringOrNumericTimeZone(false) && r.advanceChar(' ') && r.advanceYear() { - r.emit(false, placeholderTimestamp) - return true - } - r.resetHead() - - // RFC850, e.g. - // - "Monday, 02-Jan-06 15:04:05 MST" - backtrackedSlice := r.source[r.head-3:] - var matchedDay []byte - for _, dw := range longDayNames { - if bytes.HasPrefix(backtrackedSlice, dw) { - matchedDay = dw - break - } - } - if matchedDay != nil { - r.head += len(matchedDay) - 3 - if r.advanceChar(',') && r.advanceChar(' ') && r.advanceUintUpTo(31, 2) && r.advanceChar('-') && r.advanceMonthName() && r.advanceChar('-') && r.advanceUintUpTo(99, 2) && r.advanceChar(' ') && r.advanceTime(false) && r.advanceStringOrNumericTimeZone(true) { - r.emit(false, placeholderTimestamp) - return true - } - } - - r.cur -= 3 // unconsume - r.resetHead() - return false - } - r.resetHead() - - if r.advanceMonthName() { - r.commit() // provisionally consume this - - // Linux journald logs and others similar like this: - // - Feb 29 23:00:14 - // - Apr-10 23:43:46.807 - // - Jul 1 00:21:28 - if (r.advanceChar('-') || (r.advanceChar(' ') && (r.advanceChar(' ') || true))) && r.advanceUintUpTo(31, 2) && r.advanceChar(' ') && r.advanceTime(false) { - r.commit() - // This is already a timestamp, but let's try to match subseconds as well - if r.advanceChar('.') && r.advanceUint() { - r.commit() - } else { - r.resetHead() - } - r.emit(false, placeholderTimestamp) - return true - } - r.cur -= 3 // unconsume - r.resetHead() - return false - } - r.resetHead() - - return false -} - -func (r *replacer) wasNumPreservingKeyword() bool { - for _, key := range numPreservingKeys { - pPos := r.cur - 1 - len(key) - if pPos < -1 { - return false // all subsequent keys are longer - } - if pPos != -1 && !boundaryChars[r.source[pPos]] { - continue - } - if bytes.HasPrefix(r.source[pPos+1:], key) { - return true - } - } - return false -} - -func (r *replacer) replaceWithPlaceholders() { - lineLen := len(r.source) - - var c byte - onBoundary := true - for r.cur = 0; r.cur < lineLen; r.cur++ { - c = r.source[r.cur] - switch { - // If we're currently not at a boundary, the only thing we need to check - // is whether the current char would create a boundary in the next iteration. - case !onBoundary: - onBoundary = boundaryChars[c] - - // We weren't at a boundary and now we are, so check if we match one - // of the special keywords that will preserve numbers - if onBoundary { - r.preserveNextNumbers = r.wasNumPreservingKeyword() - } - - // If we've reached this far, it means we're currently at a boundary! - - // A lot of very complex logic if we encounter a number at a boundary, - // so we move that to a helper function. - case '0' <= c && c <= '9': - r.copyUpToCurrent() - onBoundary = r.handleNumberStart(false) - - // Handle negative numbers, potentially - case c == '-': - next := r.cur + 1 - // This might be a number, a date, an IP address, etc. So we don't - // know if this is a minus sign to replace or a dash to copy yet. - if next < lineLen && '0' <= r.source[next] && r.source[next] <= '9' { - // Copy everything before the dash, but mark it as consumed. - r.copyUpToCurrent() - r.cur++ - r.consumeUpToCurrent() - onBoundary = r.handleNumberStart(true) - } else { - onBoundary = true - } - - // Try to match weird timestamps. They require a lot of remaining - // length, generally start with a capitalized day of the week or month - // name (1 upper case letter followed by 2 lower case letters). - // - // We are basically looking for something that may match this here: - // Mon|Tue|Wed|Thu|Fri|Sat|Sun|Jan|Feb|Mar|Apr|May|Jul|Jun|Aug|Sep|Oct|Nov|Dec - // - // The detailed check would be performed by the actual handler: - case 'A' <= c && c <= 'W' && lineLen-r.cur >= 14 && - 'a' <= r.source[r.cur+1] && r.source[r.cur+1] <= 'u' && - 'b' <= r.source[r.cur+2] && r.source[r.cur+2] <= 'y': - r.copyUpToCurrent() - onBoundary = r.handleWeirdTimestamp() - - // This could be the start of an lower case hex string: - case 'a' <= c && c <= 'f': - r.copyUpToCurrent() - r.resetHead() - onBoundary = r.handleHex(false, 0, 'a', 'f', true) - - // This could be the start of an upper case hex string: - case 'A' <= c && c <= 'F': - r.copyUpToCurrent() - r.resetHead() - onBoundary = r.handleHex(false, 0, 'A', 'F', true) - - // If we haven't actually matched anything, update whether we're still - // on a boundary character and continue onto the next one. - default: - onBoundary = boundaryChars[c] - } - } - - if r.cur > r.tail { - r.dest = append(r.dest, r.source[r.tail:]...) - r.consumeUpToCurrent() - } -} - -func Preprocess(content []byte) []byte { - // ~floor(120%), to allow for some expansion from replacements, hopefully - // without needing to allocate more memory - r := replacer{source: content, dest: make([]byte, 0, len(content)*120/100)} - r.replaceWithPlaceholders() - return r.dest -} diff --git a/pkg/pattern/tokenization/tokenization.go b/pkg/pattern/tokenization/tokenization.go deleted file mode 100644 index 52b239d049c7f..0000000000000 --- a/pkg/pattern/tokenization/tokenization.go +++ /dev/null @@ -1,198 +0,0 @@ -package tokenization - -import ( - "unsafe" -) - -const placeholderEndOfLine = "<...>" - -// Outside of quoted strings, these are the delimiters between tokens. However, -// they are not going to be a part of the tokens themselves and will be replaced -// by spaces in the actual log template. -var delimiters = [256]bool{0: true, '\t': true, '\n': true, '\v': true, '\f': true, '\r': true, ' ': true} - -type tokenizer struct { - // Input - rawLine []byte - maxTokens int - - // State and position iterators - buf []byte - tpos int - tokenCount int - maybeJSON bool - - // Result values, the values in the `tokens` slice reference line and shouldn't - // allocate new memory. - line string - tokens []string -} - -func (t *tokenizer) countOrSaveToken(endTokenPos int) { - if t.tokens != nil { - // Intentionally written like this and not with append(), so this can - // panic if we ever exceed the preallocated slice size, since that means - // we have a nasty bug in handleNextToken() below. - t.tokens[t.tokenCount] = t.line[t.tpos:endTokenPos] - } - t.tokenCount++ - t.tpos = endTokenPos -} - -func (t *tokenizer) handleNextToken() bool { - escaped := false - var c, curQuoteChar byte - curQuotePos := -1 - - lineLen := len(t.line) - for p := t.tpos; p < lineLen; p++ { - c = t.line[p] - switch { - - // If the previous character was a backslash, we ignore the next - // character, unless it was an non-token delimiter (space, tab, etc.) - // outside of a quoted string. - case escaped: - if curQuotePos < 0 && delimiters[c] { - t.countOrSaveToken(p + 1) - return true - } else { - escaped = false - } - - // If we weren't already escaped and we encounter a backslash, toggle - // the escaped flag and ignore the current byte. - case c == '\\': - escaped = true - - // Non-ASCII / UTF8 / invalid character, consider it a part of the - // current token, for lack of a better efficient option... - case c > 127: - // Intentionally blank, continues to the next char - - // If we are currently in a quoted part of the string, the current - // character is also part of the current token. The only special case - // here is if the current character is a matching quote, that means - // we'll no longer be quoted. - case curQuotePos >= 0: - if c == curQuoteChar { // end quote - curQuotePos = -1 - } - - // If we encounter a qoute character and we were not already in a quoted - // part of the line, mark that we are now in a quote from that type. - case c == '"' || c == '\'' || c == '`': - curQuoteChar = c - curQuotePos = p - - // If we encounter a delimiter outside of a quote, count or save the - // token and skip the delimiter. - case delimiters[c]: - t.countOrSaveToken(p + 1) - return true - - // Handle likely JSON object keys that have been serialized without - // spaces. For example, something like this: - // `{"context":{"taskId":1},"message":"starting",...}` - // - // If the line starts or ends with curly braces, we consider it might be - // a JSON log and try to detect the `":` part of the message that isn't - // followed by a delimiter character. If we find that pattern, we - // consider everything up to and including the `:` character as a - // separate token. - // - // Similarly, we try to detect the `,"` pattern and also split a token - // before the comma value. The `p > t.tpos` check is crucial here, - // because it ensures that we're not at the start of a token, i.e. there - // wasn't a delimiter right before the comma. - case t.maybeJSON && p > t.tpos && (c == ':' || c == ',') && p+1 < lineLen: - if c == ':' && t.line[p-1] == '"' && !delimiters[t.line[p+1]] { - t.countOrSaveToken(p + 1) - return true - } - if c == ',' && t.line[p+1] == '"' { - t.countOrSaveToken(p) - return true - } - } - - // By default we do nothing, simply advance one character forward - // because the current character was a part of the current token. - } - - // We have an unterminated single quote at position `curQuotePos`. To handle - // this edge case somewhat gracefully, we can emit everything up to that - // unterminated quote and the quote itself as a single token, and continue - // fairly normally from there. - if curQuotePos > 0 { - t.countOrSaveToken(curQuotePos + 1) - return true - } - - if t.tpos < len(t.line) { - t.countOrSaveToken(len(t.line)) - return true - } - - return false -} - -// This function is called twice! The first time it counts the tokens but -// doesn't save them. Afterwards we allocate the tokens return slice with -// exactly the correct capacity and we call it again, this time to save them. -func (t *tokenizer) process() { - // We want to handle the end of the string as a single token, so we start - // the loop from 1. - for i := 1; i < t.maxTokens; i++ { - if !t.handleNextToken() { - break - } - } - - if t.tpos >= len(t.line) { - return - } - - // We have token count more than or equal to maxTokens, add one last token - // containing placeholderEndOfLine to signal that. - if t.tokens != nil { - t.tokens[t.tokenCount] = placeholderEndOfLine - } - t.tokenCount++ - t.tpos += len(placeholderEndOfLine) -} - -func (t *tokenizer) tokenize() []string { - t.buf = Preprocess(t.rawLine) - - // We use unsafe to convert buf to a string without any new allocations. - // This is safe because t.buf won't be used or referenced anywhere else - // besides here from now on. - t.line = unsafe.String(unsafe.SliceData(t.buf), len(t.buf)) - - if len(t.line) >= 2 && (t.line[0] == '{' || t.line[len(t.line)-1] == '}') { - t.maybeJSON = true - } - - t.process() - - // If we have super long lines (more than twice the size we need to get the - // maxTokens we want), copy just the part we need so the tokens don't hold a - // reference to the original huge []byte slice. - if t.tokenCount == t.maxTokens && t.tpos*2 < len(t.line) { - t.line = string(t.buf[0 : t.tpos+1]) - } - - t.tokens = make([]string, t.tokenCount) // intentionally like this, see comment in countOrSaveToken() - t.tokenCount = 0 - t.tpos = 0 - t.process() - - return t.tokens -} - -func PreprocessAndTokenize(content []byte) []string { - t := tokenizer{rawLine: content, maxTokens: 100} // TODO: parametrize maxTokens - - return t.tokenize() -} diff --git a/pkg/pattern/tokenization/tokenization_benchmark_test.go b/pkg/pattern/tokenization/tokenization_benchmark_test.go deleted file mode 100644 index c614f57576ed9..0000000000000 --- a/pkg/pattern/tokenization/tokenization_benchmark_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package tokenization - -import ( - "fmt" - "testing" -) - -var sampleLogBenchCount = 0 - -func BenchmarkTokenizationTestCases(b *testing.B) { - for i, tc := range tokenizationRealisticTestCases { - line := []byte(tc.line) - b.Run(fmt.Sprintf("test-case-%d", i), func(b *testing.B) { - for i := 0; i < b.N; i++ { - PreprocessAndTokenize(line) - } - }) - } -} - -func BenchmarkTokenizationPlayground(b *testing.B) { - line := []byte(`level=info ts=2023-09-06T00:59:59.982171323Z caller=metrics.go:160 component=frontend org_id=29 traceID=4b93729ff3efabd0 latency=fast query="{stream=\"stdout\",pod=\"loki-canary-nl54q\"} " query_hash=1280418884 query_type=limited range_type=range length=20s start_delta=2h54m30.690801022s end_delta=2h54m10.690801238s step=1s duration=13.926955ms status=200 limit=1000 returned_lines=0 throughput=16MB total_bytes=219kB total_bytes_non_indexed_labels=2.1kB lines_per_second=14935 total_lines=208 post_filter_lines=208 total_entries=41 store_chunks_download_time=1.592805ms queue_time=127µs splits=0 shards=0 chunk_refs_fetch_time=3.599883ms cache_chunk_req=1 cache_chunk_hit=1 cache_chunk_bytes_stored=0 cache_chunk_bytes_fetched=480079 cache_chunk_download_time=1.307396ms cache_index_req=0 cache_index_hit=0 cache_index_download_time=0s cache_stats_results_req=1 cache_stats_results_hit=1 cache_stats_results_download_time=361.913µs cache_result_req=0 cache_result_hit=0 cache_result_download_time=0s token_id=gcom-1234`) - for i := 0; i < b.N; i++ { - PreprocessAndTokenize(line) - } -} diff --git a/pkg/pattern/tokenization/tokenization_test.go b/pkg/pattern/tokenization/tokenization_test.go deleted file mode 100644 index 1461e14d35c77..0000000000000 --- a/pkg/pattern/tokenization/tokenization_test.go +++ /dev/null @@ -1,387 +0,0 @@ -package tokenization - -import ( - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type tokenizationTestCase struct { - line string - expResult []string -} - -var tokenizationCornerTestCases = []tokenizationTestCase{ - { - "", - []string{}, - }, - { - " foo ", - // TOFIX: maybe this is not exactly what we want? should we try to combine empty space into a single token? - []string{" ", "foo ", " "}, - }, - { - "foo bar baz", - []string{"foo ", "bar ", "baz"}, - }, - { - "\nfoo\t bar baz\r\n", - // TOFIX: same as above - should we combine empty space into a single token? - []string{"\n", "foo\t", " ", " ", "bar ", "baz\r", "\n"}, - }, - { - "ends single char C", - []string{"ends ", "single ", "char ", "C"}, - }, - { - "0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Z Y X W V U T S R Q P O N M L K J I H G F E D C B A z y x w v u t s r q p o n m l k j i h g f e d c b a 9 8 7 6 5 4 3 2 1 0", - // The tail end of strings longer than maxTokens is returned as a single token - []string{"<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "<NUM> ", "a ", "b ", "c ", "d ", "e ", "f ", "g ", "h ", "i ", "j ", "k ", "l ", "m ", "n ", "o ", "p ", "q ", "r ", "s ", "t ", "u ", "v ", "w ", "x ", "y ", "z ", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "J ", "K ", "L ", "M ", "N ", "O ", "P ", "Q ", "R ", "S ", "T ", "U ", "V ", "W ", "X ", "Y ", "Z ", "Z ", "Y ", "X ", "W ", "V ", "U ", "T ", "S ", "R ", "Q ", "P ", "O ", "N ", "M ", "L ", "K ", "J ", "I ", "H ", "G ", "F ", "E ", "D ", "C ", "B ", "A ", "z ", "y ", "x ", "w ", "v ", "u ", "t ", "s ", "r ", "q ", "p ", "<...>"}, - }, - { - `a "quoted string"`, - []string{"a ", `"quoted string"`}, - }, - { - `a "quoted string with \" escapes!"`, - []string{"a ", `"quoted string with \" escapes!"`}, - }, - { - `a 'singly quoted string"'`, - []string{"a ", `'singly quoted string"'`}, - }, - { - `a 'singly quoted string" \''`, - []string{"a ", `'singly quoted string" \''`}, - }, - { - `a 'singly quoted string" \\\''`, - []string{"a ", `'singly quoted string" \\\''`}, - }, - { - `a'twisted excappe\\' "with an unterminated quote" 'at_the_end`, - []string{`a'twisted excappe\\' `, `"with an unterminated quote" `, `'`, "at_the_end"}, - }, - { - `a "quoted string 'inception'"!` + "`woot`'much`wow'", - []string{"a ", `"quoted string 'inception'"!` + "`woot`'much`wow'"}, - }, - { - `unterminated"quote`, - []string{`unterminated"`, `quote`}, - }, - { - "`mix`" + ` "and" 'match'`, - []string{"`mix` ", `"and" `, `'match'`}, - }, - { - "`mix`" + ` "and" 'match'`, - []string{"`mix` ", `"and" `, `'match'`}, - }, - { - `{"json":"uninterrupted \"logline\"","foo":"bar"}`, - []string{`{"json":`, `"uninterrupted \"logline\""`, `,"foo":`, `"bar"}`}, - }, - { - `{"weirdo1":`, - []string{`{"weirdo1":`}, - }, - { - // This and the corner case below are not optimal, though they're - // unlikely to be encountered in the real world, so it's hopefully a - // nice tradeoff for the performance of not needing a full JSON parser. - `{"weirdo2":}`, - []string{`{"weirdo2":`, `}`}, - }, - { - `,"weirdo3":}`, - []string{`,"weirdo3":`, `}`}, - }, - { - // We deliberately do treat "escaped" whitespaces outside of quotes as - // delimiters, i.e. whitespaces outside of strings cannot be escaped. - `weird\ escape`, - []string{`weird\ `, `escape`}, - }, - { - "-3.14-foo 0.0.0.0/24-0.0.0.1-255.255.255.255-256.255.255.255 1337-ber 0.12-ber n0tnumb3er 12faux -123.0.1.123 -123 -1231.11 333. 123.456. 123.45-", - []string{"<NUM>-foo ", "<IP>/<NUM>-<IP>-<IP>-<NUM>.<NUM>.<NUM>.<NUM> ", "<NUM>-ber ", "<NUM>-ber ", "n0tnumb3er ", "12faux ", "-<IP> ", "<NUM> ", "<NUM> ", "<NUM>. ", "<NUM>.<NUM>. ", "<NUM>-"}, - }, - { - "2022-12-31 12:12:31 3022-12-31 12:12:31-Jul 1 00:21:28", - []string{"<TIMESTAMP> ", "<NUM>-<NUM>-<NUM> ", "<NUM>:<NUM>:<NUM>-<TIMESTAMP>"}, - }, - { - "2022/12/01 12:12:31 - 2022/13/32 12:12:31", - []string{"<TIMESTAMP> ", "- ", "<NUM>/<NUM>/<NUM> ", "<NUM>:<NUM>:<NUM>"}, - }, - { - "UUIDS: 123e4567-e89b-12d3-a456-426614174000, 550E8400-E29B-41D4-A716-446655440000, -00000000-0000-0000-0000-000000000000, 12345678-dead-beef-1337-000000000000 {c6ad1a63-10b5-460e-ab2c-05c13604539d} ''<A3AE4842-E9AA-4C27-9509-772DB3CC3190>''", - []string{"UUIDS: ", "<UUID>, ", "<UUID>, ", "-<UUID>, ", "<UUID> ", "{<UUID>} ", "''<<UUID>>''"}, - }, - // Mixed case UUID and hex strings are ignored, to limit false positives - { - "Not UUIDS: 123e4567-E89B-12d3-a456-426614174000, 1234567-dead-beef-1337-00000000000a", - []string{"Not ", "UUIDS: ", "123e4567-E89B-12d3-a456-<NUM>, ", "<NUM>-dead-beef-<NUM>-<HEX>"}, - }, - { - "Hexes: 0x0123456789 0xabcdef0123 deadbeef1337-ABCDEF0123456?0123456789ab:FFFFAAAAFFFF Curses: 0x012345678 dEaDbeef1337 abcdefabcde ABCDEFABCDE 0xASDFASDFASDF abcdef0123456NOT", - []string{"Hexes: ", "<HEX> ", "<HEX> ", "<HEX>-<HEX>?<HEX>:<HEX> ", "Curses: ", "0x012345678 ", "dEaDbeef1337 ", "abcdefabcde ", "ABCDEFABCDE ", "0xASDFASDFASDF ", "abcdef0123456NOT"}, - }, - { - "30546354_3313121680 0_123_456_789 foo_123", - []string{"<NUM>_<NUM> ", "<NUM>_<NUM>_<NUM>_<NUM> ", "foo_<NUM>"}, - }, - { - `3.31ms/1h2m|-12h2m6.1s 31m "165m2.1s(6h0m12.05us)" -451325.31µs 6m23μs 123h21m3.4124561s/0s/-0.0123ms`, - []string{"<DURATION>/<DURATION>|<DURATION> ", "<DURATION> ", `"<DURATION>(<DURATION>)" `, "<DURATION> ", "<DURATION> ", "<DURATION>/<DURATION>/<DURATION>"}, - }, - { - // Invalid duration values - "3.31.1ms 3h121m3.4124561s 1h0.12s 100usa 0.12msa", - []string{"<NUM>.<DURATION> ", "3h121m3.<DURATION> ", "1h0.<DURATION> ", "100usa ", "0.12msa"}, - }, - { - // We only consider integers to be valid bytesizes in bytes (0.2B doesn't make sense) - "2Mib 0.12KB-5GB 3.12kb 123Gbps 124mbit:512Tbit 5 B;124.1 KB/3b - 2b or 2 BeNot 13.37 b 3 b", - []string{ - "<BYTESIZE> ", "<BYTESIZE>-<BYTESIZE> ", "<BYTESIZE> ", "<BYTESIZE> ", "<BYTESIZE>:<BYTESIZE> ", - "<BYTESIZE>;<BYTESIZE>/<BYTESIZE> ", "- ", "<BYTESIZE> ", "or ", "<NUM> ", "BeNot ", "<NUM> ", "b ", "<BYTESIZE>"}, - }, - { - `status=123 status_code:500 status 200 status="-1" status_code:"404" httpStatus=200`, - []string{"status=123 ", "status_code:500 ", "status ", "200 ", `status="-1" `, `status_code:"404" `, "httpStatus=200"}, - }, - { - `status_code_foo=123 status_code:500.1 status 2023-09-06T00:59:59.98 status:"404KiB"`, - []string{"status_code_foo=<NUM> ", "status_code:<NUM> ", "status ", "<TIMESTAMP> ", `status:"<BYTESIZE>"`}, - }, -} - -// TODO: add these to the benchmark tests -var tokenizationRealisticTestCases = []tokenizationTestCase{ - // logfmt from loki, metrics.go with a lot of number values of various types - { - `level=info ts=2023-09-06T00:59:59.982171323Z caller=metrics.go:160 component=frontend org_id=29 traceID=4b93729ff3efabd0 latency=fast query="{stream=\"stdout\",pod=\"loki-canary-nl54q\"} " query_hash=1280418884 query_type=limited range_type=range length=20s start_delta=2h54m30.690801022s end_delta=2h54m10.690801238s step=1s duration=13.926955ms status=200 limit=1000 returned_lines=0 throughput=16MB total_bytes=219kB total_bytes_non_indexed_labels=2.1kB lines_per_second=14935 total_lines=208 post_filter_lines=208 total_entries=41 store_chunks_download_time=1.592805ms queue_time=127µs splits=0 shards=0 chunk_refs_fetch_time=3.599883ms cache_chunk_req=1 cache_chunk_hit=1 cache_chunk_bytes_stored=0 cache_chunk_bytes_fetched=480079 cache_chunk_download_time=1.307396ms cache_index_req=0 cache_index_hit=0 cache_index_download_time=0s cache_stats_results_req=1 cache_stats_results_hit=1 cache_stats_results_download_time=361.913µs cache_result_req=0 cache_result_hit=0 cache_result_download_time=0s token_id=gcom-1234`, - - []string{ - "level=info ", "ts=<TIMESTAMP> ", "caller=metrics.go:<NUM> ", "component=frontend ", "org_id=<NUM> ", "traceID=<HEX> ", "latency=fast ", `query="{stream=\"stdout\",pod=\"loki-canary-nl54q\"} " `, "query_hash=<NUM> ", "query_type=limited ", "range_type=range ", "length=<DURATION> ", "start_delta=<DURATION> ", "end_delta=<DURATION> ", "step=<DURATION> ", "duration=<DURATION> ", "status=200 ", "limit=<NUM> ", "returned_lines=<NUM> ", "throughput=<BYTESIZE> ", "total_bytes=<BYTESIZE> ", "total_bytes_non_indexed_labels=<BYTESIZE> ", "lines_per_second=<NUM> ", "total_lines=<NUM> ", "post_filter_lines=<NUM> ", "total_entries=<NUM> ", "store_chunks_download_time=<DURATION> ", "queue_time=<DURATION> ", "splits=<NUM> ", "shards=<NUM> ", "chunk_refs_fetch_time=<DURATION> ", "cache_chunk_req=<NUM> ", "cache_chunk_hit=<NUM> ", "cache_chunk_bytes_stored=<NUM> ", "cache_chunk_bytes_fetched=<NUM> ", "cache_chunk_download_time=<DURATION> ", "cache_index_req=<NUM> ", "cache_index_hit=<NUM> ", "cache_index_download_time=<DURATION> ", "cache_stats_results_req=<NUM> ", "cache_stats_results_hit=<NUM> ", "cache_stats_results_download_time=<DURATION> ", "cache_result_req=<NUM> ", "cache_result_hit=<NUM> ", "cache_result_download_time=<DURATION> ", "token_id=gcom-<NUM>", - }, - }, - // logfmt from loki, with string multi-word messages - { - `level=debug ts=2023-09-06T00:59:59.98214402Z caller=shard_resolver.go:114 bytes=205kB chunks=2 streams=2 entries=200 msg="queried index" type=single matchers="{stream=\"stdout\", pod=\"loki-canary-v75j4\"}" duration=9.498885ms from=2023-09-06T00:48:53.138Z through=2023-09-06T00:49:43.138Z length=50s`, - []string{ - "level=debug ", "ts=<TIMESTAMP> ", "caller=shard_resolver.go:<NUM> ", "bytes=<BYTESIZE> ", "chunks=<NUM> ", "streams=<NUM> ", "entries=<NUM> ", `msg="queried index" `, "type=single ", `matchers="{stream=\"stdout\", pod=\"loki-canary-v75j4\"}" `, "duration=<DURATION> ", "from=<TIMESTAMP> ", "through=<TIMESTAMP> ", "length=<DURATION>", - }, - }, - // tricky loki distributor message: - { - `level=debug ts=2024-07-12T12:25:06.175464934Z caller=push.go:146 org_id=29 traceID=7af4f918eab1c80f msg="push request parsed" path=/loki/api/v1/push contentType=application/x-protobuf contentEncoding= bodySize="8.8 kB" streams=11 entries=43 streamLabelsSize="3.4 kB" entriesSize="19 kB" structuredMetadataSize="71 B" totalSize="22 kB" mostRecentLagMs=167 adaptiveLogsDroppedLines=10 adaptiveLogsDroppedSize=4965 adaptiveLogsMatchedLines=37`, - []string{ - "level=debug ", "ts=<TIMESTAMP> ", "caller=push.go:<NUM> ", "org_id=<NUM> ", "traceID=<HEX> ", `msg="push request parsed" `, "path=/loki/api/v1/push ", "contentType=application/x-protobuf ", "contentEncoding= ", `bodySize="<BYTESIZE>" `, "streams=<NUM> ", "entries=<NUM> ", `streamLabelsSize="<BYTESIZE>" `, `entriesSize="<BYTESIZE>" `, `structuredMetadataSize="<BYTESIZE>" `, `totalSize="<BYTESIZE>" `, "mostRecentLagMs=<NUM> ", "adaptiveLogsDroppedLines=<NUM> ", "adaptiveLogsDroppedSize=<NUM> ", "adaptiveLogsMatchedLines=<NUM>", - }, - }, - // random JSON logs - { - `{"timestamp": "2022-12-23T12:34:56Z", "level": "debug", "message": "Server starting", "server_id": "abcdefghij", "start_time": "2022-12-23T12:30:00Z"}`, - []string{`{"timestamp": `, `"<TIMESTAMP>", `, `"level": `, `"debug", `, `"message": `, `"Server starting", `, `"server_id": `, `"abcdefghij", `, `"start_time": `, `"<TIMESTAMP>"}`}, - }, - { - // JSON logs without spaces between elements, like how JavaScript's JSON.Stringify() produces: - `{"context":{"taskId":1},"message":"starting task ID 1","sequence":0,"time":1506776210000,"version":"1.0.0"}`, - []string{`{"context":`, `{"taskId":`, `<NUM>}`, `,"message":`, `"starting task ID <NUM>"`, `,"sequence":`, `<NUM>`, `,"time":`, `<NUM>`, `,"version":`, `"<NUM>.<NUM>.<NUM>"}`}, - }, - // Android logs from https://github.com/logpai/logparser/blob/main/data/loghub_2k/Android/Android_2k.log - { - // This test case has an unterminated double quote - // - // TOFIX: - // - timestamp is not correctly detected - // - empty "" token? - `03-17 16:13:40.345 1702 14638 D PowerManagerService: release:lock=166121161, flg=0x0, tag="RILJ_ACK_WL", name=com.android.phone", ws=null, uid=1001, pid=2626`, - []string{"<NUM>-<NUM> ", "<NUM>:<NUM>:<NUM> ", " ", "<NUM> ", "<NUM> ", "D ", "PowerManagerService: ", "release:lock=<NUM>, ", "flg=0x0, ", `tag="RILJ_ACK_WL", `, `name=com.android.phone"`, ", ", "ws=null, ", "uid=<NUM>, ", "pid=<NUM>"}, - }, - { - // TOFIX: - // - timestamp is not correctly detected - // - empty "" tokens - `03-17 16:13:47.518 1702 8671 D ActivityManager: Skipping, withExcluded: false, tr.intent:Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Tencent/QQfile_recv/b.apk typ=application/vnd.android.package-archive flg=0x10800000 cmp=com.android.packageinstaller/.PackageInstallerActivity (has extras) }`, - []string{ - "<NUM>-<NUM> ", "<NUM>:<NUM>:<NUM> ", " ", "<NUM> ", " ", "<NUM> ", "D ", "ActivityManager: ", "Skipping, ", "withExcluded: ", "false, ", "tr.intent:Intent ", "{ ", "act=android.intent.action.VIEW ", "dat=file:///storage/emulated/<NUM>/Tencent/QQfile_recv/b.apk ", "typ=application/vnd.android.package-archive ", "flg=0x10800000 ", "cmp=com.android.packageinstaller/.PackageInstallerActivity ", "(has ", "extras) ", "}", - }, - }, - // Apache logs from https://github.com/logpai/logparser/blob/main/data/loghub_2k/Apache/Apache_2k.log - { - `[Mon Dec 05 13:16:27 2005] [notice] jk2_init() Found child 5877 in scoreboard slot 9`, - []string{"[<TIMESTAMP>] ", "[notice] ", "jk2_init() ", "Found ", "child ", "<NUM> ", "in ", "scoreboard ", "slot ", "<NUM>"}, - }, - { - `[Mon Dec 05 19:14:11 2005] [notice] workerEnv.init() ok /etc/httpd/conf/workers2.properties`, - []string{"[<TIMESTAMP>] ", "[notice] ", "workerEnv.init() ", "ok ", "/etc/httpd/conf/workers2.properties"}, - }, - // nginx logs by running `docker run -p 80:80 -v $(pwd):/usr/share/nginx/html nginx` locally - { - `2024/03/27 14:31:42 [error] 29#29: *1 directory index of "/usr/share/nginx/html/" is forbidden, client: 172.17.0.1, server: localhost, request: "GET / HTTP/1.1", host: "127.0.0.1"`, - []string{"<TIMESTAMP> ", "[error] ", "<NUM>#<NUM>: ", "*<NUM> ", "directory ", "index ", "of ", "\"/usr/share/nginx/html/\" ", "is ", "forbidden, ", "client: ", "<IP>, ", "server: ", "localhost, ", "request: ", `"GET / HTTP/<NUM>", `, "host: ", "\"<IP>\""}, - }, - { - // TOFIX: - // - probably not all numbers should be replaced with <NUM>, e.g. for "*1", "(2:", "HTTP/1.1" it's definitely a worse UX - `2024/03/27 14:34:37 [error] 29#29: *1 open() "/usr/share/nginx/html/test url with spaces" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /test%20url%20with%20spaces HTTP/1.1", host: "127.0.0.1" - 172.17.0.1 - - [31/Mar/2024:14:34:37 +0000] "GET /test%20url%20with%20spaces HTTP/1.1" 404 153 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:123.0) Gecko/20100101 Firefox/123.0" "-"`, - []string{"<TIMESTAMP> ", "[error] ", "<NUM>#<NUM>: ", "*<NUM> ", "open() ", `"/usr/share/nginx/html/test url with spaces" `, "failed ", "(<NUM>: ", "No ", "such ", "file ", "or ", "directory), ", "client: ", "<IP>, ", "server: ", "localhost, ", "request: ", `"GET /test%20url%20with%20spaces HTTP/<NUM>", `, "host: ", "\"<IP>\"\n", "\t", "\t", "<IP> ", "- ", "- ", "[<TIMESTAMP>] ", `"GET /test%20url%20with%20spaces HTTP/<NUM>" `, "<NUM> ", "<NUM> ", "\"-\" ", `"Mozilla/<NUM> (X11; Linux x86_<NUM>; rv:<NUM>) Gecko/<NUM> Firefox/<NUM>" `, `"-"`}, - }, - // Linux systemd (journalctl) logs - { - `Mar 27 11:52:21 hostname systemd-networkd[2043]: enp6s0: LLDP Rx: Invoking callback for 'refreshed' event.`, - []string{"<TIMESTAMP> ", "hostname ", "systemd-networkd[<NUM>]: ", "enp6s0: ", "LLDP ", "Rx: ", "Invoking ", "callback ", "for ", "'refreshed' ", "event."}, - }, - { - `Feb 29 23:00:14 nixos dbus-daemon[11432]: [system] Activating via systemd: service name='org.opensuse.Snapper' unit='snapperd.service' requested by ':1.324' (uid=0 pid=22089 comm="/nix/store/7rgimysvkczzyiaq4fkfymyjad4vbd9c-snappe" label="kernel")`, - []string{"<TIMESTAMP> ", "nixos ", "dbus-daemon[<NUM>]: ", "[system] ", "Activating ", "via ", "systemd: ", "service ", "name='org.opensuse.Snapper' ", "unit='snapperd.service' ", "requested ", "by ", "':<NUM>' ", "(uid=<NUM> ", "pid=<NUM> ", "comm=\"/nix/store/7rgimysvkczzyiaq4fkfymyjad4vbd9c-snappe\" ", "label=\"kernel\")"}, - }, - // Random slack logs: - { - `Apr-10 23:43:46.807 [API-Q] (T02S4RCS0) c37dfd20-1712781826.804 conversations.suggestions is ACTIVE`, - []string{"<TIMESTAMP> ", "[API-Q] ", "(T02S4RCS0) ", "c37dfd20-<NUM> ", "conversations.suggestions ", "is ", "ACTIVE"}, - }, - { - `Apr-11 00:01:57.743 [DEVICE-PERMISSIONS-MA] Permissions saved to local storage: {"permissions":{"microphone":"granted","camera":"prompt","screen":"prompt"},"timestamp":1712782917742}`, - []string{"<TIMESTAMP> ", "[DEVICE-PERMISSIONS-MA] ", "Permissions ", "saved ", "to ", "local ", "storage: ", `{"permissions":`, `{"microphone":`, `"granted"`, `,"camera":`, `"prompt"`, `,"screen":`, `"prompt"}`, `,"timestamp":`, `<NUM>}`}, - }, - // Another weird log from loki: - { - `ts=2023-09-06T00:59:59.900879737Z caller=spanlogger.go:86 user=29 level=debug msg="querying ingester" params="selector={stream=\"stdout\", pod=\"loki-canary-t98wq\"}, direction=BACKWARD, start=2023-09-05 23:20:28.030285153 +0000 UTC, end=2023-09-05 23:20:48.030285153 +0000 UTC, limit=1000, shards="`, - []string{"ts=<TIMESTAMP> ", "caller=spanlogger.go:<NUM> ", "user=<NUM> ", "level=debug ", `msg="querying ingester" `, `params="selector={stream=\"stdout\", pod=\"loki-canary-t98wq\"}, direction=BACKWARD, start=<TIMESTAMP>, end=<TIMESTAMP>, limit=<NUM>, shards="`}, - }, - // {``, []string{}}, -} - -func getTimestampTests(t *testing.T) []tokenizationTestCase { - timeStamps := []string{ - "2023-01-03T15:04:05.999999999Z", - "2024-02-29T11:12:03.33+02:00", - "2022-03-02T23:59:59Z", - "2024-04-01T01:33:59+03:00", - "2021-05-07T00:00:00-04:30", - "1999-06-12T13:37:31.123+03:00", - "2005-07-17T12:00:00Z", - "1988-08-03T00:00:00Z", - "2020-09-30T00:00:59.9999+03:00", - "2034-10-31T12:34:56.7890+11:23", - "2034-11-01T01:23:45.67890Z", - "2025-12-31T01:23:45.67890Z", - } - - timestampConst := string(placeholderTimestamp) - layouts := []struct { - layout string - expResult []string - }{ - // TOFIX: all of the commented out lines. - - //{time.Layout, []string{timestampConst}}, - {time.ANSIC, []string{timestampConst}}, - {time.UnixDate, []string{timestampConst}}, - {"Mon _2 Jan 15:04:05 MST 2006", []string{timestampConst}}, // linux `date` - {time.RubyDate, []string{timestampConst}}, - {time.RFC822, []string{timestampConst}}, - {time.RFC822Z, []string{timestampConst}}, - {time.RFC850, []string{timestampConst}}, - {time.RFC1123, []string{timestampConst}}, - {time.RFC1123Z, []string{timestampConst}}, - {time.RFC3339, []string{timestampConst}}, - {time.RFC3339Nano, []string{timestampConst}}, - //{time.Stamp, []string{timestampConst}}, - //{time.StampMilli, []string{timestampConst}}, - //{time.StampMicro, []string{timestampConst}}, - //{time.StampNano, []string{timestampConst}}, - {time.DateTime, []string{timestampConst}}, - - // TOFIX: maybe consider these timestamps? - {time.DateOnly, []string{"<NUM>-<NUM>-<NUM>"}}, - {time.TimeOnly, []string{"<NUM>:<NUM>:<NUM>"}}, - } - - result := make([]tokenizationTestCase, 0, len(timeStamps)*len(layouts)) - for _, tss := range timeStamps { - ts, err := time.Parse(time.RFC3339Nano, tss) - require.NoError(t, err) - for _, layout := range layouts { - result = append(result, tokenizationTestCase{ - line: ts.Format(layout.layout), - expResult: layout.expResult, - }) - } - } - return result -} - -type tokenizationTestCasePack struct { - name string - cases []tokenizationTestCase -} - -func TestTokenization(t *testing.T) { - packs := []tokenizationTestCasePack{ - {"cornerTestCases", tokenizationCornerTestCases}, - {"timestamps", getTimestampTests(t)}, - {"realisticTestCases", tokenizationRealisticTestCases}, - } - - for i, pack := range packs { - pack := pack - t.Run(fmt.Sprintf("test-pack-%d-%s", i, pack.name), func(t *testing.T) { - for j, tc := range pack.cases { - tc := tc - t.Run(fmt.Sprintf("case-%d", j), func(t *testing.T) { - result := PreprocessAndTokenize([]byte(tc.line)) - assert.Equal( - t, tc.expResult, result, - fmt.Sprintf("Log line: %q\nActual result slice: %#v", tc.line, result), - ) - }) - } - }) - } -} - -func TestTokenizationMemcpy(t *testing.T) { - buf := make([]byte, 0, 1000) - for i := 0; i < 300; i++ { - buf = append(buf, 'a', ' ') - } - tokenizer := tokenizer{rawLine: buf, maxTokens: 10} - tokenizer.tokenize() - require.Less(t, len(tokenizer.line), 100) -} - -// Useful for running single test cases in isolation -func TestTokenizationPlayground(t *testing.T) { - tc := tokenizationTestCase{ - "foo 121113.21231 bar 123.0.1.123 -123 -1231.11", - []string{"foo ", "<NUM> ", "bar ", "<IP> ", "<NUM> ", "<NUM>"}, - } - result := PreprocessAndTokenize([]byte(tc.line)) - assert.Equal( - t, tc.expResult, result, - fmt.Sprintf("Log line: %q\nActual result slice: %#v", tc.line, result), - ) -} - -func TestReplacementPlayground(t *testing.T) { - line := "Jul 1 00:21:28" - exp := "<TIMESTAMP>" - r := replacer{source: []byte(line)} - r.replaceWithPlaceholders() - - assert.Equal( - t, exp, string(r.dest), - fmt.Sprintf("Log line: %q", line), - ) -}
chore
remove unused pattern tokenization form Loki (#13783)
e4d82ed29359f3d68a450e70aac25a18aa5d03d1
2024-04-04 17:39:04
Periklis Tsirakidis
chore(operator): Update Loki operand to v2.9.6 (#12370)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index b836901242286..a6f7cae8bab2d 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [12370](https://github.com/grafana/loki/pull/12370) **periklis**: Update Loki operand to v2.9.6 - [12333](https://github.com/grafana/loki/pull/12333) **periklis**: Bump max OpenShift version to next release ## 0.6.0 (2024-03-19) diff --git a/operator/bundle/community-openshift/manifests/loki-operator.clusterserviceversion.yaml b/operator/bundle/community-openshift/manifests/loki-operator.clusterserviceversion.yaml index 0fe4276c4b726..36639683bc0d3 100644 --- a/operator/bundle/community-openshift/manifests/loki-operator.clusterserviceversion.yaml +++ b/operator/bundle/community-openshift/manifests/loki-operator.clusterserviceversion.yaml @@ -150,7 +150,7 @@ metadata: categories: OpenShift Optional, Logging & Tracing certified: "false" containerImage: docker.io/grafana/loki-operator:0.6.0 - createdAt: "2024-03-19T14:29:49Z" + createdAt: "2024-03-27T08:04:23Z" description: The Community Loki Operator provides Kubernetes native deployment and management of Loki and related logging components. features.operators.openshift.io/disconnected: "true" @@ -1714,7 +1714,7 @@ spec: - /manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.9.4 + value: docker.io/grafana/loki:2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA @@ -1838,7 +1838,7 @@ spec: provider: name: Grafana Loki SIG Operator relatedImages: - - image: docker.io/grafana/loki:2.9.4 + - image: docker.io/grafana/loki:2.9.6 name: loki - image: quay.io/observatorium/api:latest name: gateway diff --git a/operator/bundle/community/manifests/loki-operator.clusterserviceversion.yaml b/operator/bundle/community/manifests/loki-operator.clusterserviceversion.yaml index 5179090de0365..0e73ba8ac3953 100644 --- a/operator/bundle/community/manifests/loki-operator.clusterserviceversion.yaml +++ b/operator/bundle/community/manifests/loki-operator.clusterserviceversion.yaml @@ -150,7 +150,7 @@ metadata: categories: OpenShift Optional, Logging & Tracing certified: "false" containerImage: docker.io/grafana/loki-operator:0.6.0 - createdAt: "2024-03-19T14:29:48Z" + createdAt: "2024-03-27T08:04:21Z" description: The Community Loki Operator provides Kubernetes native deployment and management of Loki and related logging components. operators.operatorframework.io/builder: operator-sdk-unknown @@ -1694,7 +1694,7 @@ spec: - /manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.9.4 + value: docker.io/grafana/loki:2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA @@ -1806,7 +1806,7 @@ spec: provider: name: Grafana Loki SIG Operator relatedImages: - - image: docker.io/grafana/loki:2.9.4 + - image: docker.io/grafana/loki:2.9.6 name: loki - image: quay.io/observatorium/api:latest name: gateway diff --git a/operator/bundle/openshift/manifests/loki-operator.clusterserviceversion.yaml b/operator/bundle/openshift/manifests/loki-operator.clusterserviceversion.yaml index f492a055d8fbd..280feb0604633 100644 --- a/operator/bundle/openshift/manifests/loki-operator.clusterserviceversion.yaml +++ b/operator/bundle/openshift/manifests/loki-operator.clusterserviceversion.yaml @@ -150,7 +150,7 @@ metadata: categories: OpenShift Optional, Logging & Tracing certified: "false" containerImage: quay.io/openshift-logging/loki-operator:0.1.0 - createdAt: "2024-03-19T14:29:51Z" + createdAt: "2024-03-27T08:04:24Z" description: | The Loki Operator for OCP provides a means for configuring and managing a Loki stack for cluster logging. ## Prerequisites and Requirements @@ -1699,7 +1699,7 @@ spec: - /manager env: - name: RELATED_IMAGE_LOKI - value: quay.io/openshift-logging/loki:v2.9.4 + value: quay.io/openshift-logging/loki:v2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA @@ -1823,7 +1823,7 @@ spec: provider: name: Red Hat relatedImages: - - image: quay.io/openshift-logging/loki:v2.9.4 + - image: quay.io/openshift-logging/loki:v2.9.6 name: loki - image: quay.io/observatorium/api:latest name: gateway diff --git a/operator/config/overlays/community-openshift/manager_related_image_patch.yaml b/operator/config/overlays/community-openshift/manager_related_image_patch.yaml index 0b11adb57bbeb..68084a4404901 100644 --- a/operator/config/overlays/community-openshift/manager_related_image_patch.yaml +++ b/operator/config/overlays/community-openshift/manager_related_image_patch.yaml @@ -9,7 +9,7 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.9.4 + value: docker.io/grafana/loki:2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA diff --git a/operator/config/overlays/community/manager_related_image_patch.yaml b/operator/config/overlays/community/manager_related_image_patch.yaml index 0b11adb57bbeb..68084a4404901 100644 --- a/operator/config/overlays/community/manager_related_image_patch.yaml +++ b/operator/config/overlays/community/manager_related_image_patch.yaml @@ -9,7 +9,7 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.9.4 + value: docker.io/grafana/loki:2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA diff --git a/operator/config/overlays/development/manager_related_image_patch.yaml b/operator/config/overlays/development/manager_related_image_patch.yaml index a9c7cf22f1d1e..65b258b1c41cc 100644 --- a/operator/config/overlays/development/manager_related_image_patch.yaml +++ b/operator/config/overlays/development/manager_related_image_patch.yaml @@ -9,6 +9,6 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: docker.io/grafana/loki:2.9.4 + value: docker.io/grafana/loki:2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest diff --git a/operator/config/overlays/openshift/manager_related_image_patch.yaml b/operator/config/overlays/openshift/manager_related_image_patch.yaml index 28c00163194a7..7b10a721a0b8b 100644 --- a/operator/config/overlays/openshift/manager_related_image_patch.yaml +++ b/operator/config/overlays/openshift/manager_related_image_patch.yaml @@ -9,7 +9,7 @@ spec: - name: manager env: - name: RELATED_IMAGE_LOKI - value: quay.io/openshift-logging/loki:v2.9.4 + value: quay.io/openshift-logging/loki:v2.9.6 - name: RELATED_IMAGE_GATEWAY value: quay.io/observatorium/api:latest - name: RELATED_IMAGE_OPA diff --git a/operator/docs/operator/compatibility.md b/operator/docs/operator/compatibility.md index 2fc1e79662d1c..30f86e0c272e6 100644 --- a/operator/docs/operator/compatibility.md +++ b/operator/docs/operator/compatibility.md @@ -38,3 +38,4 @@ The versions of Loki compatible to be run with the Loki Operator are: * v2.9.2 * v2.9.3 * v2.9.4 +* v2.9.6 diff --git a/operator/hack/addons_dev.yaml b/operator/hack/addons_dev.yaml index f2538cd9f5af1..9021682211a89 100644 --- a/operator/hack/addons_dev.yaml +++ b/operator/hack/addons_dev.yaml @@ -29,7 +29,7 @@ spec: spec: containers: - name: logcli - image: docker.io/grafana/logcli:2.9.4-amd64 + image: docker.io/grafana/logcli:2.9.6-amd64 imagePullPolicy: IfNotPresent command: - /bin/sh @@ -73,7 +73,7 @@ spec: spec: containers: - name: promtail - image: docker.io/grafana/promtail:2.9.4 + image: docker.io/grafana/promtail:2.9.6 args: - -config.file=/etc/promtail/promtail.yaml - -log.level=info diff --git a/operator/hack/addons_ocp.yaml b/operator/hack/addons_ocp.yaml index 5a09cbc0e6aa4..47faa521b5fe6 100644 --- a/operator/hack/addons_ocp.yaml +++ b/operator/hack/addons_ocp.yaml @@ -29,7 +29,7 @@ spec: spec: containers: - name: logcli - image: docker.io/grafana/logcli:2.9.4-amd64 + image: docker.io/grafana/logcli:2.9.6-amd64 imagePullPolicy: IfNotPresent command: - /bin/sh @@ -70,7 +70,7 @@ spec: spec: containers: - name: promtail - image: docker.io/grafana/promtail:2.9.4 + image: docker.io/grafana/promtail:2.9.6 args: - -config.file=/etc/promtail/promtail.yaml - -log.level=info diff --git a/operator/internal/manifests/var.go b/operator/internal/manifests/var.go index c81636fe5a553..bfdef5d0db592 100644 --- a/operator/internal/manifests/var.go +++ b/operator/internal/manifests/var.go @@ -59,7 +59,7 @@ const ( EnvRelatedImageGateway = "RELATED_IMAGE_GATEWAY" // DefaultContainerImage declares the default fallback for loki image. - DefaultContainerImage = "docker.io/grafana/loki:2.9.4" + DefaultContainerImage = "docker.io/grafana/loki:2.9.6" // DefaultLokiStackGatewayImage declares the default image for lokiStack-gateway. DefaultLokiStackGatewayImage = "quay.io/observatorium/api:latest"
chore
Update Loki operand to v2.9.6 (#12370)
5da5dc0b290b08f30ae9564f99f3791a7b69bf77
2025-02-13 23:35:17
renovate[bot]
chore(deps): update docker.io/grafana/loki docker tag to v3.4.1 (main) (#16238)
false
diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 19e0fcf7dddcb..167911d6bbc02 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -6149,7 +6149,7 @@ null <td>string</td> <td>Overrides the image tag whose default is the chart's appVersion</td> <td><pre lang="json"> -"3.4.0" +"3.4.1" </pre> </td> </tr> diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index 395f6325489da..d80cf1830b1bf 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -14,6 +14,7 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) - [FEATURE] Added support for globals: `extraArgs`, `extraEnv`, `extraEnvFrom`, `extraVolumes`, `extraVolumeMounts` ([#16062](https://github.com/grafana/loki/pull/16062)) relates to ([#12652](https://github.com/grafana/loki/pull/12652)) +- [CHANGE] Changed version of Grafana Loki to 3.4.1 ## 6.26.0 diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index 90cf0a7522e66..a0385fb7903e7 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -75,7 +75,7 @@ loki: # -- Docker image repository repository: grafana/loki # -- Overrides the image tag whose default is the chart's appVersion - tag: 3.4.0 + tag: 3.4.1 # -- Overrides the image tag with an image digest digest: null # -- Docker image pull policy
chore
update docker.io/grafana/loki docker tag to v3.4.1 (main) (#16238)
2477f70431179e55f7c39fffbf75dc403e91a67f
2019-10-08 19:16:14
Marco Pracucci
docs: clarified the relation between retention period and table period (#1129)
false
diff --git a/docs/configuration/README.md b/docs/configuration/README.md index 55988200e7cad..3e8f5aed5d4f4 100644 --- a/docs/configuration/README.md +++ b/docs/configuration/README.md @@ -745,7 +745,8 @@ and how to provision tables when DynamoDB is used as the backing store. [retention_deletes_enabled: <boolean> | default = false] # How far back tables will be kept before they are deleted. 0s disables -# deletion. +# deletion. The retention period must be a multiple of the index / chunks +# table "period" (see period_config). [retention_period: <duration> | default = 0s] # Period with which the table manager will poll for tables. diff --git a/docs/operations/storage/retention.md b/docs/operations/storage/retention.md index afcf2e08c0cce..9c0c3c19954a0 100644 --- a/docs/operations/storage/retention.md +++ b/docs/operations/storage/retention.md @@ -10,8 +10,10 @@ Alternatively, the `table-manager.retention-period` and provided retention period needs to be a duration represented as a string that can be parsed using Go's [time.Duration](https://golang.org/pkg/time/#ParseDuration). -> **WARNING**: The retention period should be at least twice the [duration of -the periodic table config](https://github.com/grafana/loki/blob/347a3e18f4976d799d51a26cee229efbc27ef6c9/production/helm/loki/values.yaml#L53), which currently defaults to 7 days. +> **WARNING**: The retention period must be a multiple of the index and chunks table +`period`, configured in the [`period_config`](../../configuration/README.md#period_config) +block. See the [Table Manager](./table-manager.md#retention) documentation for +more information. When using S3 or GCS, the bucket storing the chunks needs to have the expiry policy set correctly. For more details check
docs
clarified the relation between retention period and table period (#1129)
67de0334e970b86f81618139b62479fbf7fc8a44
2022-10-21 22:38:27
Dylan Guedes
docs: Add max_streams to Promtail configuration doc (#7489)
false
diff --git a/docs/sources/clients/promtail/configuration.md b/docs/sources/clients/promtail/configuration.md index b3d3aefb58e9f..83cefe1eb3879 100644 --- a/docs/sources/clients/promtail/configuration.md +++ b/docs/sources/clients/promtail/configuration.md @@ -1918,6 +1918,12 @@ The optional `limits_config` block configures global limits for this instance of # log lines, rather than sending them to Loki. When false, exceeding the rate limit # causes this instance of Promtail to temporarily hold off on sending the log lines and retry later. [readline_rate_drop: <bool> | default = true] + +# Limits the max number of active streams. +# Limiting the number of streams is useful as a mechanism to limit memory usage by Promtail, which helps +# to avoid OOM scenarios. +# 0 means it is disabled. +[max_streams: <int> | default = 0] ``` ## target_config
docs
Add max_streams to Promtail configuration doc (#7489)
be0388443f9d65a6fe4219f200261feac09fe227
2024-04-16 00:26:17
Dylan Guedes
docs: helm: Update monolithic guide. (#12591)
false
diff --git a/docs/sources/setup/install/helm/install-monolithic/_index.md b/docs/sources/setup/install/helm/install-monolithic/_index.md index e85d6a52159b5..fcd9e66716256 100644 --- a/docs/sources/setup/install/helm/install-monolithic/_index.md +++ b/docs/sources/setup/install/helm/install-monolithic/_index.md @@ -12,7 +12,7 @@ weight: 100 This Helm Chart installation runs the Grafana Loki *single binary* within a Kubernetes cluster. -If you set the `singleBinary.replicas` value to 1, this chart configures Loki to run the `all` target in a [monolithic mode]({{< relref "../../../../get-started/deployment-modes#monolithic-mode" >}}), designed to work with a filesystem storage. It will also configure meta-monitoring of metrics and logs. +If you set the `singleBinary.replicas` value to 1 and set the deployment mode to `SingleBinary`, this chart configures Loki to run the `all` target in a [monolithic mode](https://grafana.com/docs/loki/<LOKI_VERSION>/get-started/deployment-modes/#monolithic-mode), designed to work with a filesystem storage. It will also configure meta-monitoring of metrics and logs. If you set the `singleBinary.replicas` value to 2 or more, this chart configures Loki to run a *single binary* in a replicated, highly available mode. When running replicas of a single binary, you must configure object storage. **Before you begin: Software Requirements** @@ -39,13 +39,29 @@ If you set the `singleBinary.replicas` value to 2 or more, this chart configures - If running a single replica of Loki, configure the `filesystem` storage: ```yaml + mode: SingleBinary loki: commonConfig: replication_factor: 1 storage: type: 'filesystem' + schemaConfig: + configs: + - from: 2024-01-01 + store: tsdb + index: + prefix: loki_index_ + period: 24h + object_store: filesystem # we're storing on filesystem so there's no real persistence here. + schema: v13 singleBinary: replicas: 1 + read: + replicas: 0 + backend: + replicas: 0 + write: + replicas: 0 ``` - If running Loki with a replication factor greater than 1, set the desired number replicas and provide object storage credentials: @@ -54,6 +70,15 @@ If you set the `singleBinary.replicas` value to 2 or more, this chart configures loki: commonConfig: replication_factor: 3 + schemaConfig: + configs: + - from: 2024-01-01 + store: tsdb + index: + prefix: loki_index_ + period: 24h + object_store: filesystem + schema: v13 storage: bucketNames: chunks: loki-chunks
docs
helm: Update monolithic guide. (#12591)
8f1d12f656924eaf9bd887037c006728b22375cf
2024-07-11 21:13:52
George Robinson
feat: Use WAL Manager (#13491)
false
diff --git a/pkg/ingester-rf1/flush.go b/pkg/ingester-rf1/flush.go index 37b24f6f1abff..eda141afd7621 100644 --- a/pkg/ingester-rf1/flush.go +++ b/pkg/ingester-rf1/flush.go @@ -4,15 +4,16 @@ import ( "crypto/rand" "fmt" "net/http" + "strconv" "time" + "github.com/dustin/go-humanize" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/grafana/dskit/backoff" "github.com/grafana/dskit/ring" "github.com/grafana/dskit/runutil" "github.com/oklog/ulid" - "github.com/prometheus/common/model" "golang.org/x/net/context" "github.com/grafana/loki/v3/pkg/storage/wal" @@ -77,18 +78,16 @@ func (i *Ingester) FlushHandler(w http.ResponseWriter, _ *http.Request) { } type flushOp struct { - from model.Time - userID string - fp model.Fingerprint - immediate bool + it *wal.PendingItem + num int64 } func (o *flushOp) Key() string { - return fmt.Sprintf("%s-%s-%v", o.userID, o.fp, o.immediate) + return strconv.Itoa(int(o.num)) } func (o *flushOp) Priority() int64 { - return -int64(o.from) + return -o.num } func (i *Ingester) flushLoop(j int) { @@ -103,29 +102,35 @@ func (i *Ingester) flushLoop(j int) { if o == nil { return } - op := o.(*flushCtx) + op := o.(*flushOp) + + start := time.Now() + + // We'll use this to log the size of the segment that was flushed. + n := humanize.Bytes(uint64(op.it.Writer.InputSize())) err := i.flushOp(l, op) + d := time.Since(start) if err != nil { - level.Error(l).Log("msg", "failed to flush", "err", err) - // Immediately re-queue another attempt at flushing this segment. - // TODO: Add some backoff or something? - i.flushQueues[j].Enqueue(op) + level.Error(l).Log("msg", "failed to flush", "size", n, "duration", d, "err", err) } else { - // Close the channel and trigger all waiting listeners to return - // TODO: Figure out how to return an error if we want to? - close(op.flushDone) + level.Debug(l).Log("msg", "flushed", "size", n, "duration", d) + } + + op.it.Result.SetDone(err) + if err = i.wal.Put(op.it); err != nil { + level.Error(l).Log("msg", "failed to put back in WAL Manager", "err", err) } } } -func (i *Ingester) flushOp(l log.Logger, flushCtx *flushCtx) error { +func (i *Ingester) flushOp(l log.Logger, op *flushOp) error { ctx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() b := backoff.New(ctx, i.cfg.FlushOpBackoff) for b.Ongoing() { - err := i.flushSegment(ctx, flushCtx.segmentWriter) + err := i.flushSegment(ctx, op.it.Writer) if err == nil { break } diff --git a/pkg/ingester-rf1/ingester.go b/pkg/ingester-rf1/ingester.go index d87159952e04b..8d1b63f74e89f 100644 --- a/pkg/ingester-rf1/ingester.go +++ b/pkg/ingester-rf1/ingester.go @@ -174,22 +174,6 @@ type Interface interface { PrepareShutdown(w http.ResponseWriter, r *http.Request) } -type flushCtx struct { - lock *sync.RWMutex - flushDone chan struct{} - newCtxAvailable chan struct{} - segmentWriter *wal.SegmentWriter - creationTime time.Time -} - -func (o *flushCtx) Key() string { - return fmt.Sprintf("%d", o.creationTime.UnixNano()) -} - -func (o *flushCtx) Priority() int64 { - return -o.creationTime.UnixNano() -} - // Ingester builds chunks for incoming log streams. type Ingester struct { services.Service @@ -217,10 +201,11 @@ type Ingester struct { // One queue per flush thread. Fingerprint is used to // pick a queue. + numOps int64 flushQueues []*util.PriorityQueue flushQueuesDone sync.WaitGroup - flushCtx *flushCtx + wal *wal.Manager limiter *Limiter @@ -268,7 +253,11 @@ func New(cfg Config, clientConfig client.Config, targetSizeStats.Set(int64(cfg.TargetChunkSize)) metrics := newIngesterMetrics(registerer, metricsNamespace) - segmentWriter, err := wal.NewWalSegmentWriter() + walManager, err := wal.NewManager(wal.Config{ + MaxAge: wal.DefaultMaxAge, + MaxSegments: wal.DefaultMaxSegments, + MaxSegmentSize: wal.DefaultMaxSegmentSize, + }) if err != nil { return nil, err } @@ -291,12 +280,7 @@ func New(cfg Config, clientConfig client.Config, writeLogManager: writefailures.NewManager(logger, registerer, writeFailuresCfg, configs, "ingester_rf1"), customStreamsTracker: customStreamsTracker, readRing: readRing, - flushCtx: &flushCtx{ - lock: &sync.RWMutex{}, - flushDone: make(chan struct{}), - newCtxAvailable: make(chan struct{}), - segmentWriter: segmentWriter, - }, + wal: walManager, } // TODO: change flush on shutdown @@ -477,7 +461,6 @@ func (i *Ingester) running(ctx context.Context) error { func (i *Ingester) stopping(_ error) error { i.stopIncomingRequests() var errs util.MultiError - // errs.Add(i.wal.Stop()) //if i.flushOnShutdownSwitch.Get() { // i.lifecycler.SetFlushOnShutdown(true) @@ -567,30 +550,18 @@ func (i *Ingester) loop() { } func (i *Ingester) doFlushTick() { - i.flushCtx.lock.Lock() - - // i.logger.Log("msg", "starting periodic flush") - // Stop new chunks being written while we swap destinations - we'll never unlock as this flushctx can no longer be used. - currentFlushCtx := i.flushCtx - - // APIs become unblocked after resetting flushCtx - segmentWriter, err := wal.NewWalSegmentWriter() - if err != nil { - // TODO: handle this properly - panic(err) - } - i.flushCtx = &flushCtx{ - lock: &sync.RWMutex{}, - flushDone: make(chan struct{}), - newCtxAvailable: make(chan struct{}), - segmentWriter: segmentWriter, - } - close(currentFlushCtx.newCtxAvailable) // Broadcast to all waiters that they can now fetch a new flushCtx. Small chance of a race but if they re-fetch the old one, they'll just check again immediately. - // Flush the finished context in the background & then notify watching API requests - // TODO: use multiple flush queues if required - // Don't write empty segments if there is nothing to write. - if currentFlushCtx.segmentWriter.InputSize() > 0 { - i.flushQueues[0].Enqueue(currentFlushCtx) + for { + // Keep adding ops to the queue until there are no more. + it, _ := i.wal.NextPending() + if it == nil { + break + } + i.numOps++ + flushQueueIndex := i.numOps % int64(i.cfg.ConcurrentFlushes) + i.flushQueues[flushQueueIndex].Enqueue(&flushOp{ + num: i.numOps, + it: it, + }) } } @@ -796,27 +767,11 @@ func (i *Ingester) Push(ctx context.Context, req *logproto.PushRequest) (*logpro return &logproto.PushResponse{}, err } - // Fetch a flush context and try to acquire the RLock - // The only time the Write Lock is held is when this context is no longer usable and a new one is being created. - // In this case, we need to re-read i.flushCtx in order to fetch the new one as soon as it's available. - // The newCtxAvailable chan is closed as soon as the new one is available to avoid a busy loop. - currentFlushCtx := i.flushCtx - for !currentFlushCtx.lock.TryRLock() { - select { - case <-currentFlushCtx.newCtxAvailable: - case <-ctx.Done(): - return &logproto.PushResponse{}, ctx.Err() - } - currentFlushCtx = i.flushCtx - } - err = instance.Push(ctx, req, currentFlushCtx) - currentFlushCtx.lock.RUnlock() - select { - case <-ctx.Done(): - return &logproto.PushResponse{}, ctx.Err() - case <-currentFlushCtx.flushDone: - return &logproto.PushResponse{}, err + if err = instance.Push(ctx, i.wal, req); err != nil { + return nil, err } + + return &logproto.PushResponse{}, nil } // GetStreamRates returns a response containing all streams and their current rate @@ -851,7 +806,7 @@ func (i *Ingester) GetOrCreateInstance(instanceID string) (*instance, error) { / inst, ok = i.instances[instanceID] if !ok { var err error - inst, err = newInstance(&i.cfg, i.periodicConfigs, instanceID, i.limiter, i.tenantConfigs, i.metrics, i.streamRateCalculator, i.writeLogManager, i.customStreamsTracker) + inst, err = newInstance(&i.cfg, i.periodicConfigs, instanceID, i.limiter, i.tenantConfigs, i.metrics, i.streamRateCalculator, i.writeLogManager, i.customStreamsTracker, i.logger) if err != nil { return nil, err } diff --git a/pkg/ingester-rf1/instance.go b/pkg/ingester-rf1/instance.go index 16a6758f4ec83..72f2f613a9090 100644 --- a/pkg/ingester-rf1/instance.go +++ b/pkg/ingester-rf1/instance.go @@ -7,6 +7,7 @@ import ( "net/http" "sync" + "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/grafana/dskit/httpgrpc" "github.com/prometheus/client_golang/prometheus" @@ -23,6 +24,7 @@ import ( "github.com/grafana/loki/v3/pkg/logql/syntax" "github.com/grafana/loki/v3/pkg/runtime" "github.com/grafana/loki/v3/pkg/storage/config" + "github.com/grafana/loki/v3/pkg/storage/wal" "github.com/grafana/loki/v3/pkg/util/constants" util_log "github.com/grafana/loki/v3/pkg/util/log" "github.com/grafana/loki/v3/pkg/validation" @@ -70,6 +72,7 @@ type instance struct { // tailers map[uint32]*tailer tailerMtx sync.RWMutex + logger log.Logger limiter *Limiter streamCountLimiter *streamCountLimiter ownedStreamsSvc *ownedStreamService @@ -87,10 +90,10 @@ type instance struct { customStreamsTracker push.UsageTracker } -func (i *instance) Push(ctx context.Context, req *logproto.PushRequest, flushCtx *flushCtx) error { +func (i *instance) Push(ctx context.Context, w *wal.Manager, req *logproto.PushRequest) error { rateLimitWholeStream := i.limiter.limits.ShardStreams(i.instanceID).Enabled - var appendErr error + results := make([]*wal.AppendResult, 0, len(req.Streams)) for _, reqStream := range req.Streams { s, _, err := i.streams.LoadOrStoreNew(reqStream.Labels, func() (*stream, error) { @@ -102,13 +105,27 @@ func (i *instance) Push(ctx context.Context, req *logproto.PushRequest, flushCtx }, ) if err != nil { - appendErr = err - continue + return err } + _, res, err := s.Push(ctx, w, reqStream.Entries, rateLimitWholeStream, i.customStreamsTracker) + if err != nil { + return err + } + results = append(results, res) + } - _, appendErr = s.Push(ctx, reqStream.Entries, rateLimitWholeStream, i.customStreamsTracker, flushCtx) + for _, result := range results { + select { + case <-ctx.Done(): + return ctx.Err() + case <-result.Done(): + if err := result.Err(); err != nil { + return err + } + } } - return appendErr + + return nil } func newInstance( @@ -121,8 +138,8 @@ func newInstance( streamRateCalculator *StreamRateCalculator, writeFailures *writefailures.Manager, customStreamsTracker push.UsageTracker, + logger log.Logger, ) (*instance, error) { - fmt.Println("new instance for", instanceID) invertedIndex, err := index.NewMultiInvertedIndex(periodConfigs, uint32(cfg.IndexShards)) if err != nil { return nil, err @@ -141,6 +158,7 @@ func newInstance( streamsRemovedTotal: streamsRemovedTotal.WithLabelValues(instanceID), // //tailers: map[uint32]*tailer{}, + logger: logger, limiter: limiter, streamCountLimiter: newStreamCountLimiter(instanceID, streams.Len, limiter, ownedStreamsSvc), ownedStreamsSvc: ownedStreamsSvc, diff --git a/pkg/ingester-rf1/stream.go b/pkg/ingester-rf1/stream.go index 8bd7bdd0e329d..44057694ccf3f 100644 --- a/pkg/ingester-rf1/stream.go +++ b/pkg/ingester-rf1/stream.go @@ -17,6 +17,7 @@ import ( "github.com/grafana/loki/v3/pkg/distributor/writefailures" "github.com/grafana/loki/v3/pkg/loghttp/push" "github.com/grafana/loki/v3/pkg/logproto" + "github.com/grafana/loki/v3/pkg/storage/wal" "github.com/grafana/loki/v3/pkg/util/flagext" "github.com/grafana/loki/v3/pkg/validation" ) @@ -130,21 +131,24 @@ func (s *stream) consumeChunk(_ context.Context, _ *logproto.Chunk) error { func (s *stream) Push( ctx context.Context, + wal *wal.Manager, entries []logproto.Entry, // Whether nor not to ingest all at once or not. It is a per-tenant configuration. rateLimitWholeStream bool, usageTracker push.UsageTracker, - flushCtx *flushCtx, -) (int, error) { +) (int, *wal.AppendResult, error) { toStore, invalid := s.validateEntries(ctx, entries, rateLimitWholeStream, usageTracker) if rateLimitWholeStream && hasRateLimitErr(invalid) { - return 0, errorForFailedEntries(s, invalid, len(entries)) + return 0, nil, errorForFailedEntries(s, invalid, len(entries)) } - bytesAdded := s.storeEntries(ctx, toStore, usageTracker, flushCtx) + bytesAdded, res, err := s.storeEntries(ctx, wal, toStore, usageTracker) + if err != nil { + return 0, nil, err + } - return bytesAdded, errorForFailedEntries(s, invalid, len(entries)) + return bytesAdded, res, errorForFailedEntries(s, invalid, len(entries)) } func errorForFailedEntries(s *stream, failedEntriesWithError []entryWithError, totalEntries int) error { @@ -195,7 +199,7 @@ func hasRateLimitErr(errs []entryWithError) bool { return ok } -func (s *stream) storeEntries(ctx context.Context, entries []*logproto.Entry, usageTracker push.UsageTracker, flushCtx *flushCtx) int { +func (s *stream) storeEntries(ctx context.Context, w *wal.Manager, entries []*logproto.Entry, usageTracker push.UsageTracker) (int, *wal.AppendResult, error) { if sp := opentracing.SpanFromContext(ctx); sp != nil { sp.LogKV("event", "stream started to store entries", "labels", s.labelsString) defer sp.LogKV("event", "stream finished to store entries") @@ -213,9 +217,18 @@ func (s *stream) storeEntries(ctx context.Context, entries []*logproto.Entry, us bytesAdded += len(entries[i].Line) } - flushCtx.segmentWriter.Append(s.tenant, s.labels.String(), s.labels, entries) + + res, err := w.Append(wal.AppendRequest{ + TenantID: s.tenant, + Labels: s.labels, + LabelsStr: s.labels.String(), + Entries: entries, + }) + if err != nil { + return 0, nil, err + } s.reportMetrics(ctx, outOfOrderSamples, outOfOrderBytes, 0, 0, usageTracker) - return bytesAdded + return bytesAdded, res, nil } func (s *stream) validateEntries(ctx context.Context, entries []logproto.Entry, rateLimitWholeStream bool, usageTracker push.UsageTracker) ([]*logproto.Entry, []entryWithError) {
feat
Use WAL Manager (#13491)
4d71ca3bbaf54841bfbcfbd7ca9503b481ee058a
2024-12-18 06:01:10
Trevor Whitney
ci: fix the docker driver build (#15354)
false
diff --git a/.github/jsonnetfile.json b/.github/jsonnetfile.json index 731d3c3c82974..e75ed698ab80f 100644 --- a/.github/jsonnetfile.json +++ b/.github/jsonnetfile.json @@ -8,7 +8,7 @@ "subdir": "workflows" } }, - "version": "21f1189544e3976070cbdb6463f64c7a32dcc176" + "version": "cfa24256090828f566f1ba59292ce65d8db4a4ae" } ], "legacyImports": true diff --git a/.github/jsonnetfile.lock.json b/.github/jsonnetfile.lock.json index d11f133725822..0f978214e1e77 100644 --- a/.github/jsonnetfile.lock.json +++ b/.github/jsonnetfile.lock.json @@ -8,8 +8,8 @@ "subdir": "workflows" } }, - "version": "21f1189544e3976070cbdb6463f64c7a32dcc176", - "sum": "IPS1oGR8k7jk6J2snciTycWFgtISCwXSPhJ3A+nEGvY=" + "version": "cfa24256090828f566f1ba59292ce65d8db4a4ae", + "sum": "tml1dcFlo15kEE6JvN/nPY2xkhfeF3ERZjAyFbnguHA=" } ], "legacyImports": false diff --git a/.github/release-workflows.jsonnet b/.github/release-workflows.jsonnet index 080dcae2d39c4..9c7aeb2cd1e0d 100644 --- a/.github/release-workflows.jsonnet +++ b/.github/release-workflows.jsonnet @@ -1,9 +1,14 @@ local lokiRelease = import 'workflows/main.jsonnet'; -local build = lokiRelease.build; +local build = lokiRelease.build; local releaseLibRef = 'main'; - local checkTemplate = 'grafana/loki-release/.github/workflows/check.yml@%s' % releaseLibRef; +local buildImageVersion = std.extVar('BUILD_IMAGE_VERSION'); +local buildImage = 'grafana/loki-build-image:%s' % buildImageVersion; +local golangCiLintVersion = 'v1.60.3'; +local imageBuildTimeoutMin = 60; +local imagePrefix = 'grafana'; +local dockerPluginDir = 'clients/cmd/docker-driver'; local imageJobs = { loki: build.image('loki', 'cmd/loki'), @@ -15,7 +20,7 @@ local imageJobs = { 'loki-canary-boringcrypto': build.image('loki-canary-boringcrypto', 'cmd/loki-canary-boringcrypto'), promtail: build.image('promtail', 'clients/cmd/promtail'), querytee: build.image('loki-query-tee', 'cmd/querytee', platform=['linux/amd64']), - 'loki-docker-driver': build.dockerPlugin('grafana/loki-docker-driver', 'clients/cmd/docker-driver', platform=['linux/amd64', 'linux/arm64']), + 'loki-docker-driver': build.dockerPlugin('loki-docker-driver', dockerPluginDir, buildImage=buildImage, platform=['linux/amd64', 'linux/arm64']), }; local weeklyImageJobs = { @@ -25,13 +30,6 @@ local weeklyImageJobs = { promtail: build.weeklyImage('promtail', 'clients/cmd/promtail'), }; -local buildImageVersion = std.extVar('BUILD_IMAGE_VERSION'); -local buildImage = 'grafana/loki-build-image:%s' % buildImageVersion; -local golangCiLintVersion = 'v1.60.3'; - -local imageBuildTimeoutMin = 60; -local imagePrefix = 'grafana'; - { 'patch-release-pr.yml': std.manifestYamlDoc( lokiRelease.releasePRWorkflow( @@ -77,6 +75,7 @@ local imagePrefix = 'grafana'; getDockerCredsFromVault=true, imagePrefix='grafana', releaseLibRef=releaseLibRef, + pluginBuildDir=dockerPluginDir, releaseRepo='grafana/loki', useGitHubAppToken=true, ), false, false diff --git a/.github/vendor/github.com/grafana/loki-release/workflows/build.libsonnet b/.github/vendor/github.com/grafana/loki-release/workflows/build.libsonnet index 72a47e901e890..d174c362c691a 100644 --- a/.github/vendor/github.com/grafana/loki-release/workflows/build.libsonnet +++ b/.github/vendor/github.com/grafana/loki-release/workflows/build.libsonnet @@ -108,14 +108,14 @@ local releaseLibStep = common.releaseLibStep; dockerPlugin: function( name, path, + buildImage, dockerfile='Dockerfile', context='release', platform=[ 'linux/amd64', 'linux/arm64', - 'linux/arm', ] - ) + ) job.new() + job.withStrategy({ 'fail-fast': true, @@ -136,6 +136,7 @@ local releaseLibStep = common.releaseLibStep; + step.withId('platform') + step.withRun(||| mkdir -p images + mkdir -p plugins platform="$(echo "${{ matrix.platform}}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT @@ -150,108 +151,39 @@ local releaseLibStep = common.releaseLibStep; step.new('Build and export', 'docker/build-push-action@v6') + step.withTimeoutMinutes('${{ fromJSON(env.BUILD_TIMEOUT) }}') + step.withIf('${{ fromJSON(needs.version.outputs.pr_created) }}') - + step.withEnv({ - IMAGE_TAG: '${{ needs.version.outputs.version }}', - }) + step.with({ context: context, file: 'release/%s/%s' % [path, dockerfile], platforms: '${{ matrix.platform }}', push: false, tags: '${{ env.IMAGE_PREFIX }}/%s:${{ needs.version.outputs.version }}-${{ steps.platform.outputs.platform_short }}' % [name], - outputs: 'type=docker,dest=release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar' % name, - 'build-args': 'IMAGE_TAG=${{ needs.version.outputs.version }},GOARCH=${{ steps.platform.outputs.platform_short }}', + outputs: 'type=local,dest=release/plugins/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}' % name, + 'build-args': ||| + %s + ||| % std.rstripChars(std.lines([ + 'IMAGE_TAG=${{ needs.version.outputs.version }}', + 'GOARCH=${{ steps.platform.outputs.platform_short }}', + ('BUILD_IMAGE=%s' % buildImage), + ]), '\n'), }), - releaseStep('Package as Docker plugin') + step.new('compress rootfs') + step.withIf('${{ fromJSON(needs.version.outputs.pr_created) }}') - + step.withEnv({ - IMAGE_TAG: '${{ needs.version.outputs.version }}', - BUILD_DIR: 'release/%s' % [path], - }) + step.withRun(||| - rm -rf "${{ env.BUILD_DIR }}/rootfs" || true - mkdir "${{ env.BUILD_DIR }}/rootfs" - tar -x -C "${{ env.BUILD_DIR }}/rootfs" -f "release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" - docker plugin create "${{ env.IMAGE_TAG }}${{ steps.platform.outputs.plugin_arch }}" "${{ env.BUILD_DIR }}" - |||), + tar -cf release/plugins/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar \ + -C release/plugins/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }} \ + . + ||| % [name, name]), step.new('upload artifacts', 'google-github-actions/upload-cloud-storage@v2') + step.withIf('${{ fromJSON(needs.version.outputs.pr_created) }}') + step.with({ - path: 'release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar' % name, - destination: '${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/images', //TODO: make bucket configurable + path: 'release/plugins/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar' % name, + destination: '${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/plugins', process_gcloudignore: false, }), ]), - weeklyDockerPlugin: function( - name, - path, - dockerfile='Dockerfile', - context='release', - platform=[ - 'linux/amd64', - 'linux/arm64', - 'linux/arm', - ] - ) - job.new() - + job.withStrategy({ - matrix: { - platform: platform, - }, - }) - + job.withSteps([ - common.fetchReleaseLib, - common.fetchReleaseRepo, - common.setupNode, - - step.new('Set up QEMU', 'docker/setup-qemu-action@v3'), - step.new('set up docker buildx', 'docker/setup-buildx-action@v3'), - step.new('Login to DockerHub (from vault)', 'grafana/shared-workflows/actions/dockerhub-login@main'), - - releaseStep('Get weekly version') - + step.withId('weekly-version') - + step.withRun(||| - echo "version=$(./tools/image-tag)" >> $GITHUB_OUTPUT - - platform="$(echo "${{ matrix.platform}}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" - echo "platform=${platform}" >> $GITHUB_OUTPUT - echo "platform_short=$(echo ${{ matrix.platform }} | cut -d / -f 2)" >> $GITHUB_OUTPUT - if [[ "${platform}" == "linux/arm64" ]]; then - echo "plugin_arch=-arm64" >> $GITHUB_OUTPUT - else - echo "plugin_arch=" >> $GITHUB_OUTPUT - fi - |||), - - step.new('Build and export', 'docker/build-push-action@v6') - + step.withTimeoutMinutes('${{ fromJSON(env.BUILD_TIMEOUT) }}') - + step.with({ - context: context, - file: 'release/%s/%s' % [path, dockerfile], - platforms: '${{ matrix.platform }}', - push: false, - tags: '${{ env.IMAGE_PREFIX }}/%s:${{ steps.weekly-version.outputs.version }}' % [name], - outputs: 'type=docker,dest=release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar' % name, - 'build-args': 'IMAGE_TAG=${{ steps.weekly-version.outputs.version }},GOARCH=${{ steps.weekly-version.outputs.platform_short }}', - }), - - releaseStep('Package and push as Docker plugin') - + step.withEnv({ - IMAGE_TAG: '${{ steps.weekly-version.outputs.version }}', - BUILD_DIR: 'release/%s' % [path], - }) - + step.withRun(||| - rm -rf "${{ env.BUILD_DIR }}/rootfs" || true - mkdir "${{ env.BUILD_DIR }}/rootfs" - tar -x -C "${{ env.BUILD_DIR }}/rootfs" -f "release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" - docker plugin create "${{ env.IMAGE_TAG }}${{ steps.platform.outputs.plugin_arch }}" "${{ env.BUILD_DIR }}" - docker plugin push "${{ env.IMAGE_TAG }}${{ steps.platform.outputs.plugin_arch }}" - |||), - ]), - version: job.new() + job.withSteps([ diff --git a/.github/vendor/github.com/grafana/loki-release/workflows/main.jsonnet b/.github/vendor/github.com/grafana/loki-release/workflows/main.jsonnet index b4d7b24246cf9..a642294498558 100644 --- a/.github/vendor/github.com/grafana/loki-release/workflows/main.jsonnet +++ b/.github/vendor/github.com/grafana/loki-release/workflows/main.jsonnet @@ -83,11 +83,13 @@ dockerUsername='grafanabot', getDockerCredsFromVault=false, imagePrefix='grafana', + pluginBuildDir='release/plugin-tmp-dir', publishBucket='', publishToGCS=false, releaseLibRef='main', releaseRepo='grafana/loki-release', useGitHubAppToken=true, + dockerPluginPath='clients/cmd/docker-driver', ) { name: 'create release', on: { @@ -119,7 +121,8 @@ shouldRelease: $.release.shouldRelease, createRelease: $.release.createRelease, publishImages: $.release.publishImages(getDockerCredsFromVault, dockerUsername), - publishRelease: $.release.publishRelease, + publishDockerPlugins: $.release.publishDockerPlugins(pluginBuildDir, getDockerCredsFromVault, dockerUsername), + publishRelease: $.release.publishRelease(['createRelease', 'publishImages', 'publishDockerPlugins']), }, }, check: { diff --git a/.github/vendor/github.com/grafana/loki-release/workflows/release.libsonnet b/.github/vendor/github.com/grafana/loki-release/workflows/release.libsonnet index b77d8fe615ec9..d35c8a76661e8 100644 --- a/.github/vendor/github.com/grafana/loki-release/workflows/release.libsonnet +++ b/.github/vendor/github.com/grafana/loki-release/workflows/release.libsonnet @@ -186,19 +186,57 @@ local pullRequestFooter = 'Merging this PR will release the [artifacts](https:// ] ), - publishRelease: job.new() - + job.withNeeds(['createRelease', 'publishImages']) - + job.withSteps([ - common.fetchReleaseRepo, - common.githubAppToken, - common.setToken, - releaseStep('publish release') - + step.withIf('${{ !fromJSON(needs.createRelease.outputs.exists) || (needs.createRelease.outputs.draft && fromJSON(needs.createRelease.outputs.draft)) }}') - + step.withEnv({ - GH_TOKEN: '${{ steps.github_app_token.outputs.token }}', - }) - + step.withRun(||| - gh release edit ${{ needs.createRelease.outputs.name }} --draft=false --latest=${{ needs.createRelease.outputs.isLatest }} - |||), - ]), + publishDockerPlugins: function(path, getDockerCredsFromVault=false, dockerUsername='grafanabot') + job.new() + + job.withNeeds(['createRelease']) + + job.withSteps( + [ + common.fetchReleaseLib, + common.fetchReleaseRepo, + common.googleAuth, + common.setupGoogleCloudSdk, + step.new('Set up QEMU', 'docker/setup-qemu-action@v3'), + step.new('set up docker buildx', 'docker/setup-buildx-action@v3'), + ] + (if getDockerCredsFromVault then [ + step.new('Login to DockerHub (from vault)', 'grafana/shared-workflows/actions/dockerhub-login@main'), + ] else [ + step.new('Login to DockerHub (from secrets)', 'docker/login-action@v3') + + step.with({ + username: dockerUsername, + password: '${{ secrets.DOCKER_PASSWORD }}', + }), + ]) + + [ + step.new('download and prepare plugins') + + step.withRun(||| + echo "downloading images to $(pwd)/plugins" + gsutil cp -r gs://${BUILD_ARTIFACTS_BUCKET}/${{ needs.createRelease.outputs.sha }}/plugins . + mkdir -p "release/%s" + ||| % path), + step.new('publish docker driver', './lib/actions/push-images') + + step.with({ + imageDir: 'plugins', + imagePrefix: '${{ env.IMAGE_PREFIX }}', + isPlugin: true, + buildDir: 'release/%s' % path, + }), + ] + ), + + publishRelease: function(dependencies=['createRelease']) + job.new() + + job.withNeeds(dependencies) + + job.withSteps([ + common.fetchReleaseRepo, + common.githubAppToken, + common.setToken, + releaseStep('publish release') + + step.withIf('${{ !fromJSON(needs.createRelease.outputs.exists) || (needs.createRelease.outputs.draft && fromJSON(needs.createRelease.outputs.draft)) }}') + + step.withEnv({ + GH_TOKEN: '${{ steps.github_app_token.outputs.token }}', + }) + + step.withRun(||| + gh release edit ${{ needs.createRelease.outputs.name }} --draft=false --latest=${{ needs.createRelease.outputs.isLatest }} + |||), + ]), } diff --git a/.github/vendor/github.com/grafana/loki-release/workflows/workflows.jsonnet b/.github/vendor/github.com/grafana/loki-release/workflows/workflows.jsonnet index 1992d23f0d3b9..930aa539f25c6 100644 --- a/.github/vendor/github.com/grafana/loki-release/workflows/workflows.jsonnet +++ b/.github/vendor/github.com/grafana/loki-release/workflows/workflows.jsonnet @@ -1,15 +1,22 @@ local lokiRelease = import 'main.jsonnet'; local build = lokiRelease.build; + + +local buildImage = 'grafana/loki-build-image:0.34.3'; +local dockerPluginDir = 'clients/cmd/docker-driver'; + { '.github/workflows/release-pr.yml': std.manifestYamlDoc( lokiRelease.releasePRWorkflow( imageJobs={ loki: build.image('fake-loki', 'cmd/loki'), + 'loki-docker-driver': build.dockerPlugin('loki-docker-driver', dockerPluginDir, buildImage=buildImage, platform=['linux/amd64', 'linux/arm64']), }, + buildImage=buildImage, buildArtifactsBucket='loki-build-artifacts', branches=['release-[0-9]+.[0-9]+.x'], imagePrefix='trevorwhitney075', - releaseLibRef='release-1.12.x', + releaseLibRef='release-1.14.x', releaseRepo='grafana/loki-release', skipValidation=false, versioningStrategy='always-bump-patch', @@ -21,12 +28,14 @@ local build = lokiRelease.build; lokiRelease.releasePRWorkflow( imageJobs={ loki: build.image('fake-loki', 'cmd/loki'), + 'loki-docker-driver': build.dockerPlugin('loki-docker-driver', dockerPluginDir, buildImage=buildImage, platform=['linux/amd64', 'linux/arm64']), }, + buildImage=buildImage, buildArtifactsBucket='loki-build-artifacts', branches=['release-[0-9]+.[0-9]+.x'], dryRun=true, imagePrefix='trevorwhitney075', - releaseLibRef='release-1.12.x', + releaseLibRef='release-1.14.x', releaseRepo='grafana/loki-release', skipValidation=false, versioningStrategy='always-bump-patch', @@ -41,11 +50,13 @@ local build = lokiRelease.build; lokiRelease.releaseWorkflow( branches=['release-[0-9]+.[0-9]+.x'], buildArtifactsBucket='loki-build-artifacts', - getDockerCredsFromVault=true, + dockerUsername='trevorwhitney075', + getDockerCredsFromVault=false, imagePrefix='trevorwhitney075', - releaseLibRef='release-1.12.x', + pluginBuildDir=dockerPluginDir, + releaseLibRef='release-1.14.x', releaseRepo='grafana/loki-release', - useGitHubAppToken=false, + useGitHubAppToken=true, ) + { name: 'Create Release', on+: { diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 5e90ce2c01920..82a801ec8668a 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -2,7 +2,7 @@ "check": "uses": "grafana/loki-release/.github/workflows/check.yml@main" "with": - "build_image": "grafana/loki-build-image:0.34.1" + "build_image": "grafana/loki-build-image:0.34.3" "golang_ci_lint_version": "v1.60.3" "release_lib_ref": "main" "skip_validation": false diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml index 55bbd64d6c3f9..cc56042b4420f 100644 --- a/.github/workflows/images.yml +++ b/.github/workflows/images.yml @@ -2,7 +2,7 @@ "check": "uses": "grafana/loki-release/.github/workflows/check.yml@main" "with": - "build_image": "grafana/loki-build-image:0.34.1" + "build_image": "grafana/loki-build-image:0.34.3" "golang_ci_lint_version": "v1.60.3" "release_lib_ref": "main" "skip_validation": false diff --git a/.github/workflows/minor-release-pr.yml b/.github/workflows/minor-release-pr.yml index 0db833dec9a2f..b8e46bf6816df 100644 --- a/.github/workflows/minor-release-pr.yml +++ b/.github/workflows/minor-release-pr.yml @@ -16,7 +16,7 @@ jobs: check: uses: "grafana/loki-release/.github/workflows/check.yml@main" with: - build_image: "grafana/loki-build-image:0.34.1" + build_image: "grafana/loki-build-image:0.34.3" golang_ci_lint_version: "v1.60.3" release_lib_ref: "main" skip_validation: false @@ -144,7 +144,7 @@ jobs: --env SKIP_ARM \ --volume .:/src/loki \ --workdir /src/loki \ - --entrypoint /bin/sh "grafana/loki-build-image:0.34.1" + --entrypoint /bin/sh "grafana/loki-build-image:0.34.3" git config --global --add safe.directory /src/loki echo "${NFPM_SIGNING_KEY}" > $NFPM_SIGNING_KEY_FILE make dist packages @@ -631,6 +631,7 @@ jobs: name: "parse image platform" run: | mkdir -p images + mkdir -p plugins platform="$(echo "${{ matrix.platform}}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT @@ -641,37 +642,33 @@ jobs: echo "plugin_arch=" >> $GITHUB_OUTPUT fi working-directory: "release" - - env: - IMAGE_TAG: "${{ needs.version.outputs.version }}" - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" + - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" name: "Build and export" timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" uses: "docker/build-push-action@v6" with: - build-args: "IMAGE_TAG=${{ needs.version.outputs.version }},GOARCH=${{ steps.platform.outputs.platform_short }}" + build-args: | + IMAGE_TAG=${{ needs.version.outputs.version }} + GOARCH=${{ steps.platform.outputs.platform_short }} + BUILD_IMAGE=grafana/loki-build-image:0.34.3 context: "release" file: "release/clients/cmd/docker-driver/Dockerfile" - outputs: "type=docker,dest=release/images/grafana/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" + outputs: "type=local,dest=release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}" platforms: "${{ matrix.platform }}" push: false - tags: "${{ env.IMAGE_PREFIX }}/grafana/loki-docker-driver:${{ needs.version.outputs.version }}-${{ steps.platform.outputs.platform_short }}" - - env: - BUILD_DIR: "release/clients/cmd/docker-driver" - IMAGE_TAG: "${{ needs.version.outputs.version }}" - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" - name: "Package as Docker plugin" + tags: "${{ env.IMAGE_PREFIX }}/loki-docker-driver:${{ needs.version.outputs.version }}-${{ steps.platform.outputs.platform_short }}" + - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" + name: "compress rootfs" run: | - rm -rf "${{ env.BUILD_DIR }}/rootfs" || true - mkdir "${{ env.BUILD_DIR }}/rootfs" - tar -x -C "${{ env.BUILD_DIR }}/rootfs" -f "release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" - docker plugin create "${{ env.IMAGE_TAG }}${{ steps.platform.outputs.plugin_arch }}" "${{ env.BUILD_DIR }}" - working-directory: "release" + tar -cf release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar \ + -C release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }} \ + . - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" name: "upload artifacts" uses: "google-github-actions/upload-cloud-storage@v2" with: - destination: "${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/images" - path: "release/images/grafana/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" + destination: "${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/plugins" + path: "release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" process_gcloudignore: false strategy: fail-fast: true diff --git a/.github/workflows/patch-release-pr.yml b/.github/workflows/patch-release-pr.yml index f1b904d22f407..cfd24aefb9c20 100644 --- a/.github/workflows/patch-release-pr.yml +++ b/.github/workflows/patch-release-pr.yml @@ -16,7 +16,7 @@ jobs: check: uses: "grafana/loki-release/.github/workflows/check.yml@main" with: - build_image: "grafana/loki-build-image:0.34.1" + build_image: "grafana/loki-build-image:0.34.3" golang_ci_lint_version: "v1.60.3" release_lib_ref: "main" skip_validation: false @@ -144,7 +144,7 @@ jobs: --env SKIP_ARM \ --volume .:/src/loki \ --workdir /src/loki \ - --entrypoint /bin/sh "grafana/loki-build-image:0.34.1" + --entrypoint /bin/sh "grafana/loki-build-image:0.34.3" git config --global --add safe.directory /src/loki echo "${NFPM_SIGNING_KEY}" > $NFPM_SIGNING_KEY_FILE make dist packages @@ -631,6 +631,7 @@ jobs: name: "parse image platform" run: | mkdir -p images + mkdir -p plugins platform="$(echo "${{ matrix.platform}}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT @@ -641,37 +642,33 @@ jobs: echo "plugin_arch=" >> $GITHUB_OUTPUT fi working-directory: "release" - - env: - IMAGE_TAG: "${{ needs.version.outputs.version }}" - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" + - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" name: "Build and export" timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" uses: "docker/build-push-action@v6" with: - build-args: "IMAGE_TAG=${{ needs.version.outputs.version }},GOARCH=${{ steps.platform.outputs.platform_short }}" + build-args: | + IMAGE_TAG=${{ needs.version.outputs.version }} + GOARCH=${{ steps.platform.outputs.platform_short }} + BUILD_IMAGE=grafana/loki-build-image:0.34.3 context: "release" file: "release/clients/cmd/docker-driver/Dockerfile" - outputs: "type=docker,dest=release/images/grafana/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" + outputs: "type=local,dest=release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}" platforms: "${{ matrix.platform }}" push: false - tags: "${{ env.IMAGE_PREFIX }}/grafana/loki-docker-driver:${{ needs.version.outputs.version }}-${{ steps.platform.outputs.platform_short }}" - - env: - BUILD_DIR: "release/clients/cmd/docker-driver" - IMAGE_TAG: "${{ needs.version.outputs.version }}" - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" - name: "Package as Docker plugin" + tags: "${{ env.IMAGE_PREFIX }}/loki-docker-driver:${{ needs.version.outputs.version }}-${{ steps.platform.outputs.platform_short }}" + - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" + name: "compress rootfs" run: | - rm -rf "${{ env.BUILD_DIR }}/rootfs" || true - mkdir "${{ env.BUILD_DIR }}/rootfs" - tar -x -C "${{ env.BUILD_DIR }}/rootfs" -f "release/images/%s-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" - docker plugin create "${{ env.IMAGE_TAG }}${{ steps.platform.outputs.plugin_arch }}" "${{ env.BUILD_DIR }}" - working-directory: "release" + tar -cf release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar \ + -C release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }} \ + . - if: "${{ fromJSON(needs.version.outputs.pr_created) }}" name: "upload artifacts" uses: "google-github-actions/upload-cloud-storage@v2" with: - destination: "${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/images" - path: "release/images/grafana/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" + destination: "${{ env.BUILD_ARTIFACTS_BUCKET }}/${{ github.sha }}/plugins" + path: "release/plugins/loki-docker-driver-${{ needs.version.outputs.version}}-${{ steps.platform.outputs.platform }}.tar" process_gcloudignore: false strategy: fail-fast: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1628a0b57dfb5..426f523f80da7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -110,6 +110,48 @@ jobs: parent: false path: "release/dist" process_gcloudignore: false + publishDockerPlugins: + needs: + - "createRelease" + runs-on: "ubuntu-latest" + steps: + - name: "pull release library code" + uses: "actions/checkout@v4" + with: + path: "lib" + ref: "${{ env.RELEASE_LIB_REF }}" + repository: "grafana/loki-release" + - name: "pull code to release" + uses: "actions/checkout@v4" + with: + path: "release" + repository: "${{ env.RELEASE_REPO }}" + - name: "auth gcs" + uses: "google-github-actions/auth@v2" + with: + credentials_json: "${{ secrets.GCS_SERVICE_ACCOUNT_KEY }}" + - name: "Set up Cloud SDK" + uses: "google-github-actions/setup-gcloud@v2" + with: + version: ">= 452.0.0" + - name: "Set up QEMU" + uses: "docker/setup-qemu-action@v3" + - name: "set up docker buildx" + uses: "docker/setup-buildx-action@v3" + - name: "Login to DockerHub (from vault)" + uses: "grafana/shared-workflows/actions/dockerhub-login@main" + - name: "download and prepare plugins" + run: | + echo "downloading images to $(pwd)/plugins" + gsutil cp -r gs://${BUILD_ARTIFACTS_BUCKET}/${{ needs.createRelease.outputs.sha }}/plugins . + mkdir -p "release/clients/cmd/docker-driver" + - name: "publish docker driver" + uses: "./lib/actions/push-images" + with: + buildDir: "release/clients/cmd/docker-driver" + imageDir: "plugins" + imagePrefix: "${{ env.IMAGE_PREFIX }}" + isPlugin: true publishImages: needs: - "createRelease" @@ -148,6 +190,7 @@ jobs: needs: - "createRelease" - "publishImages" + - "publishDockerPlugins" runs-on: "ubuntu-latest" steps: - name: "pull code to release" diff --git a/Makefile b/Makefile index 2b152ac6ae739..76de2fac98dfc 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ CI ?= false # Ensure you run `make release-workflows` after changing this GO_VERSION := 1.23.1 -BUILD_IMAGE_TAG := 0.34.1 +BUILD_IMAGE_TAG := 0.34.3 IMAGE_TAG ?= $(shell ./tools/image-tag) GIT_REVISION := $(shell git rev-parse --short HEAD) @@ -672,12 +672,12 @@ logql-analyzer-push: logql-analyzer-image # Build image build-image: ## build the build docker image $(OCI_BUILD) -t $(BUILD_IMAGE) ./loki-build-image -build-image-push: build-image +build-image-push: ifneq (,$(findstring WIP,$(IMAGE_TAG))) @echo "Cannot push a WIP image, commit changes first"; \ false; endif - $(OCI_PUSH) -t $(BUILD_IMAGE) + DOCKER_BUILDKIT=1 docker buildx build $(OCI_PLATFORMS) $(OCI_BUILD_ARGS) $(OCI_PUSH_ARGS) -t $(BUILD_IMAGE) ./loki-build-image # Loki Operator loki-operator-image: ## build the operator docker image @@ -873,8 +873,12 @@ scan-vulnerabilities: trivy snyk .PHONY: release-workflows release-workflows: +ifeq ($(BUILD_IN_CONTAINER),true) + $(run_in_container) +else pushd $(CURDIR)/.github && jb update && popd jsonnet -SJ .github/vendor -m .github/workflows -V BUILD_IMAGE_VERSION=$(BUILD_IMAGE_TAG) .github/release-workflows.jsonnet +endif .PHONY: release-workflows-check release-workflows-check:
ci
fix the docker driver build (#15354)
28a413539e4d14311a2d5d58e7e145e0e1e56ac6
2024-01-18 20:32:23
Periklis Tsirakidis
operator: Replace deprecated ctrl-runtime cfg with custom package (#11678)
false
diff --git a/operator/apis/config/v1/projectconfig_types.go b/operator/apis/config/v1/projectconfig_types.go index b6a80175266b6..488f7b2cb64f3 100644 --- a/operator/apis/config/v1/projectconfig_types.go +++ b/operator/apis/config/v1/projectconfig_types.go @@ -2,7 +2,7 @@ package v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - cfg "sigs.k8s.io/controller-runtime/pkg/config/v1alpha1" //nolint:staticcheck + configv1alpha1 "k8s.io/component-base/config/v1alpha1" ) // BuiltInCertManagement is the configuration for the built-in facility to generate and rotate @@ -142,6 +142,67 @@ const ( TLSProfileModernType TLSProfileType = "Modern" ) +// ControllerManagerConfigurationSpec defines the desired state of GenericControllerManagerConfiguration. +type ControllerManagerConfigurationSpec struct { + // LeaderElection is the LeaderElection config to be used when configuring + // the manager.Manager leader election + // +optional + LeaderElection *configv1alpha1.LeaderElectionConfiguration `json:"leaderElection,omitempty"` + + // Metrics contains the controller metrics configuration + // +optional + Metrics ControllerMetrics `json:"metrics,omitempty"` + + // Health contains the controller health configuration + // +optional + Health ControllerHealth `json:"health,omitempty"` + + // Webhook contains the controllers webhook configuration + // +optional + Webhook ControllerWebhook `json:"webhook,omitempty"` +} + +// ControllerMetrics defines the metrics configs. +type ControllerMetrics struct { + // BindAddress is the TCP address that the controller should bind to + // for serving prometheus metrics. + // It can be set to "0" to disable the metrics serving. + // +optional + BindAddress string `json:"bindAddress,omitempty"` +} + +// ControllerHealth defines the health configs. +type ControllerHealth struct { + // HealthProbeBindAddress is the TCP address that the controller should bind to + // for serving health probes + // It can be set to "0" or "" to disable serving the health probe. + // +optional + HealthProbeBindAddress string `json:"healthProbeBindAddress,omitempty"` +} + +// ControllerWebhook defines the webhook server for the controller. +type ControllerWebhook struct { + // Port is the port that the webhook server serves at. + // It is used to set webhook.Server.Port. + // +optional + Port *int `json:"port,omitempty"` +} + +//+kubebuilder:object:root=true + +// ControllerManagerConfiguration is the Schema for the GenericControllerManagerConfigurations API. +type ControllerManagerConfiguration struct { + metav1.TypeMeta `json:",inline"` + + // ControllerManagerConfiguration returns the contfigurations for controllers + ControllerManagerConfigurationSpec `json:",inline"` +} + +// Complete returns the configuration for controller-runtime. +func (c *ControllerManagerConfigurationSpec) Complete() (ControllerManagerConfigurationSpec, error) { + return *c, nil +} + //+kubebuilder:object:root=true // ProjectConfig is the Schema for the projectconfigs API @@ -149,7 +210,7 @@ type ProjectConfig struct { metav1.TypeMeta `json:",inline"` // ControllerManagerConfigurationSpec returns the contfigurations for controllers - cfg.ControllerManagerConfigurationSpec `json:",inline"` + ControllerManagerConfigurationSpec `json:",inline"` Gates FeatureGates `json:"featureGates,omitempty"` } diff --git a/operator/apis/config/v1/zz_generated.deepcopy.go b/operator/apis/config/v1/zz_generated.deepcopy.go index ef20274e286eb..f047818445aa4 100644 --- a/operator/apis/config/v1/zz_generated.deepcopy.go +++ b/operator/apis/config/v1/zz_generated.deepcopy.go @@ -6,6 +6,7 @@ package v1 import ( runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/component-base/config/v1alpha1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -23,6 +24,104 @@ func (in *BuiltInCertManagement) DeepCopy() *BuiltInCertManagement { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerHealth) DeepCopyInto(out *ControllerHealth) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerHealth. +func (in *ControllerHealth) DeepCopy() *ControllerHealth { + if in == nil { + return nil + } + out := new(ControllerHealth) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerManagerConfiguration) DeepCopyInto(out *ControllerManagerConfiguration) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ControllerManagerConfigurationSpec.DeepCopyInto(&out.ControllerManagerConfigurationSpec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerManagerConfiguration. +func (in *ControllerManagerConfiguration) DeepCopy() *ControllerManagerConfiguration { + if in == nil { + return nil + } + out := new(ControllerManagerConfiguration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ControllerManagerConfiguration) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerManagerConfigurationSpec) DeepCopyInto(out *ControllerManagerConfigurationSpec) { + *out = *in + if in.LeaderElection != nil { + in, out := &in.LeaderElection, &out.LeaderElection + *out = new(v1alpha1.LeaderElectionConfiguration) + (*in).DeepCopyInto(*out) + } + out.Metrics = in.Metrics + out.Health = in.Health + in.Webhook.DeepCopyInto(&out.Webhook) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerManagerConfigurationSpec. +func (in *ControllerManagerConfigurationSpec) DeepCopy() *ControllerManagerConfigurationSpec { + if in == nil { + return nil + } + out := new(ControllerManagerConfigurationSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerMetrics) DeepCopyInto(out *ControllerMetrics) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerMetrics. +func (in *ControllerMetrics) DeepCopy() *ControllerMetrics { + if in == nil { + return nil + } + out := new(ControllerMetrics) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerWebhook) DeepCopyInto(out *ControllerWebhook) { + *out = *in + if in.Port != nil { + in, out := &in.Port, &out.Port + *out = new(int) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerWebhook. +func (in *ControllerWebhook) DeepCopy() *ControllerWebhook { + if in == nil { + return nil + } + out := new(ControllerWebhook) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FeatureGates) DeepCopyInto(out *FeatureGates) { *out = *in diff --git a/operator/config/docs/config.json b/operator/config/docs/config.json index 3d912e857d2b4..fb1b7d8a11b2b 100644 --- a/operator/config/docs/config.json +++ b/operator/config/docs/config.json @@ -4,7 +4,13 @@ ], "hideTypePatterns": [ "ParseError$", - "List$" + "List$", + "ControllerHealth$", + "ControllerManagerConfiguration$", + "ControllerManagerConfigurationSpec$", + "ControllerMetrics$", + "ControllerWebhook$", + "ProjectConfig$" ], "externalPackages": [ { @@ -38,22 +44,6 @@ { "typeMatchPrefix": "^k8s\\.io/component-base/config/v1alpha1\\.LeaderElectionConfiguration$", "docsURLTemplate": "https://pkg.go.dev/k8s.io/component-base/config#LeaderElectionConfiguration" - }, - { - "typeMatchPrefix": "^sigs\\.k8s\\.io/controller-runtime/pkg/config/v1alpha1\\.ControllerConfigurationSpec$", - "docsURLTemplate": "https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerConfigurationSpec" - }, - { - "typeMatchPrefix": "^sigs\\.k8s\\.io/controller-runtime/pkg/config/v1alpha1\\.ControllerMetrics$", - "docsURLTemplate": "https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerMetrics" - }, - { - "typeMatchPrefix": "^sigs\\.k8s\\.io/controller-runtime/pkg/config/v1alpha1\\.ControllerHealth$", - "docsURLTemplate": "https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerHealth" - }, - { - "typeMatchPrefix": "^sigs\\.k8s\\.io/controller-runtime/pkg/config/v1alpha1\\.ControllerWebhook$", - "docsURLTemplate": "https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerWebhook" } ], "typeDisplayNamePrefixOverrides": { @@ -66,4 +56,4 @@ "github.com/grafana/loki/operator/apis/loki/config/v1": "Feature Gates" }, "markdownDisabled": false -} \ No newline at end of file +} diff --git a/operator/docs/operator/feature-gates.md b/operator/docs/operator/feature-gates.md index 7475dfa8a1cc0..1d5c046be7755 100644 --- a/operator/docs/operator/feature-gates.md +++ b/operator/docs/operator/feature-gates.md @@ -99,9 +99,6 @@ The refresh is applied to all LokiStack certificates at once.</p> </table> ## FeatureGates { #config-loki-grafana-com-v1-FeatureGates } -<p> -(<em>Appears on:</em><a href="#config-loki-grafana-com-v1-ProjectConfig">ProjectConfig</a>) -</p> <div> <p>FeatureGates is the supported set of all operator feature gates.</p> </div> @@ -415,156 +412,6 @@ bool </tbody> </table> -## ProjectConfig { #config-loki-grafana-com-v1-ProjectConfig } -<div> -<p>ProjectConfig is the Schema for the projectconfigs API</p> -</div> -<table> -<thead> -<tr> -<th>Field</th> -<th>Description</th> -</tr> -</thead> -<tbody> -<tr> -<td> -<code>syncPeriod</code><br/> -<em> -<a href="https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Duration"> -Kubernetes meta/v1.Duration -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>SyncPeriod determines the minimum frequency at which watched resources are -reconciled. A lower period will correct entropy more quickly, but reduce -responsiveness to change if there are many watched resources. Change this -value only if you know what you are doing. Defaults to 10 hours if unset. -there will a 10 percent jitter between the SyncPeriod of all controllers -so that all controllers will not send list requests simultaneously.</p> -</td> -</tr> -<tr> -<td> -<code>leaderElection</code><br/> -<em> -<a href="https://pkg.go.dev/k8s.io/component-base/config#LeaderElectionConfiguration"> -Kubernetes v1alpha1.LeaderElectionConfiguration -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>LeaderElection is the LeaderElection config to be used when configuring -the manager.Manager leader election</p> -</td> -</tr> -<tr> -<td> -<code>cacheNamespace</code><br/> -<em> -string -</em> -</td> -<td> -<em>(Optional)</em> -<p>CacheNamespace if specified restricts the manager&rsquo;s cache to watch objects in -the desired namespace Defaults to all namespaces</p> -<p>Note: If a namespace is specified, controllers can still Watch for a -cluster-scoped resource (e.g Node). For namespaced resources the cache -will only hold objects from the desired namespace.</p> -</td> -</tr> -<tr> -<td> -<code>gracefulShutDown</code><br/> -<em> -<a href="https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Duration"> -Kubernetes meta/v1.Duration -</a> -</em> -</td> -<td> -<p>GracefulShutdownTimeout is the duration given to runnable to stop before the manager actually returns on stop. -To disable graceful shutdown, set to time.Duration(0) -To use graceful shutdown without timeout, set to a negative duration, e.G. time.Duration(-1) -The graceful shutdown is skipped for safety reasons in case the leader election lease is lost.</p> -</td> -</tr> -<tr> -<td> -<code>controller</code><br/> -<em> -<a href="https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerConfigurationSpec"> -K8S Controller-runtime v1alpha1.ControllerConfigurationSpec -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>Controller contains global configuration options for controllers -registered within this manager.</p> -</td> -</tr> -<tr> -<td> -<code>metrics</code><br/> -<em> -<a href="https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerMetrics"> -K8S Controller-runtime v1alpha1.ControllerMetrics -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>Metrics contains the controller metrics configuration</p> -</td> -</tr> -<tr> -<td> -<code>health</code><br/> -<em> -<a href="https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerHealth"> -K8S Controller-runtime v1alpha1.ControllerHealth -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>Health contains the controller health configuration</p> -</td> -</tr> -<tr> -<td> -<code>webhook</code><br/> -<em> -<a href="https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/config/v1alpha1#ControllerWebhook"> -K8S Controller-runtime v1alpha1.ControllerWebhook -</a> -</em> -</td> -<td> -<em>(Optional)</em> -<p>Webhook contains the controllers webhook configuration</p> -</td> -</tr> -<tr> -<td> -<code>featureGates</code><br/> -<em> -<a href="#config-loki-grafana-com-v1-FeatureGates"> -FeatureGates -</a> -</em> -</td> -<td> -</td> -</tr> -</tbody> -</table> - ## TLSProfileType { #config-loki-grafana-com-v1-TLSProfileType } (<code>string</code> alias) <div> diff --git a/operator/go.mod b/operator/go.mod index 4ffc3899d11ce..0ee7c037f16cc 100644 --- a/operator/go.mod +++ b/operator/go.mod @@ -23,6 +23,7 @@ require ( k8s.io/apimachinery v0.27.7 k8s.io/apiserver v0.27.7 k8s.io/client-go v0.27.7 + k8s.io/component-base v0.27.7 k8s.io/utils v0.0.0-20230505201702-9f6742963106 sigs.k8s.io/controller-runtime v0.15.3 sigs.k8s.io/yaml v1.3.0 @@ -150,7 +151,6 @@ require ( gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.27.7 // indirect - k8s.io/component-base v0.27.7 // indirect k8s.io/klog/v2 v2.100.1 // indirect k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect diff --git a/operator/internal/config/loader.go b/operator/internal/config/loader.go new file mode 100644 index 0000000000000..b5af090ddb887 --- /dev/null +++ b/operator/internal/config/loader.go @@ -0,0 +1,30 @@ +package config + +import ( + "errors" + "fmt" + "os" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" + + configv1 "github.com/grafana/loki/operator/apis/config/v1" +) + +var errConfigFileLoading = errors.New("could not read file at path") + +func loadConfigFile(scheme *runtime.Scheme, configFile string) (*configv1.ProjectConfig, error) { + content, err := os.ReadFile(configFile) + if err != nil { + return nil, fmt.Errorf("%w %s", errConfigFileLoading, configFile) + } + + codecs := serializer.NewCodecFactory(scheme) + + outConfig := &configv1.ProjectConfig{} + if err = runtime.DecodeInto(codecs.UniversalDecoder(), content, outConfig); err != nil { + return nil, fmt.Errorf("could not decode file into runtime.Object: %w", err) + } + + return outConfig, nil +} diff --git a/operator/internal/config/options.go b/operator/internal/config/options.go new file mode 100644 index 0000000000000..8aeba0eb53b3f --- /dev/null +++ b/operator/internal/config/options.go @@ -0,0 +1,94 @@ +package config + +import ( + "fmt" + "reflect" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/webhook" + + configv1 "github.com/grafana/loki/operator/apis/config/v1" +) + +// LoadConfig initializes the controller configuration, optionally overriding the defaults +// from a provided configuration file. +func LoadConfig(scheme *runtime.Scheme, configFile string) (*configv1.ProjectConfig, ctrl.Options, error) { + options := ctrl.Options{Scheme: scheme} + if configFile == "" { + return &configv1.ProjectConfig{}, options, nil + } + + ctrlCfg, err := loadConfigFile(scheme, configFile) + if err != nil { + return nil, options, fmt.Errorf("failed to parse controller manager config file: %w", err) + } + + options = mergeOptionsFromFile(options, ctrlCfg) + return ctrlCfg, options, nil +} + +func mergeOptionsFromFile(o manager.Options, cfg *configv1.ProjectConfig) manager.Options { + o = setLeaderElectionConfig(o, cfg.ControllerManagerConfigurationSpec) + + if o.MetricsBindAddress == "" && cfg.Metrics.BindAddress != "" { + o.MetricsBindAddress = cfg.Metrics.BindAddress + } + + if o.HealthProbeBindAddress == "" && cfg.Health.HealthProbeBindAddress != "" { + o.HealthProbeBindAddress = cfg.Health.HealthProbeBindAddress + } + + //nolint:staticcheck + if o.Port == 0 && cfg.Webhook.Port != nil { + o.Port = *cfg.Webhook.Port + } + + //nolint:staticcheck + if o.WebhookServer == nil { + o.WebhookServer = webhook.NewServer(webhook.Options{ + Port: o.Port, + }) + } + + return o +} + +func setLeaderElectionConfig(o manager.Options, obj configv1.ControllerManagerConfigurationSpec) manager.Options { + if obj.LeaderElection == nil { + // The source does not have any configuration; noop + return o + } + + if !o.LeaderElection && obj.LeaderElection.LeaderElect != nil { + o.LeaderElection = *obj.LeaderElection.LeaderElect + } + + if o.LeaderElectionResourceLock == "" && obj.LeaderElection.ResourceLock != "" { + o.LeaderElectionResourceLock = obj.LeaderElection.ResourceLock + } + + if o.LeaderElectionNamespace == "" && obj.LeaderElection.ResourceNamespace != "" { + o.LeaderElectionNamespace = obj.LeaderElection.ResourceNamespace + } + + if o.LeaderElectionID == "" && obj.LeaderElection.ResourceName != "" { + o.LeaderElectionID = obj.LeaderElection.ResourceName + } + + if o.LeaseDuration == nil && !reflect.DeepEqual(obj.LeaderElection.LeaseDuration, metav1.Duration{}) { + o.LeaseDuration = &obj.LeaderElection.LeaseDuration.Duration + } + + if o.RenewDeadline == nil && !reflect.DeepEqual(obj.LeaderElection.RenewDeadline, metav1.Duration{}) { + o.RenewDeadline = &obj.LeaderElection.RenewDeadline.Duration + } + + if o.RetryPeriod == nil && !reflect.DeepEqual(obj.LeaderElection.RetryPeriod, metav1.Duration{}) { + o.RetryPeriod = &obj.LeaderElection.RetryPeriod.Duration + } + + return o +} diff --git a/operator/main.go b/operator/main.go index 6b101175407e7..ffa16608707cd 100644 --- a/operator/main.go +++ b/operator/main.go @@ -21,6 +21,7 @@ import ( lokiv1 "github.com/grafana/loki/operator/apis/loki/v1" lokiv1beta1 "github.com/grafana/loki/operator/apis/loki/v1beta1" lokictrl "github.com/grafana/loki/operator/controllers/loki" + "github.com/grafana/loki/operator/internal/config" "github.com/grafana/loki/operator/internal/metrics" "github.com/grafana/loki/operator/internal/operator" "github.com/grafana/loki/operator/internal/validation" @@ -59,14 +60,10 @@ func main() { var err error - ctrlCfg := ctrlconfigv1.ProjectConfig{} - options := ctrl.Options{Scheme: scheme} - if configFile != "" { - options, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile).OfKind(&ctrlCfg)) //nolint:staticcheck - if err != nil { - logger.Error(err, "failed to parse controller manager config file") - os.Exit(1) - } + ctrlCfg, options, err := config.LoadConfig(scheme, configFile) + if err != nil { + logger.Error(err, "failed to load operator configuration") + os.Exit(1) } if ctrlCfg.Gates.LokiStackAlerts && !ctrlCfg.Gates.ServiceMonitors {
operator
Replace deprecated ctrl-runtime cfg with custom package (#11678)
ffd9e29486d3222aeb33b500f79be162fba10982
2021-12-29 23:11:39
Dylan Guedes
docs: Fix list of Ruler supported storages (#5008)
false
diff --git a/docs/sources/rules/_index.md b/docs/sources/rules/_index.md index 556f364547849..9dd214861212e 100644 --- a/docs/sources/rules/_index.md +++ b/docs/sources/rules/_index.md @@ -253,7 +253,7 @@ ruler: ## Ruler storage -The Ruler supports six kinds of storage: configdb, azure, gcs, s3, swift, and local. Most kinds of storage work with the sharded Ruler configuration in an obvious way, i.e. configure all Rulers to use the same backend. +The Ruler supports five kinds of storage: azure, gcs, s3, swift, and local. Most kinds of storage work with the sharded Ruler configuration in an obvious way, i.e. configure all Rulers to use the same backend. The local implementation reads the rule files off of the local filesystem. This is a read-only backend that does not support the creation and deletion of rules through the [Ruler API](../api/#ruler). Despite the fact that it reads the local filesystem this method can still be used in a sharded Ruler configuration if the operator takes care to load the same rules to every Ruler. For instance, this could be accomplished by mounting a [Kubernetes ConfigMap](https://kubernetes.io/docs/concepts/configuration/configmap/) onto every Ruler pod.
docs
Fix list of Ruler supported storages (#5008)
2a2d1f9178564ef2a6a94592431206b566ba6b26
2023-01-05 01:15:51
Ammar Lakis
docs: Fix promtail installation doc (#8007)
false
diff --git a/docs/sources/clients/promtail/installation.md b/docs/sources/clients/promtail/installation.md index 693d5296ea9c1..a19d72456fd4f 100644 --- a/docs/sources/clients/promtail/installation.md +++ b/docs/sources/clients/promtail/installation.md @@ -37,7 +37,7 @@ helm repo update Finally, Promtail can be deployed with: ```bash -$ helm upgrade --install promtail grafana/promtail --set "loki.serviceName=loki" +helm upgrade --install promtail grafana/promtail ``` ## Kubernetes
docs
Fix promtail installation doc (#8007)
c25841901c9dcfdf067eb6052938077fd18e4ddc
2025-01-30 23:19:03
Owen Diehl
feat(kafka): tenant topics (#15977)
false
diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index cfc4db5c451f6..c06ffc72c12aa 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -2368,6 +2368,28 @@ otlp_config: # Enable writes to Ingesters during Push requests. Defaults to true. # CLI flag: -distributor.ingester-writes-enabled [ingester_writes_enabled: <boolean> | default = true] + +tenant_topic: + # Enable the tenant topic tee, which writes logs to Kafka topics based on + # tenant IDs instead of using multitenant topics/partitions. + # CLI flag: -distributor.tenant-topic-tee.enabled + [enabled: <boolean> | default = false] + + # Prefix to prepend to tenant IDs to form the final Kafka topic name + # CLI flag: -distributor.tenant-topic-tee.topic-prefix + [topic_prefix: <string> | default = "loki.tenant"] + + # Maximum number of bytes that can be buffered before producing to Kafka + # CLI flag: -distributor.tenant-topic-tee.max-buffered-bytes + [max_buffered_bytes: <int> | default = 100MiB] + + # Maximum size of a single Kafka record in bytes + # CLI flag: -distributor.tenant-topic-tee.max-record-size-bytes + [max_record_size_bytes: <int> | default = 15MiB249KiB] + + # Topic strategy to use. Valid values are 'simple' or 'automatic' + # CLI flag: -distributor.tenant-topic-tee.strategy + [strategy: <string> | default = "simple"] ``` ### etcd diff --git a/pkg/distributor/distributor.go b/pkg/distributor/distributor.go index 8643b3d0726f0..d44206a3e4998 100644 --- a/pkg/distributor/distributor.go +++ b/pkg/distributor/distributor.go @@ -99,6 +99,9 @@ type Config struct { KafkaEnabled bool `yaml:"kafka_writes_enabled"` IngesterEnabled bool `yaml:"ingester_writes_enabled"` KafkaConfig kafka.Config `yaml:"-"` + + // TODO: cleanup config + TenantTopic TenantTopicConfig `yaml:"tenant_topic" category:"experimental"` } // RegisterFlags registers distributor-related flags. @@ -107,6 +110,7 @@ func (cfg *Config) RegisterFlags(fs *flag.FlagSet) { cfg.DistributorRing.RegisterFlags(fs) cfg.RateStore.RegisterFlagsWithPrefix("distributor.rate-store", fs) cfg.WriteFailuresLogging.RegisterFlagsWithPrefix("distributor.write-failures-logging", fs) + cfg.TenantTopic.RegisterFlags(fs) fs.IntVar(&cfg.PushWorkerCount, "distributor.push-worker-count", 256, "Number of workers to push batches to ingesters.") fs.BoolVar(&cfg.KafkaEnabled, "distributor.kafka-writes-enabled", false, "Enable writes to Kafka during Push requests.") fs.BoolVar(&cfg.IngesterEnabled, "distributor.ingester-writes-enabled", true, "Enable writes to Ingesters during Push requests. Defaults to true.") @@ -116,6 +120,9 @@ func (cfg *Config) Validate() error { if !cfg.KafkaEnabled && !cfg.IngesterEnabled { return fmt.Errorf("at least one of kafka and ingestor writes must be enabled") } + if err := cfg.TenantTopic.Validate(); err != nil { + return errors.Wrap(err, "validating tenant topic config") + } return nil } @@ -246,6 +253,16 @@ func New( } kafkaWriter = kafka_client.NewProducer(kafkaClient, cfg.KafkaConfig.ProducerMaxBufferedBytes, prometheus.WrapRegistererWithPrefix("loki_", registerer)) + + // TODO: cleanup/make independent of whether we write kafka as primary? + if cfg.TenantTopic.Enabled { + w, err := NewTenantTopicWriter(cfg.TenantTopic, kafkaClient, overrides, registerer, logger) + if err != nil { + return nil, fmt.Errorf("failed to start tenant topic tee: %w", err) + } + + tee = WrapTee(tee, w) + } } d := &Distributor{ diff --git a/pkg/distributor/ratestore.go b/pkg/distributor/ratestore.go index 0fe5c3aca0bce..52845a28476c7 100644 --- a/pkg/distributor/ratestore.go +++ b/pkg/distributor/ratestore.go @@ -257,13 +257,6 @@ func (s *rateStore) aggregateByShard(ctx context.Context, streamRates map[string return rates } -func max(a, b int64) int64 { - if a > b { - return a - } - return b -} - func (s *rateStore) getRates(ctx context.Context, clients []ingesterClient) map[string]map[uint64]*logproto.StreamRate { if s.debug { if sp := opentracing.SpanFromContext(ctx); sp != nil { diff --git a/pkg/distributor/tenant_topic_tee.go b/pkg/distributor/tenant_topic_tee.go new file mode 100644 index 0000000000000..7d7ad84e7bc53 --- /dev/null +++ b/pkg/distributor/tenant_topic_tee.go @@ -0,0 +1,395 @@ +package distributor + +import ( + "context" + "errors" + "flag" + "fmt" + "math" + "sync" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/grafana/dskit/flagext" + "github.com/prometheus/client_golang/prometheus" + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + "golang.org/x/sync/singleflight" + + "github.com/grafana/loki/v3/pkg/kafka" + "github.com/grafana/loki/v3/pkg/kafka/client" +) + +// Strategy represents the topic creation strategy +type Strategy uint8 + +const ( + SimpleStrategy Strategy = iota + AutomaticStrategy +) + +func (s Strategy) String() string { + switch s { + case SimpleStrategy: + return "simple" + case AutomaticStrategy: + return "automatic" + default: + return "unknown" + } +} + +// ParseStrategy converts a string to a Strategy +func ParseStrategy(s string) (Strategy, error) { + switch s { + case "simple": + return SimpleStrategy, nil + case "automatic": + return AutomaticStrategy, nil + default: + return SimpleStrategy, fmt.Errorf("invalid strategy %q, must be either 'simple' or 'automatic'", s) + } +} + +// TenantTopicConfig configures the TenantTopicWriter +type TenantTopicConfig struct { + Enabled bool `yaml:"enabled"` + + // TopicPrefix is prepended to tenant IDs to form the final topic name + TopicPrefix string `yaml:"topic_prefix"` + // MaxBufferedBytes is the maximum number of bytes that can be buffered before producing to Kafka + MaxBufferedBytes flagext.Bytes `yaml:"max_buffered_bytes"` + + // MaxRecordSizeBytes is the maximum size of a single Kafka record + MaxRecordSizeBytes flagext.Bytes `yaml:"max_record_size_bytes"` + + // Strategy determines how topics are created and partitioned + Strategy string `yaml:"strategy"` +} + +// Validate ensures the config is valid +func (cfg *TenantTopicConfig) Validate() error { + if !cfg.Enabled { + return nil + } + + if cfg.TopicPrefix == "" { + return errors.New("distributor.tenant-topic-tee.topic-prefix must be set") + } + + if _, err := ParseStrategy(cfg.Strategy); err != nil { + return fmt.Errorf("invalid strategy: %w", err) + } + + return nil +} + +// RegisterFlags adds the flags required to configure this flag set. +func (cfg *TenantTopicConfig) RegisterFlags(f *flag.FlagSet) { + f.BoolVar(&cfg.Enabled, "distributor.tenant-topic-tee.enabled", false, "Enable the tenant topic tee, which writes logs to Kafka topics based on tenant IDs instead of using multitenant topics/partitions.") + f.StringVar(&cfg.TopicPrefix, "distributor.tenant-topic-tee.topic-prefix", "loki.tenant", "Prefix to prepend to tenant IDs to form the final Kafka topic name") + cfg.MaxBufferedBytes = 100 << 20 // 100MB + f.Var(&cfg.MaxBufferedBytes, "distributor.tenant-topic-tee.max-buffered-bytes", "Maximum number of bytes that can be buffered before producing to Kafka") + cfg.MaxRecordSizeBytes = kafka.MaxProducerRecordDataBytesLimit + f.Var(&cfg.MaxRecordSizeBytes, "distributor.tenant-topic-tee.max-record-size-bytes", "Maximum size of a single Kafka record in bytes") + f.StringVar(&cfg.Strategy, "distributor.tenant-topic-tee.strategy", "simple", "Topic strategy to use. Valid values are 'simple' or 'automatic'") +} + +// PartitionResolver resolves the topic and partition for a given tenant and stream +type PartitionResolver interface { + // Resolve returns the topic and partition for a given tenant and stream + Resolve(ctx context.Context, tenant string, totalPartitions uint32, stream KeyedStream) (topic string, partition int32, err error) +} + +// SimplePartitionResolver is a basic implementation of PartitionResolver that +// uses a prefix for topics and hash-based partitioning +type SimplePartitionResolver struct { + topicPrefix string +} + +// NewSimplePartitionResolver creates a new SimplePartitionResolver +func NewSimplePartitionResolver(topicPrefix string) *SimplePartitionResolver { + return &SimplePartitionResolver{ + topicPrefix: topicPrefix, + } +} + +// Resolve implements PartitionResolver +func (r *SimplePartitionResolver) Resolve(_ context.Context, tenant string, totalPartitions uint32, stream KeyedStream) (string, int32, error) { + topic := fmt.Sprintf("%s.%s", r.topicPrefix, tenant) + partition := int32(stream.HashKey % totalPartitions) + return topic, partition, nil +} + +// ShardedPartitionResolver implements a partition resolution strategy that creates +// single-partition topics for each tenant and shard combination. This approach offers +// several advantages over traditional multi-partition topics: +// +// 1. Dynamic Scaling: +// - Topics are created in the form "<prefix>.<tenant>.<shard>" +// - Each topic has exactly one partition, with shards serving the same purpose +// as traditional partitions +// - Unlike traditional partitions which can only be increased but never decreased, +// this approach allows for both scaling up and down +// - When volume decreases, we can stop writing to higher-numbered shards +// - Old shards will be automatically cleaned up through normal retention policies +// +// 2. Consumer Group Flexibility: +// - Consumers can subscribe to all tenant data using regex pattern "<prefix>.*" +// - Individual tenants or tenant subsets can be consumed using more specific patterns +// - Each topic having a single partition simplifies consumer group rebalancing +// +// 3. Topic Management: +// - Topics are created on-demand when new tenant/shard combinations are encountered +// - A thread-safe cache (map[tenant]map[shard]struct{}) tracks existing topics +// - Read lock is used for lookups, write lock for cache updates +// - Topic creation is idempotent, handling "already exists" errors gracefully +// +// The resolver maintains an internal cache of known tenant/shard combinations to minimize +// admin API calls. When resolving a partition: +// 1. First checks the cache under a read lock +// 2. If not found, releases read lock and attempts to create the topic +// 3. Updates the cache under a write lock +// 4. Returns the topic name with partition 0 (since each topic has exactly one partition) +type ShardedPartitionResolver struct { + sync.RWMutex + admin *kadm.Client + topicPrefix string + + sflight singleflight.Group // for topic creation + // tenantShards maps tenant IDs to their active shards + // map[tenant]map[shard]struct{} + tenantShards map[string]map[int32]struct{} +} + +// NewShardedPartitionResolver creates a new ShardedPartitionResolver +func NewShardedPartitionResolver(kafkaClient *kgo.Client, topicPrefix string) *ShardedPartitionResolver { + return &ShardedPartitionResolver{ + admin: kadm.NewClient(kafkaClient), + topicPrefix: topicPrefix, + tenantShards: make(map[string]map[int32]struct{}), + } +} + +// Resolve implements PartitionResolver. It ensures a topic exists for the given tenant +// and shard before returning the topic name and partition. If the topic does not exist, +// it will be created with a single partition. +// NB(owen-d): We always use partition 0 since each topic has 1 partition +func (r *ShardedPartitionResolver) Resolve(ctx context.Context, tenant string, totalPartitions uint32, stream KeyedStream) (string, int32, error) { + // Use the hash key modulo total partitions as the shard number + shard := int32(stream.HashKey % totalPartitions) + + // Check cache under read lock + r.RLock() + shards, exists := r.tenantShards[tenant] + if exists { + _, shardExists := shards[shard] + if shardExists { + r.RUnlock() + return r.topicName(tenant, shard), 0, nil + } + } + r.RUnlock() + + // Create the shard if it doesn't exist + if err := r.createShard(ctx, tenant, shard); err != nil { + return "", 0, fmt.Errorf("failed to create shard: %w", err) + } + + return r.topicName(tenant, shard), 0, nil +} + +// createShard creates a new topic for the given tenant and shard. +// It handles the case where the topic already exists. +func (r *ShardedPartitionResolver) createShard(ctx context.Context, tenant string, shard int32) error { + topic := r.topicName(tenant, shard) + replicationFactor := 2 // TODO: expose RF + + _, err, _ := r.sflight.Do(topic, func() (interface{}, error) { + return r.admin.CreateTopic( + ctx, + 1, + int16(replicationFactor), + nil, + topic, + ) + }) + + // Topic creation errors are returned in the response + if err != nil && !errors.Is(err, kerr.TopicAlreadyExists) { + return fmt.Errorf("failed to create topic %s: %w", topic, err) + } + + // Update cache under write lock + r.Lock() + defer r.Unlock() + + shards, exists := r.tenantShards[tenant] + if !exists { + shards = make(map[int32]struct{}) + r.tenantShards[tenant] = shards + } + shards[shard] = struct{}{} + + return nil +} + +// topicName returns the topic name for a given tenant and shard +func (r *ShardedPartitionResolver) topicName(tenant string, shard int32) string { + return fmt.Sprintf("%s.%s.%d", r.topicPrefix, tenant, shard) +} + +// TenantTopicWriter implements the Tee interface by writing logs to Kafka topics +// based on tenant IDs. Each tenant's logs are written to a dedicated topic. +type TenantTopicWriter struct { + cfg TenantTopicConfig + producer *client.Producer + logger log.Logger + resolver PartitionResolver + limits IngestionRateLimits + + // Metrics + teeBatchSize prometheus.Histogram + teeQueueLatency prometheus.Histogram + teeErrors *prometheus.CounterVec +} + +// NewTenantTopicWriter creates a new TenantTopicWriter +func NewTenantTopicWriter( + cfg TenantTopicConfig, + kafkaClient *kgo.Client, + limits IngestionRateLimits, + reg prometheus.Registerer, + logger log.Logger, +) (*TenantTopicWriter, error) { + strategy, err := ParseStrategy(cfg.Strategy) + if err != nil { + return nil, fmt.Errorf("invalid strategy: %w", err) + } + + var resolver PartitionResolver + switch strategy { + case SimpleStrategy: + resolver = NewSimplePartitionResolver(cfg.TopicPrefix) + case AutomaticStrategy: + resolver = NewShardedPartitionResolver(kafkaClient, cfg.TopicPrefix) + default: + return nil, fmt.Errorf("unknown strategy %q", strategy.String()) + } + + t := &TenantTopicWriter{ + cfg: cfg, + logger: logger, + limits: limits, + producer: client.NewProducer( + kafkaClient, + int64(cfg.MaxBufferedBytes), + reg, + ), + resolver: resolver, + teeBatchSize: prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "loki_distributor_tenant_topic_tee_batch_size_bytes", + Help: "Size in bytes of batches sent to Kafka by the tenant topic tee", + Buckets: prometheus.ExponentialBucketsRange(1<<10, 100<<20, 10), + }), + teeQueueLatency: prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "loki_distributor_tenant_topic_tee_queue_duration_seconds", + Help: "Duration in seconds spent waiting in queue by the tenant topic tee", + Buckets: prometheus.DefBuckets, + }), + teeErrors: prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "loki_distributor_tenant_topic_tee_errors_total", + Help: "Total number of errors encountered by the tenant topic tee", + }, []string{"reason"}), + } + + if reg != nil { + reg.MustRegister(t.teeBatchSize, t.teeQueueLatency, t.teeErrors) + } + + return t, nil +} + +func (t *TenantTopicWriter) partitionsForRateLimit(bytesRateLimit float64) uint32 { + targetThroughputPerPartition := float64(10 << 20) // 10 MB + + target := uint32(math.Round(bytesRateLimit / targetThroughputPerPartition)) + + // Calculate partitions, ensuring at least 1 + return max(target, 1) +} + +// Duplicate implements the Tee interface +func (t *TenantTopicWriter) Duplicate(tenant string, streams []KeyedStream) { + if len(streams) == 0 { + return + } + + go t.write(tenant, streams) +} + +func (t *TenantTopicWriter) write(tenant string, streams []KeyedStream) { + totalPartitions := t.partitionsForRateLimit(t.limits.IngestionRateBytes(tenant)) + + // Convert streams to Kafka records + records := make([]*kgo.Record, 0, len(streams)) + for _, stream := range streams { + topic, partition, err := t.resolver.Resolve(context.Background(), tenant, totalPartitions, stream) + if err != nil { + level.Error(t.logger).Log( + "msg", "failed to resolve topic and partition", + "tenant", tenant, + "err", err, + ) + t.teeErrors.WithLabelValues("resolve_error").Inc() + continue + } + + streamRecords, err := kafka.EncodeWithTopic(topic, partition, tenant, stream.Stream, int(t.cfg.MaxRecordSizeBytes)) + if err != nil { + level.Error(t.logger).Log( + "msg", "failed to encode stream", + "tenant", tenant, + "err", err, + ) + t.teeErrors.WithLabelValues("encode_error").Inc() + continue + } + + records = append(records, streamRecords...) + } + + if len(records) == 0 { + return + } + + // Send records to Kafka + results := t.producer.ProduceSync(context.TODO(), records) + if results.FirstErr() != nil { + level.Error(t.logger).Log( + "msg", "failed to write records to kafka", + "tenant", tenant, + "err", results.FirstErr(), + ) + t.teeErrors.WithLabelValues("produce_error").Inc() + return + } + + // Update metrics + var batchSize int64 + for _, record := range records { + batchSize += int64(len(record.Value)) + } + t.teeBatchSize.Observe(float64(batchSize)) +} + +// Close stops the writer and releases resources +func (t *TenantTopicWriter) Close() error { + t.producer.Close() + return nil +} + +type IngestionRateLimits interface { + IngestionRateBytes(userID string) float64 +} diff --git a/pkg/kafka/config.go b/pkg/kafka/config.go index 607bc56e888ec..ed73add8681b9 100644 --- a/pkg/kafka/config.go +++ b/pkg/kafka/config.go @@ -18,11 +18,11 @@ const ( // ProducerBatchMaxBytes is the max allowed size of a batch of Kafka records. ProducerBatchMaxBytes = 16_000_000 - // maxProducerRecordDataBytesLimit is the max allowed size of a single record data. Given we have a limit + // MaxProducerRecordDataBytesLimit is the max allowed size of a single record data. Given we have a limit // on the max batch size (ProducerBatchMaxBytes), a Kafka record data can't be bigger than the batch size // minus some overhead required to serialise the batch and the record itself. We use 16KB as such overhead // in the worst case scenario, which is expected to be way above the actual one. - maxProducerRecordDataBytesLimit = ProducerBatchMaxBytes - 16384 + MaxProducerRecordDataBytesLimit = ProducerBatchMaxBytes - 16384 minProducerRecordDataBytesLimit = 1024 * 1024 ) @@ -30,7 +30,7 @@ var ( ErrMissingKafkaAddress = errors.New("the Kafka address has not been configured") ErrMissingKafkaTopic = errors.New("the Kafka topic has not been configured") ErrInconsistentSASLUsernameAndPassword = errors.New("both sasl username and password must be set") - ErrInvalidProducerMaxRecordSizeBytes = fmt.Errorf("the configured producer max record size bytes must be a value between %d and %d", minProducerRecordDataBytesLimit, maxProducerRecordDataBytesLimit) + ErrInvalidProducerMaxRecordSizeBytes = fmt.Errorf("the configured producer max record size bytes must be a value between %d and %d", minProducerRecordDataBytesLimit, MaxProducerRecordDataBytesLimit) ) // Config holds the generic config for the Kafka backend. @@ -80,7 +80,7 @@ func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { f.BoolVar(&cfg.AutoCreateTopicEnabled, prefix+".auto-create-topic-enabled", true, "Enable auto-creation of Kafka topic if it doesn't exist.") f.IntVar(&cfg.AutoCreateTopicDefaultPartitions, prefix+".auto-create-topic-default-partitions", 1000, "When auto-creation of Kafka topic is enabled and this value is positive, Kafka's num.partitions configuration option is set on Kafka brokers with this value when Loki component that uses Kafka starts. This configuration option specifies the default number of partitions that the Kafka broker uses for auto-created topics. Note that this is a Kafka-cluster wide setting, and applies to any auto-created topic. If the setting of num.partitions fails, Loki proceeds anyways, but auto-created topics could have an incorrect number of partitions.") - f.IntVar(&cfg.ProducerMaxRecordSizeBytes, prefix+".producer-max-record-size-bytes", maxProducerRecordDataBytesLimit, "The maximum size of a Kafka record data that should be generated by the producer. An incoming write request larger than this size is split into multiple Kafka records. We strongly recommend to not change this setting unless for testing purposes.") + f.IntVar(&cfg.ProducerMaxRecordSizeBytes, prefix+".producer-max-record-size-bytes", MaxProducerRecordDataBytesLimit, "The maximum size of a Kafka record data that should be generated by the producer. An incoming write request larger than this size is split into multiple Kafka records. We strongly recommend to not change this setting unless for testing purposes.") f.Int64Var(&cfg.ProducerMaxBufferedBytes, prefix+".producer-max-buffered-bytes", 1024*1024*1024, "The maximum size of (uncompressed) buffered and unacknowledged produced records sent to Kafka. The produce request fails once this limit is reached. This limit is per Kafka client. 0 to disable the limit.") consumerLagUsage := fmt.Sprintf("Set -%s to 0 to disable waiting for maximum consumer lag being honored at startup.", prefix+".max-consumer-lag-at-startup") @@ -94,7 +94,7 @@ func (cfg *Config) Validate() error { if cfg.Topic == "" { return ErrMissingKafkaTopic } - if cfg.ProducerMaxRecordSizeBytes < minProducerRecordDataBytesLimit || cfg.ProducerMaxRecordSizeBytes > maxProducerRecordDataBytesLimit { + if cfg.ProducerMaxRecordSizeBytes < minProducerRecordDataBytesLimit || cfg.ProducerMaxRecordSizeBytes > MaxProducerRecordDataBytesLimit { return ErrInvalidProducerMaxRecordSizeBytes } if (cfg.SASLUsername == "") != (cfg.SASLPassword.String() == "") { diff --git a/pkg/kafka/encoding.go b/pkg/kafka/encoding.go index 15479336de670..5ee885473fe89 100644 --- a/pkg/kafka/encoding.go +++ b/pkg/kafka/encoding.go @@ -41,11 +41,15 @@ var encoderPool = sync.Pool{ // - stream: The logproto.Stream to be encoded // - maxSize: The maximum size of each Kafka record func Encode(partitionID int32, tenantID string, stream logproto.Stream, maxSize int) ([]*kgo.Record, error) { + return EncodeWithTopic("", partitionID, tenantID, stream, maxSize) +} + +func EncodeWithTopic(topic string, partitionID int32, tenantID string, stream logproto.Stream, maxSize int) ([]*kgo.Record, error) { reqSize := stream.Size() // Fast path for small requests if reqSize <= maxSize { - rec, err := marshalWriteRequestToRecord(partitionID, tenantID, stream) + rec, err := marshalWriteRequestToRecord(topic, partitionID, tenantID, stream) if err != nil { return nil, err } @@ -79,7 +83,7 @@ func Encode(partitionID int32, tenantID string, stream logproto.Stream, maxSize if currentSize+entrySize > maxSize { // Current stream is full, create a record and start a new stream if len(batch.Entries) > 0 { - rec, err := marshalWriteRequestToRecord(partitionID, tenantID, *batch) + rec, err := marshalWriteRequestToRecord(topic, partitionID, tenantID, *batch) if err != nil { return nil, err } @@ -95,7 +99,7 @@ func Encode(partitionID int32, tenantID string, stream logproto.Stream, maxSize // Handle any remaining entries if len(batch.Entries) > 0 { - rec, err := marshalWriteRequestToRecord(partitionID, tenantID, *batch) + rec, err := marshalWriteRequestToRecord(topic, partitionID, tenantID, *batch) if err != nil { return nil, err } @@ -109,13 +113,15 @@ func Encode(partitionID int32, tenantID string, stream logproto.Stream, maxSize return records, nil } -func marshalWriteRequestToRecord(partitionID int32, tenantID string, stream logproto.Stream) (*kgo.Record, error) { +// topic can be empty in the case the client injects a default. +func marshalWriteRequestToRecord(topic string, partitionID int32, tenantID string, stream logproto.Stream) (*kgo.Record, error) { data, err := stream.Marshal() if err != nil { return nil, fmt.Errorf("failed to marshal stream: %w", err) } return &kgo.Record{ + Topic: topic, Key: []byte(tenantID), Value: data, Partition: partitionID,
feat
tenant topics (#15977)
673ede16a5f675684f9e6a53903335af5075a507
2024-10-23 16:22:01
Salva Corts
feat: New bloom planning using chunk size TSDB stats (#14547)
false
diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index 6ca10719d5771..728e61e5096e3 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -3765,7 +3765,7 @@ shard_streams: [bloom_creation_enabled: <boolean> | default = false] # Experimental. Bloom planning strategy to use in bloom creation. Can be one of: -# 'split_keyspace_by_factor' +# 'split_keyspace_by_factor', 'split_by_series_chunks_size' # CLI flag: -bloom-build.planning-strategy [bloom_planning_strategy: <string> | default = "split_keyspace_by_factor"] @@ -3775,6 +3775,10 @@ shard_streams: # CLI flag: -bloom-build.split-keyspace-by [bloom_split_series_keyspace_by: <int> | default = 256] +# Experimental. Target chunk size in bytes for bloom tasks. Default is 20GB. +# CLI flag: -bloom-build.split-target-series-chunk-size +[bloom_task_target_series_chunk_size: <int> | default = 20GB] + # Experimental. Compression algorithm for bloom block pages. # CLI flag: -bloom-build.block-encoding [bloom_block_encoding: <string> | default = "none"] diff --git a/integration/bloom_building_test.go b/integration/bloom_building_test.go index 2c4662eef4cb3..b5186b3b23ff0 100644 --- a/integration/bloom_building_test.go +++ b/integration/bloom_building_test.go @@ -96,6 +96,8 @@ func TestBloomBuilding(t *testing.T) { "-bloom-build.planner.interval=15s", "-bloom-build.planner.min-table-offset=0", // Disable table offset so we process today's data. "-bloom.cache-list-ops=0", // Disable cache list operations to avoid caching issues. + "-bloom-build.planning-strategy=split_by_series_chunks_size", + "-bloom-build.split-target-series-chunk-size=1KB", ) require.NoError(t, clu.Run()) diff --git a/pkg/bloombuild/planner/planner.go b/pkg/bloombuild/planner/planner.go index 18c43cfcfa121..33f0bf64c833b 100644 --- a/pkg/bloombuild/planner/planner.go +++ b/pkg/bloombuild/planner/planner.go @@ -281,8 +281,6 @@ func (p *Planner) runOne(ctx context.Context) error { continue } - level.Debug(logger).Log("msg", "computed tasks", "tasks", len(tasks), "existingMetas", len(existingMetas)) - var tenantTableEnqueuedTasks int resultsCh := make(chan *protos.TaskResult, len(tasks)) @@ -377,13 +375,13 @@ func (p *Planner) computeTasks( table config.DayTable, tenant string, ) ([]*protos.Task, []bloomshipper.Meta, error) { - logger := log.With(p.logger, "table", table.Addr(), "tenant", tenant) - strategy, err := strategies.NewStrategy(tenant, p.limits, p.logger) if err != nil { return nil, nil, fmt.Errorf("error creating strategy: %w", err) } + logger := log.With(p.logger, "table", table.Addr(), "tenant", tenant, "strategy", strategy.Name()) + // Fetch source metas to be used in both build and cleanup of out-of-date metas+blooms metas, err := p.bloomStore.FetchMetas( ctx, @@ -432,6 +430,7 @@ func (p *Planner) computeTasks( return nil, nil, fmt.Errorf("failed to plan tasks: %w", err) } + level.Debug(logger).Log("msg", "computed tasks", "tasks", len(tasks), "existingMetas", len(metas)) return tasks, metas, nil } diff --git a/pkg/bloombuild/planner/planner_test.go b/pkg/bloombuild/planner/planner_test.go index 545cb65df142b..6b1b1e0beba16 100644 --- a/pkg/bloombuild/planner/planner_test.go +++ b/pkg/bloombuild/planner/planner_test.go @@ -18,6 +18,7 @@ import ( "google.golang.org/grpc" "github.com/grafana/loki/v3/pkg/bloombuild/planner/plannertest" + "github.com/grafana/loki/v3/pkg/bloombuild/planner/strategies" "github.com/grafana/loki/v3/pkg/bloombuild/protos" "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -750,3 +751,11 @@ func (f *fakeLimits) BloomBuildMaxBuilders(_ string) int { func (f *fakeLimits) BloomTaskMaxRetries(_ string) int { return f.maxRetries } + +func (f *fakeLimits) BloomPlanningStrategy(_ string) string { + return strategies.SplitBySeriesChunkSizeStrategyName +} + +func (f *fakeLimits) BloomTaskTargetSeriesChunksSizeBytes(_ string) uint64 { + return 1 << 20 // 1MB +} diff --git a/pkg/bloombuild/planner/plannertest/utils.go b/pkg/bloombuild/planner/plannertest/utils.go index f0c8f0ec70362..706e0abdf00a7 100644 --- a/pkg/bloombuild/planner/plannertest/utils.go +++ b/pkg/bloombuild/planner/plannertest/utils.go @@ -88,8 +88,12 @@ func GenBlock(ref bloomshipper.BlockRef) (bloomshipper.Block, error) { } func GenSeries(bounds v1.FingerprintBounds) []*v1.Series { - series := make([]*v1.Series, 0, int(bounds.Max-bounds.Min+1)) - for i := bounds.Min; i <= bounds.Max; i++ { + return GenSeriesWithStep(bounds, 1) +} + +func GenSeriesWithStep(bounds v1.FingerprintBounds, step int) []*v1.Series { + series := make([]*v1.Series, 0, int(bounds.Max-bounds.Min+1)/step) + for i := bounds.Min; i <= bounds.Max; i += model.Fingerprint(step) { series = append(series, &v1.Series{ Fingerprint: i, Chunks: v1.ChunkRefs{ diff --git a/pkg/bloombuild/planner/strategies/chunksize.go b/pkg/bloombuild/planner/strategies/chunksize.go new file mode 100644 index 0000000000000..21f473908dd99 --- /dev/null +++ b/pkg/bloombuild/planner/strategies/chunksize.go @@ -0,0 +1,286 @@ +package strategies + +import ( + "context" + "fmt" + "math" + "sort" + + "github.com/dustin/go-humanize" + "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/labels" + + "github.com/grafana/loki/v3/pkg/bloombuild/protos" + iter "github.com/grafana/loki/v3/pkg/iter/v2" + v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" + "github.com/grafana/loki/v3/pkg/storage/config" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" +) + +type ChunkSizeStrategyLimits interface { + BloomTaskTargetSeriesChunksSizeBytes(tenantID string) uint64 +} + +type ChunkSizeStrategy struct { + limits ChunkSizeStrategyLimits + logger log.Logger +} + +func NewChunkSizeStrategy( + limits ChunkSizeStrategyLimits, + logger log.Logger, +) (*ChunkSizeStrategy, error) { + return &ChunkSizeStrategy{ + limits: limits, + logger: logger, + }, nil +} + +func (s *ChunkSizeStrategy) Name() string { + return SplitBySeriesChunkSizeStrategyName +} + +func (s *ChunkSizeStrategy) Plan( + ctx context.Context, + table config.DayTable, + tenant string, + tsdbs TSDBSet, + metas []bloomshipper.Meta, +) ([]*protos.Task, error) { + targetTaskSize := s.limits.BloomTaskTargetSeriesChunksSizeBytes(tenant) + + logger := log.With(s.logger, "table", table.Addr(), "tenant", tenant) + level.Debug(s.logger).Log("msg", "loading work for tenant", "target task size", humanize.Bytes(targetTaskSize)) + + // Determine which TSDBs have gaps and need to be processed. + tsdbsWithGaps, err := gapsBetweenTSDBsAndMetas(v1.NewBounds(0, math.MaxUint64), tsdbs, metas) + if err != nil { + level.Error(logger).Log("msg", "failed to find gaps", "err", err) + return nil, fmt.Errorf("failed to find gaps: %w", err) + } + + if len(tsdbsWithGaps) == 0 { + level.Debug(logger).Log("msg", "blooms exist for all tsdbs") + return nil, nil + } + + sizedIter, iterSize, err := s.sizedSeriesIter(ctx, tenant, tsdbsWithGaps, targetTaskSize) + if err != nil { + return nil, fmt.Errorf("failed to get sized series iter: %w", err) + } + + tasks := make([]*protos.Task, 0, iterSize) + for sizedIter.Next() { + series := sizedIter.At() + if series.Len() == 0 { + // This should never happen, but just in case. + level.Warn(logger).Log("msg", "got empty series batch", "tsdb", series.TSDB().Name()) + continue + } + + bounds := series.Bounds() + + blocks, err := getBlocksMatchingBounds(metas, bounds) + if err != nil { + return nil, fmt.Errorf("failed to get blocks matching bounds: %w", err) + } + + planGap := protos.Gap{ + Bounds: bounds, + Series: series.V1Series(), + Blocks: blocks, + } + + tasks = append(tasks, protos.NewTask(table, tenant, bounds, series.TSDB(), []protos.Gap{planGap})) + } + if err := sizedIter.Err(); err != nil { + return nil, fmt.Errorf("failed to iterate over sized series: %w", err) + } + + return tasks, nil +} + +func getBlocksMatchingBounds(metas []bloomshipper.Meta, bounds v1.FingerprintBounds) ([]bloomshipper.BlockRef, error) { + blocks := make([]bloomshipper.BlockRef, 0, 10) + + for _, meta := range metas { + if meta.Bounds.Intersection(bounds) == nil { + // this meta doesn't overlap the gap, skip + continue + } + + for _, block := range meta.Blocks { + if block.Bounds.Intersection(bounds) == nil { + // this block doesn't overlap the gap, skip + continue + } + // this block overlaps the gap, add it to the plan + // for this gap + blocks = append(blocks, block) + } + } + + // ensure we sort blocks so deduping iterator works as expected + sort.Slice(blocks, func(i, j int) bool { + return blocks[i].Bounds.Less(blocks[j].Bounds) + }) + + peekingBlocks := iter.NewPeekIter( + iter.NewSliceIter( + blocks, + ), + ) + + // dedupe blocks which could be in multiple metas + itr := iter.NewDedupingIter( + func(a, b bloomshipper.BlockRef) bool { + return a == b + }, + iter.Identity[bloomshipper.BlockRef], + func(a, _ bloomshipper.BlockRef) bloomshipper.BlockRef { + return a + }, + peekingBlocks, + ) + + deduped, err := iter.Collect(itr) + if err != nil { + return nil, fmt.Errorf("failed to dedupe blocks: %w", err) + } + + return deduped, nil +} + +type seriesWithChunks struct { + tsdb tsdb.SingleTenantTSDBIdentifier + fp model.Fingerprint + chunks []index.ChunkMeta +} + +type seriesBatch struct { + series []seriesWithChunks + size uint64 +} + +func newSeriesBatch() seriesBatch { + return seriesBatch{ + series: make([]seriesWithChunks, 0, 100), + } +} + +func (b *seriesBatch) Bounds() v1.FingerprintBounds { + if len(b.series) == 0 { + return v1.NewBounds(0, 0) + } + + // We assume that the series are sorted by fingerprint. + // This is guaranteed since series are iterated in order by the TSDB. + return v1.NewBounds(b.series[0].fp, b.series[len(b.series)-1].fp) +} + +func (b *seriesBatch) V1Series() []*v1.Series { + series := make([]*v1.Series, 0, len(b.series)) + for _, s := range b.series { + res := &v1.Series{ + Fingerprint: s.fp, + Chunks: make(v1.ChunkRefs, 0, len(s.chunks)), + } + for _, chk := range s.chunks { + res.Chunks = append(res.Chunks, v1.ChunkRef{ + From: model.Time(chk.MinTime), + Through: model.Time(chk.MaxTime), + Checksum: chk.Checksum, + }) + } + + series = append(series, res) + } + + return series +} + +func (b *seriesBatch) Append(s seriesWithChunks, size uint64) { + b.series = append(b.series, s) + b.size += size +} + +func (b *seriesBatch) Len() int { + return len(b.series) +} + +func (b *seriesBatch) Size() uint64 { + return b.size +} + +func (b *seriesBatch) TSDB() tsdb.SingleTenantTSDBIdentifier { + if len(b.series) == 0 { + return tsdb.SingleTenantTSDBIdentifier{} + } + return b.series[0].tsdb +} + +func (s *ChunkSizeStrategy) sizedSeriesIter( + ctx context.Context, + tenant string, + tsdbsWithGaps []tsdbGaps, + targetTaskSizeBytes uint64, +) (iter.Iterator[seriesBatch], int, error) { + batches := make([]seriesBatch, 0, 100) + currentBatch := newSeriesBatch() + + for _, idx := range tsdbsWithGaps { + for _, gap := range idx.gaps { + if err := idx.tsdb.ForSeries( + ctx, + tenant, + gap, + 0, math.MaxInt64, + func(_ labels.Labels, fp model.Fingerprint, chks []index.ChunkMeta) (stop bool) { + select { + case <-ctx.Done(): + return true + default: + var seriesSize uint64 + for _, chk := range chks { + seriesSize += uint64(chk.KB * 1024) + } + + // Cut a new batch IF the current batch is not empty (so we add at least one series to the batch) + // AND Adding this series to the batch would exceed the target task size. + if currentBatch.Len() > 0 && currentBatch.Size()+seriesSize > targetTaskSizeBytes { + batches = append(batches, currentBatch) + currentBatch = newSeriesBatch() + } + + currentBatch.Append(seriesWithChunks{ + tsdb: idx.tsdbIdentifier, + fp: fp, + chunks: chks, + }, seriesSize) + return false + } + }, + labels.MustNewMatcher(labels.MatchEqual, "", ""), + ); err != nil { + return nil, 0, err + } + + // Add the last batch for this TSDB if it's not empty. + if currentBatch.Len() > 0 { + batches = append(batches, currentBatch) + currentBatch = newSeriesBatch() + } + } + } + + select { + case <-ctx.Done(): + return iter.NewEmptyIter[seriesBatch](), 0, ctx.Err() + default: + return iter.NewCancelableIter[seriesBatch](ctx, iter.NewSliceIter[seriesBatch](batches)), len(batches), nil + } +} diff --git a/pkg/bloombuild/planner/strategies/chunksize_test.go b/pkg/bloombuild/planner/strategies/chunksize_test.go new file mode 100644 index 0000000000000..951d033e5c100 --- /dev/null +++ b/pkg/bloombuild/planner/strategies/chunksize_test.go @@ -0,0 +1,248 @@ +package strategies + +import ( + "context" + "testing" + + "github.com/go-kit/log" + "github.com/stretchr/testify/require" + + "github.com/grafana/loki/v3/pkg/bloombuild/planner/plannertest" + "github.com/grafana/loki/v3/pkg/bloombuild/protos" + v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" +) + +func taskForGap(tsdb tsdb.SingleTenantTSDBIdentifier, bounds v1.FingerprintBounds, blocks []bloomshipper.BlockRef) *protos.Task { + return protos.NewTask(plannertest.TestTable, "fake", bounds, tsdb, []protos.Gap{ + { + Bounds: bounds, + Series: plannertest.GenSeriesWithStep(bounds, 10), + Blocks: blocks, + }, + }) +} + +func Test_ChunkSizeStrategy_Plan(t *testing.T) { + for _, tc := range []struct { + name string + limits ChunkSizeStrategyLimits + originalMetas []bloomshipper.Meta + tsdbs TSDBSet + expectedTasks []*protos.Task + }{ + { + name: "no previous blocks and metas", + limits: fakeChunkSizeLimits{TargetSize: 200 * 1 << 10}, // 2 series (100KB each) per task + + // Each series will have 1 chunk of 100KB each + tsdbs: TSDBSet{ + plannertest.TsdbID(0): newFakeForSeries(plannertest.GenSeriesWithStep(v1.NewBounds(0, 100), 10)), // 10 series + }, + + // We expect 5 tasks, each with 2 series each + expectedTasks: []*protos.Task{ + taskForGap(plannertest.TsdbID(0), v1.NewBounds(0, 10), nil), + taskForGap(plannertest.TsdbID(0), v1.NewBounds(20, 30), nil), + taskForGap(plannertest.TsdbID(0), v1.NewBounds(40, 50), nil), + taskForGap(plannertest.TsdbID(0), v1.NewBounds(60, 70), nil), + taskForGap(plannertest.TsdbID(0), v1.NewBounds(80, 90), nil), + taskForGap(plannertest.TsdbID(0), v1.NewBounds(100, 100), nil), + }, + }, + { + name: "previous metas with no gaps", + limits: fakeChunkSizeLimits{TargetSize: 200 * 1 << 10}, + + // Original metas cover the entire range + // One meta for each 2 series w/ 1 block per series + originalMetas: []bloomshipper.Meta{ + plannertest.GenMeta(0, 10, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + }), + plannertest.GenMeta(20, 30, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(20, 20), + plannertest.GenBlockRef(30, 30), + }), + plannertest.GenMeta(40, 50, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(40, 40), + plannertest.GenBlockRef(50, 50), + }), + plannertest.GenMeta(60, 70, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(60, 60), + plannertest.GenBlockRef(70, 70), + }), + plannertest.GenMeta(80, 90, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(80, 80), + plannertest.GenBlockRef(90, 90), + }), + plannertest.GenMeta(100, 100, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(100, 100), + }), + }, + + tsdbs: TSDBSet{ + plannertest.TsdbID(0): newFakeForSeries(plannertest.GenSeriesWithStep(v1.NewBounds(0, 100), 10)), // 10 series + }, + + // We expect no tasks + expectedTasks: []*protos.Task{}, + }, + { + name: "Original metas do not cover the entire range", + limits: fakeChunkSizeLimits{TargetSize: 200 * 1 << 10}, + + // Original metas cover only part of the range + // Original metas cover the entire range + // One meta for each 2 series w/ 1 block per series + originalMetas: []bloomshipper.Meta{ + plannertest.GenMeta(0, 10, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + }), + // Missing meta for 20-30 + plannertest.GenMeta(40, 50, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(40, 40), + plannertest.GenBlockRef(50, 50), + }), + plannertest.GenMeta(60, 70, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(60, 60), + plannertest.GenBlockRef(70, 70), + }), + plannertest.GenMeta(80, 90, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(80, 80), + plannertest.GenBlockRef(90, 90), + }), + plannertest.GenMeta(100, 100, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(100, 100), + }), + }, + + tsdbs: TSDBSet{ + plannertest.TsdbID(0): newFakeForSeries(plannertest.GenSeriesWithStep(v1.NewBounds(0, 100), 10)), // 10 series + }, + + // We expect 1 tasks for the missing series + expectedTasks: []*protos.Task{ + taskForGap(plannertest.TsdbID(0), v1.NewBounds(20, 30), nil), + }, + }, + { + name: "All metas are outdated", + limits: fakeChunkSizeLimits{TargetSize: 200 * 1 << 10}, + + originalMetas: []bloomshipper.Meta{ + plannertest.GenMeta(0, 100, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + plannertest.GenBlockRef(20, 20), + plannertest.GenBlockRef(30, 30), + plannertest.GenBlockRef(40, 40), + plannertest.GenBlockRef(50, 50), + plannertest.GenBlockRef(60, 60), + plannertest.GenBlockRef(70, 70), + plannertest.GenBlockRef(80, 80), + plannertest.GenBlockRef(90, 90), + plannertest.GenBlockRef(100, 100), + }), + }, + + tsdbs: TSDBSet{ + plannertest.TsdbID(1): newFakeForSeries(plannertest.GenSeriesWithStep(v1.NewBounds(0, 100), 10)), // 10 series + }, + + // We expect 5 tasks, each with 2 series each + expectedTasks: []*protos.Task{ + taskForGap(plannertest.TsdbID(1), v1.NewBounds(0, 10), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(20, 30), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(20, 20), + plannertest.GenBlockRef(30, 30), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(40, 50), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(40, 40), + plannertest.GenBlockRef(50, 50), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(60, 70), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(60, 60), + plannertest.GenBlockRef(70, 70), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(80, 90), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(80, 80), + plannertest.GenBlockRef(90, 90), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(100, 100), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(100, 100), + }), + }, + }, + { + name: "Some metas are outdated", + limits: fakeChunkSizeLimits{TargetSize: 200 * 1 << 10}, + + originalMetas: []bloomshipper.Meta{ + // Outdated meta + plannertest.GenMeta(0, 49, []int{0}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + plannertest.GenBlockRef(20, 20), + plannertest.GenBlockRef(30, 30), + plannertest.GenBlockRef(40, 40), + }), + // Updated meta + plannertest.GenMeta(50, 100, []int{1}, []bloomshipper.BlockRef{ + plannertest.GenBlockRef(50, 50), + plannertest.GenBlockRef(60, 60), + plannertest.GenBlockRef(70, 70), + plannertest.GenBlockRef(80, 80), + plannertest.GenBlockRef(90, 90), + plannertest.GenBlockRef(100, 100), + }), + }, + + tsdbs: TSDBSet{ + plannertest.TsdbID(1): newFakeForSeries(plannertest.GenSeriesWithStep(v1.NewBounds(0, 100), 10)), // 10 series + }, + + // We expect 5 tasks, each with 2 series each + expectedTasks: []*protos.Task{ + taskForGap(plannertest.TsdbID(1), v1.NewBounds(0, 10), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(0, 0), + plannertest.GenBlockRef(10, 10), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(20, 30), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(20, 20), + plannertest.GenBlockRef(30, 30), + }), + taskForGap(plannertest.TsdbID(1), v1.NewBounds(40, 40), []bloomshipper.BlockRef{ + plannertest.GenBlockRef(40, 40), + }), + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + logger := log.NewNopLogger() + //logger := log.NewLogfmtLogger(os.Stdout) + + strategy, err := NewChunkSizeStrategy(tc.limits, logger) + require.NoError(t, err) + + actual, err := strategy.Plan(context.Background(), plannertest.TestTable, "fake", tc.tsdbs, tc.originalMetas) + require.NoError(t, err) + + require.ElementsMatch(t, tc.expectedTasks, actual) + }) + } +} + +type fakeChunkSizeLimits struct { + TargetSize uint64 +} + +func (f fakeChunkSizeLimits) BloomTaskTargetSeriesChunksSizeBytes(_ string) uint64 { + return f.TargetSize +} diff --git a/pkg/bloombuild/planner/strategies/factory.go b/pkg/bloombuild/planner/strategies/factory.go index 578f74f855d35..f58f91e51708d 100644 --- a/pkg/bloombuild/planner/strategies/factory.go +++ b/pkg/bloombuild/planner/strategies/factory.go @@ -14,17 +14,20 @@ import ( ) const ( - SplitKeyspaceStrategyName = "split_keyspace_by_factor" + SplitKeyspaceStrategyName = "split_keyspace_by_factor" + SplitBySeriesChunkSizeStrategyName = "split_by_series_chunks_size" ) type Limits interface { BloomPlanningStrategy(tenantID string) string - BloomSplitSeriesKeyspaceBy(tenantID string) int + SplitKeyspaceStrategyLimits + ChunkSizeStrategyLimits } type TSDBSet = map[tsdb.SingleTenantTSDBIdentifier]common.ClosableForSeries type PlanningStrategy interface { + Name() string // Plan returns a set of tasks for a given tenant-table tuple and TSDBs. Plan(ctx context.Context, table config.DayTable, tenant string, tsdbs TSDBSet, metas []bloomshipper.Meta) ([]*protos.Task, error) } @@ -39,6 +42,8 @@ func NewStrategy( switch strategy { case SplitKeyspaceStrategyName: return NewSplitKeyspaceStrategy(limits, logger) + case SplitBySeriesChunkSizeStrategyName: + return NewChunkSizeStrategy(limits, logger) default: return nil, fmt.Errorf("unknown bloom planning strategy (%s)", strategy) } diff --git a/pkg/bloombuild/planner/strategies/splitkeyspace.go b/pkg/bloombuild/planner/strategies/splitkeyspace.go index 6aa572bd3af40..2e799d1ed4903 100644 --- a/pkg/bloombuild/planner/strategies/splitkeyspace.go +++ b/pkg/bloombuild/planner/strategies/splitkeyspace.go @@ -3,7 +3,6 @@ package strategies import ( "context" "fmt" - "sort" "github.com/go-kit/log" "github.com/go-kit/log/level" @@ -17,13 +16,17 @@ import ( "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" ) +type SplitKeyspaceStrategyLimits interface { + BloomSplitSeriesKeyspaceBy(tenantID string) int +} + type SplitKeyspaceStrategy struct { - limits Limits + limits SplitKeyspaceStrategyLimits logger log.Logger } func NewSplitKeyspaceStrategy( - limits Limits, + limits SplitKeyspaceStrategyLimits, logger log.Logger, ) (*SplitKeyspaceStrategy, error) { return &SplitKeyspaceStrategy{ @@ -32,6 +35,10 @@ func NewSplitKeyspaceStrategy( }, nil } +func (s *SplitKeyspaceStrategy) Name() string { + return SplitKeyspaceStrategyName +} + func (s *SplitKeyspaceStrategy) Plan( ctx context.Context, table config.DayTable, @@ -185,50 +192,10 @@ func blockPlansForGaps( return nil, fmt.Errorf("failed to collect series: %w", err) } - for _, meta := range metas { - if meta.Bounds.Intersection(gap) == nil { - // this meta doesn't overlap the gap, skip - continue - } - - for _, block := range meta.Blocks { - if block.Bounds.Intersection(gap) == nil { - // this block doesn't overlap the gap, skip - continue - } - // this block overlaps the gap, add it to the plan - // for this gap - planGap.Blocks = append(planGap.Blocks, block) - } - } - - // ensure we sort blocks so deduping iterator works as expected - sort.Slice(planGap.Blocks, func(i, j int) bool { - return planGap.Blocks[i].Bounds.Less(planGap.Blocks[j].Bounds) - }) - - peekingBlocks := iter.NewPeekIter( - iter.NewSliceIter( - planGap.Blocks, - ), - ) - // dedupe blocks which could be in multiple metas - itr := iter.NewDedupingIter( - func(a, b bloomshipper.BlockRef) bool { - return a == b - }, - iter.Identity[bloomshipper.BlockRef], - func(a, _ bloomshipper.BlockRef) bloomshipper.BlockRef { - return a - }, - peekingBlocks, - ) - - deduped, err := iter.Collect(itr) + planGap.Blocks, err = getBlocksMatchingBounds(metas, gap) if err != nil { - return nil, fmt.Errorf("failed to dedupe blocks: %w", err) + return nil, fmt.Errorf("failed to get blocks matching bounds: %w", err) } - planGap.Blocks = deduped plan.gaps = append(plan.gaps, planGap) } diff --git a/pkg/bloombuild/planner/strategies/splitkeyspace_test.go b/pkg/bloombuild/planner/strategies/splitkeyspace_test.go index 7f5a49a54cc2d..18480d74c98fc 100644 --- a/pkg/bloombuild/planner/strategies/splitkeyspace_test.go +++ b/pkg/bloombuild/planner/strategies/splitkeyspace_test.go @@ -348,6 +348,7 @@ func (f fakeForSeries) ForSeries(_ context.Context, _ string, ff index.Fingerpri MinTime: int64(c.From), MaxTime: int64(c.Through), Checksum: c.Checksum, + KB: 100, }) } diff --git a/pkg/validation/limits.go b/pkg/validation/limits.go index 96a1af0693a28..7129db9a53b63 100644 --- a/pkg/validation/limits.go +++ b/pkg/validation/limits.go @@ -61,6 +61,7 @@ const ( defaultMaxStructuredMetadataCount = 128 defaultBloomBuildMaxBlockSize = "200MB" defaultBloomBuildMaxBloomSize = "128MB" + defaultBloomTaskTargetChunkSize = "20GB" defaultBlockedIngestionStatusCode = 260 // 260 is a custom status code to indicate blocked ingestion ) @@ -207,10 +208,11 @@ type Limits struct { BloomBuildTaskMaxRetries int `yaml:"bloom_build_task_max_retries" json:"bloom_build_task_max_retries" category:"experimental"` BloomBuilderResponseTimeout time.Duration `yaml:"bloom_build_builder_response_timeout" json:"bloom_build_builder_response_timeout" category:"experimental"` - BloomCreationEnabled bool `yaml:"bloom_creation_enabled" json:"bloom_creation_enabled" category:"experimental"` - BloomPlanningStrategy string `yaml:"bloom_planning_strategy" json:"bloom_planning_strategy" category:"experimental"` - BloomSplitSeriesKeyspaceBy int `yaml:"bloom_split_series_keyspace_by" json:"bloom_split_series_keyspace_by" category:"experimental"` - BloomBlockEncoding string `yaml:"bloom_block_encoding" json:"bloom_block_encoding" category:"experimental"` + BloomCreationEnabled bool `yaml:"bloom_creation_enabled" json:"bloom_creation_enabled" category:"experimental"` + BloomPlanningStrategy string `yaml:"bloom_planning_strategy" json:"bloom_planning_strategy" category:"experimental"` + BloomSplitSeriesKeyspaceBy int `yaml:"bloom_split_series_keyspace_by" json:"bloom_split_series_keyspace_by" category:"experimental"` + BloomTaskTargetSeriesChunkSize flagext.ByteSize `yaml:"bloom_task_target_series_chunk_size" json:"bloom_task_target_series_chunk_size" category:"experimental"` + BloomBlockEncoding string `yaml:"bloom_block_encoding" json:"bloom_block_encoding" category:"experimental"` BloomMaxBlockSize flagext.ByteSize `yaml:"bloom_max_block_size" json:"bloom_max_block_size" category:"experimental"` BloomMaxBloomSize flagext.ByteSize `yaml:"bloom_max_bloom_size" json:"bloom_max_bloom_size" category:"experimental"` @@ -394,8 +396,10 @@ func (l *Limits) RegisterFlags(f *flag.FlagSet) { ) f.BoolVar(&l.BloomCreationEnabled, "bloom-build.enable", false, "Experimental. Whether to create blooms for the tenant.") - f.StringVar(&l.BloomPlanningStrategy, "bloom-build.planning-strategy", "split_keyspace_by_factor", "Experimental. Bloom planning strategy to use in bloom creation. Can be one of: 'split_keyspace_by_factor'") + f.StringVar(&l.BloomPlanningStrategy, "bloom-build.planning-strategy", "split_keyspace_by_factor", "Experimental. Bloom planning strategy to use in bloom creation. Can be one of: 'split_keyspace_by_factor', 'split_by_series_chunks_size'") f.IntVar(&l.BloomSplitSeriesKeyspaceBy, "bloom-build.split-keyspace-by", 256, "Experimental. Only if `bloom-build.planning-strategy` is 'split'. Number of splits to create for the series keyspace when building blooms. The series keyspace is split into this many parts to parallelize bloom creation.") + _ = l.BloomTaskTargetSeriesChunkSize.Set(defaultBloomTaskTargetChunkSize) + f.Var(&l.BloomTaskTargetSeriesChunkSize, "bloom-build.split-target-series-chunk-size", fmt.Sprintf("Experimental. Target chunk size in bytes for bloom tasks. Default is %s.", defaultBloomTaskTargetChunkSize)) f.IntVar(&l.BloomBuildMaxBuilders, "bloom-build.max-builders", 0, "Experimental. Maximum number of builders to use when building blooms. 0 allows unlimited builders.") f.DurationVar(&l.BloomBuilderResponseTimeout, "bloom-build.builder-response-timeout", 0, "Experimental. Timeout for a builder to finish a task. If a builder does not respond within this time, it is considered failed and the task will be requeued. 0 disables the timeout.") f.IntVar(&l.BloomBuildTaskMaxRetries, "bloom-build.task-max-retries", 3, "Experimental. Maximum number of retries for a failed task. If a task fails more than this number of times, it is considered failed and will not be retried. A value of 0 disables this limit.") @@ -1015,6 +1019,10 @@ func (o *Overrides) BloomSplitSeriesKeyspaceBy(userID string) int { return o.getOverridesForUser(userID).BloomSplitSeriesKeyspaceBy } +func (o *Overrides) BloomTaskTargetSeriesChunksSizeBytes(userID string) uint64 { + return uint64(o.getOverridesForUser(userID).BloomTaskTargetSeriesChunkSize) +} + func (o *Overrides) BloomBuildMaxBuilders(userID string) int { return o.getOverridesForUser(userID).BloomBuildMaxBuilders }
feat
New bloom planning using chunk size TSDB stats (#14547)
2bbf4b21c3ce7b92bfd7044ac49388d76441c73a
2021-01-28 02:39:16
Thibault Deutsch
logcli: support --include-label when not using --tail (#3229)
false
diff --git a/pkg/logcli/query/query.go b/pkg/logcli/query/query.go index e38348182f236..43added3f72ab 100644 --- a/pkg/logcli/query/query.go +++ b/pkg/logcli/query/query.go @@ -274,6 +274,10 @@ func (q *Query) printStream(streams loghttp.Streams, out output.LogOutput, lastE log.Println("Ignoring labels key:", color.RedString(strings.Join(q.IgnoreLabelsKey, ","))) } + if len(q.ShowLabelsKey) > 0 && !q.Quiet { + log.Println("Print only labels key:", color.RedString(strings.Join(q.ShowLabelsKey, ","))) + } + // Remove ignored and common labels from the cached labels and // calculate the max labels length maxLabelsLen := q.FixedLabelsLen @@ -281,6 +285,10 @@ func (q *Query) printStream(streams loghttp.Streams, out output.LogOutput, lastE // Remove common labels ls := subtract(s.Labels, common) + if len(q.ShowLabelsKey) > 0 { + ls = matchLabels(true, ls, q.ShowLabelsKey) + } + // Remove ignored labels if len(q.IgnoreLabelsKey) > 0 { ls = matchLabels(false, ls, q.IgnoreLabelsKey)
logcli
support --include-label when not using --tail (#3229)
dcec284dbc2dcdd5fddd8864a432b8a14dc6dbc2
2025-02-06 02:31:42
Jack Baldry
ci: Remove "Add to docs project" workflow (#14417)
false
diff --git a/.github/workflows/add-to-docs-project.yml b/.github/workflows/add-to-docs-project.yml deleted file mode 100644 index 56f57ed9badf4..0000000000000 --- a/.github/workflows/add-to-docs-project.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Add to docs project -on: - issues: - types: [labeled] - pull_request: - types: [labeled] -jobs: - main: - if: ${{ github.event.label.name == 'type/docs' }} - permissions: - contents: read - id-token: write - runs-on: ubuntu-latest - steps: - - uses: grafana/writers-toolkit/add-to-docs-project@add-to-docs-project/v1
ci
Remove "Add to docs project" workflow (#14417)
bf54cf14969a8ceb8fc1a90f0b4c6093c59317c5
2024-10-21 17:47:58
Robert Fratto
chore(bloom): remove unused code from blooms (#14539)
false
diff --git a/pkg/bloombuild/builder/batch.go b/pkg/bloombuild/builder/batch.go index d86111d2924a7..cb39a6df831f8 100644 --- a/pkg/bloombuild/builder/batch.go +++ b/pkg/bloombuild/builder/batch.go @@ -248,7 +248,7 @@ func (i *blockLoadingIter) loadNext() bool { blockRefs := i.overlapping.At() loader := newBatchedBlockLoader(i.ctx, i.fetcher, blockRefs, i.batchSize) - filtered := iter.NewFilterIter[*bloomshipper.CloseableBlockQuerier](loader, i.filter) + filtered := iter.NewFilterIter(loader, i.filter) iters := make([]iter.PeekIterator[*v1.SeriesWithBlooms], 0, len(blockRefs)) for filtered.Next() { @@ -279,7 +279,7 @@ func (i *blockLoadingIter) loadNext() bool { // two overlapping blocks can conceivably have the same series, so we need to dedupe, // preferring the one with the most chunks already indexed since we'll have // to add fewer chunks to the bloom - i.iter = iter.NewDedupingIter[*v1.SeriesWithBlooms, *v1.SeriesWithBlooms]( + i.iter = iter.NewDedupingIter( func(a, b *v1.SeriesWithBlooms) bool { return a.Series.Fingerprint == b.Series.Fingerprint }, @@ -346,7 +346,7 @@ func overlappingBlocksIter(inputs []bloomshipper.BlockRef) iter.Iterator[[]bloom // can we assume sorted blocks? peekIter := iter.NewPeekIter(iter.NewSliceIter(inputs)) - return iter.NewDedupingIter[bloomshipper.BlockRef, []bloomshipper.BlockRef]( + return iter.NewDedupingIter( func(a bloomshipper.BlockRef, b []bloomshipper.BlockRef) bool { minFp := b[0].Bounds.Min maxFp := slices.MaxFunc(b, func(a, b bloomshipper.BlockRef) int { return int(a.Bounds.Max - b.Bounds.Max) }).Bounds.Max diff --git a/pkg/bloombuild/builder/batch_test.go b/pkg/bloombuild/builder/batch_test.go index 608ab0807c9ec..cedba1480e2f6 100644 --- a/pkg/bloombuild/builder/batch_test.go +++ b/pkg/bloombuild/builder/batch_test.go @@ -120,7 +120,7 @@ func TestBatchedLoader(t *testing.T) { ) } - loader := newBatchedLoader[int, int, int]( + loader := newBatchedLoader( tc.ctx, fetchers, tc.inputs, @@ -128,7 +128,7 @@ func TestBatchedLoader(t *testing.T) { tc.batchSize, ) - got, err := v2.Collect[int](loader) + got, err := v2.Collect(loader) if tc.err { require.Error(t, err) return diff --git a/pkg/bloombuild/builder/builder.go b/pkg/bloombuild/builder/builder.go index 389749d7dc92f..364d4ed5b0820 100644 --- a/pkg/bloombuild/builder/builder.go +++ b/pkg/bloombuild/builder/builder.go @@ -46,7 +46,6 @@ type Builder struct { metrics *Metrics logger log.Logger - tsdbStore common.TSDBStore bloomStore bloomshipper.Store chunkLoader ChunkLoader @@ -74,18 +73,12 @@ func New( builderID := uuid.NewString() logger = log.With(logger, "builder_id", builderID) - tsdbStore, err := common.NewTSDBStores("bloom-builder", schemaCfg, storeCfg, storageMetrics, logger) - if err != nil { - return nil, fmt.Errorf("error creating TSDB store: %w", err) - } - metrics := NewMetrics(r) b := &Builder{ ID: builderID, cfg: cfg, limits: limits, metrics: metrics, - tsdbStore: tsdbStore, bloomStore: bloomStore, chunkLoader: NewStoreChunkLoader(fetcherProvider, metrics), logger: logger, @@ -386,7 +379,7 @@ func (b *Builder) processTask( // Blocks are built consuming the series iterator. For observability, we wrap the series iterator // with a counter iterator to count the number of times Next() is called on it. // This is used to observe the number of series that are being processed. - seriesItrWithCounter := iter.NewCounterIter[*v1.Series](seriesItr) + seriesItrWithCounter := iter.NewCounterIter(seriesItr) gen := NewSimpleBloomGenerator( tenant, @@ -416,7 +409,7 @@ func (b *Builder) processTask( return nil, fmt.Errorf("failed to build block: %w", err) } - logger := log.With(logger, "block", built.BlockRef.String()) + logger := log.With(logger, "block", built.String()) if err := client.PutBlock( ctx, @@ -461,7 +454,7 @@ func (b *Builder) processTask( } meta.MetaRef = ref - logger = log.With(logger, "meta", meta.MetaRef.String()) + logger = log.With(logger, "meta", meta.String()) if err := client.PutMeta(ctx, meta); err != nil { level.Error(logger).Log("msg", "failed to write meta", "err", err) @@ -490,7 +483,7 @@ func (b *Builder) loadWorkForGap( table config.DayTable, gap protos.Gap, ) (iter.Iterator[*v1.Series], iter.CloseResetIterator[*v1.SeriesWithBlooms], error) { - seriesItr := iter.NewCancelableIter[*v1.Series](ctx, iter.NewSliceIter[*v1.Series](gap.Series)) + seriesItr := iter.NewCancelableIter(ctx, iter.NewSliceIter(gap.Series)) // load a blocks iterator for the gap fetcher, err := b.bloomStore.Fetcher(table.ModelTime()) diff --git a/pkg/bloombuild/builder/spec.go b/pkg/bloombuild/builder/spec.go index 180c2fc32cb00..781a0ca04872e 100644 --- a/pkg/bloombuild/builder/spec.go +++ b/pkg/bloombuild/builder/spec.go @@ -3,7 +3,6 @@ package builder import ( "context" "fmt" - "io" "github.com/go-kit/log" "github.com/go-kit/log/level" @@ -17,29 +16,8 @@ import ( "github.com/grafana/loki/v3/pkg/storage/chunk/fetcher" "github.com/grafana/loki/v3/pkg/storage/stores" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" - "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" ) -// inclusive range -type Keyspace struct { - min, max model.Fingerprint -} - -func (k Keyspace) Cmp(other Keyspace) v1.BoundsCheck { - if other.max < k.min { - return v1.Before - } else if other.min > k.max { - return v1.After - } - return v1.Overlap -} - -// Store is likely bound within. This allows specifying impls like ShardedStore<Store> -// to only request the shard-range needed from the existing store. -type BloomGenerator interface { - Generate(ctx context.Context) (skippedBlocks []v1.BlockMetadata, toClose []io.Closer, results iter.Iterator[*v1.Block], err error) -} - // Simple implementation of a BloomGenerator. type SimpleBloomGenerator struct { userID string @@ -247,12 +225,6 @@ func (b *LazyBlockBuilderIterator) Err() error { return b.err } -// IndexLoader loads an index. This helps us do things like -// load TSDBs for a specific period excluding multitenant (pre-compacted) indices -type indexLoader interface { - Index() (tsdb.Index, error) -} - // ChunkItersByFingerprint models the chunks belonging to a fingerprint type ChunkItersByFingerprint struct { fp model.Fingerprint diff --git a/pkg/bloombuild/builder/spec_test.go b/pkg/bloombuild/builder/spec_test.go index 23afa58754743..be14c91db36a1 100644 --- a/pkg/bloombuild/builder/spec_test.go +++ b/pkg/bloombuild/builder/spec_test.go @@ -48,7 +48,7 @@ func blocksFromSchemaWithRange(t *testing.T, n int, options v1.BlockOptions, fro minIdx, maxIdx := i*seriesPerBlock, (i+1)*seriesPerBlock - itr := v2.NewSliceIter[v1.SeriesWithBlooms](data[minIdx:maxIdx]) + itr := v2.NewSliceIter(data[minIdx:maxIdx]) _, err = builder.BuildFrom(itr) require.Nil(t, err) @@ -134,8 +134,8 @@ func TestSimpleBloomGenerator(t *testing.T) { } { t.Run(fmt.Sprintf("%s/%s", tc.desc, enc), func(t *testing.T) { sourceBlocks, data, refs := blocksFromSchemaWithRange(t, 2, tc.fromSchema, 0x00000, 0x6ffff) - storeItr := v2.NewMapIter[v1.SeriesWithBlooms, *v1.Series]( - v2.NewSliceIter[v1.SeriesWithBlooms](data), + storeItr := v2.NewMapIter( + v2.NewSliceIter(data), func(swb v1.SeriesWithBlooms) *v1.Series { return &swb.Series.Series }, diff --git a/pkg/bloombuild/common/tsdb.go b/pkg/bloombuild/common/tsdb.go index 67977231667ee..a58b7cd6130f9 100644 --- a/pkg/bloombuild/common/tsdb.go +++ b/pkg/bloombuild/common/tsdb.go @@ -163,7 +163,7 @@ func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, b case <-ctx.Done(): return iter.NewEmptyIter[*v1.Series](), ctx.Err() default: - return iter.NewCancelableIter[*v1.Series](ctx, iter.NewSliceIter[*v1.Series](series)), nil + return iter.NewCancelableIter(ctx, iter.NewSliceIter(series)), nil } } diff --git a/pkg/bloombuild/common/tsdb_test.go b/pkg/bloombuild/common/tsdb_test.go index 70ee440551e42..b2df7982f4382 100644 --- a/pkg/bloombuild/common/tsdb_test.go +++ b/pkg/bloombuild/common/tsdb_test.go @@ -66,7 +66,7 @@ func TestTSDBSeriesIter(t *testing.T) { itr, err := NewTSDBSeriesIter(context.Background(), "", forSeriesTestImpl(input), v1.NewBounds(0, math.MaxUint64)) require.NoError(t, err) - v1.EqualIterators[*v1.Series]( + v1.EqualIterators( t, func(a, b *v1.Series) { require.Equal(t, a, b) diff --git a/pkg/bloombuild/planner/metrics.go b/pkg/bloombuild/planner/metrics.go index 3523135780e55..936515ad736f3 100644 --- a/pkg/bloombuild/planner/metrics.go +++ b/pkg/bloombuild/planner/metrics.go @@ -5,8 +5,6 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - - "github.com/grafana/loki/v3/pkg/queue" ) const ( @@ -211,7 +209,3 @@ func NewMetrics( }), } } - -func NewQueueMetrics(r prometheus.Registerer) *queue.Metrics { - return queue.NewMetrics(r, metricsNamespace, metricsSubsystem) -} diff --git a/pkg/bloombuild/planner/planner.go b/pkg/bloombuild/planner/planner.go index d2884b87cfda0..18c43cfcfa121 100644 --- a/pkg/bloombuild/planner/planner.go +++ b/pkg/bloombuild/planner/planner.go @@ -82,7 +82,7 @@ func New( } // Queue to manage tasks - queueMetrics := NewQueueMetrics(r) + queueMetrics := queue.NewMetrics(r, metricsNamespace, metricsSubsystem) tasksQueue := queue.NewRequestQueue(cfg.MaxQueuedTasksPerTenant, 0, NewQueueLimits(limits), queueMetrics) // Clean metrics for inactive users: do not have added tasks to the queue in the last 1 hour @@ -591,14 +591,14 @@ func (p *Planner) deleteOutdatedMetasAndBlocks( err = client.DeleteMetas(ctx, []bloomshipper.MetaRef{meta.MetaRef}) if err != nil { if client.IsObjectNotFoundErr(err) { - level.Debug(logger).Log("msg", "meta not found while attempting delete, continuing", "meta", meta.MetaRef.String()) + level.Debug(logger).Log("msg", "meta not found while attempting delete, continuing", "meta", meta.String()) } else { - level.Error(logger).Log("msg", "failed to delete meta", "err", err, "meta", meta.MetaRef.String()) + level.Error(logger).Log("msg", "failed to delete meta", "err", err, "meta", meta.String()) return nil, errors.Wrap(err, "failed to delete meta") } } deletedMetas++ - level.Debug(logger).Log("msg", "removed outdated meta", "meta", meta.MetaRef.String()) + level.Debug(logger).Log("msg", "removed outdated meta", "meta", meta.String()) } level.Debug(logger).Log( diff --git a/pkg/bloombuild/planner/strategies/splitkeyspace.go b/pkg/bloombuild/planner/strategies/splitkeyspace.go index ea4db8f2e29fc..6aa572bd3af40 100644 --- a/pkg/bloombuild/planner/strategies/splitkeyspace.go +++ b/pkg/bloombuild/planner/strategies/splitkeyspace.go @@ -207,13 +207,13 @@ func blockPlansForGaps( return planGap.Blocks[i].Bounds.Less(planGap.Blocks[j].Bounds) }) - peekingBlocks := iter.NewPeekIter[bloomshipper.BlockRef]( - iter.NewSliceIter[bloomshipper.BlockRef]( + peekingBlocks := iter.NewPeekIter( + iter.NewSliceIter( planGap.Blocks, ), ) // dedupe blocks which could be in multiple metas - itr := iter.NewDedupingIter[bloomshipper.BlockRef, bloomshipper.BlockRef]( + itr := iter.NewDedupingIter( func(a, b bloomshipper.BlockRef) bool { return a == b }, @@ -224,7 +224,7 @@ func blockPlansForGaps( peekingBlocks, ) - deduped, err := iter.Collect[bloomshipper.BlockRef](itr) + deduped, err := iter.Collect(itr) if err != nil { return nil, fmt.Errorf("failed to dedupe blocks: %w", err) } diff --git a/pkg/bloombuild/planner/util.go b/pkg/bloombuild/planner/util.go deleted file mode 100644 index f9a97587f802f..0000000000000 --- a/pkg/bloombuild/planner/util.go +++ /dev/null @@ -1,125 +0,0 @@ -package planner - -import ( - "fmt" - "math" - - "github.com/prometheus/common/model" - - v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" -) - -// SplitFingerprintKeyspaceByFactor splits the keyspace covered by model.Fingerprint into contiguous non-overlapping ranges. -func SplitFingerprintKeyspaceByFactor(factor int) []v1.FingerprintBounds { - if factor <= 0 { - return nil - } - - bounds := make([]v1.FingerprintBounds, 0, factor) - - // The keyspace of a Fingerprint is from 0 to max uint64. - keyspaceSize := uint64(math.MaxUint64) - - // Calculate the size of each range. - rangeSize := keyspaceSize / uint64(factor) - - for i := 0; i < factor; i++ { - // Calculate the start and end of the range. - start := uint64(i) * rangeSize - end := start + rangeSize - 1 - - // For the last range, make sure it ends at the end of the keyspace. - if i == factor-1 { - end = keyspaceSize - } - - // Create a FingerprintBounds for the range and add it to the slice. - bounds = append(bounds, v1.FingerprintBounds{ - Min: model.Fingerprint(start), - Max: model.Fingerprint(end), - }) - } - - return bounds -} - -func FindGapsInFingerprintBounds(ownershipRange v1.FingerprintBounds, metas []v1.FingerprintBounds) (gaps []v1.FingerprintBounds, err error) { - if len(metas) == 0 { - return []v1.FingerprintBounds{ownershipRange}, nil - } - - // turn the available metas into a list of non-overlapping metas - // for easier processing - var nonOverlapping []v1.FingerprintBounds - // First, we reduce the metas into a smaller set by combining overlaps. They must be sorted. - var cur *v1.FingerprintBounds - for i := 0; i < len(metas); i++ { - j := i + 1 - - // first iteration (i == 0), set the current meta - if cur == nil { - cur = &metas[i] - } - - if j >= len(metas) { - // We've reached the end of the list. Add the last meta to the non-overlapping set. - nonOverlapping = append(nonOverlapping, *cur) - break - } - - combined := cur.Union(metas[j]) - if len(combined) == 1 { - // There was an overlap between the two tested ranges. Combine them and keep going. - cur = &combined[0] - continue - } - - // There was no overlap between the two tested ranges. Add the first to the non-overlapping set. - // and keep the second for the next iteration. - nonOverlapping = append(nonOverlapping, combined[0]) - cur = &combined[1] - } - - // Now, detect gaps between the non-overlapping metas and the ownership range. - // The left bound of the ownership range will be adjusted as we go. - leftBound := ownershipRange.Min - for _, meta := range nonOverlapping { - - clippedMeta := meta.Intersection(ownershipRange) - // should never happen as long as we are only combining metas - // that intersect with the ownership range - if clippedMeta == nil { - return nil, fmt.Errorf("meta is not within ownership range: %v", meta) - } - - searchRange := ownershipRange.Slice(leftBound, clippedMeta.Max) - // update the left bound for the next iteration - // We do the max to prevent the max bound to overflow from MaxUInt64 to 0 - leftBound = min( - max(clippedMeta.Max+1, clippedMeta.Max), - max(ownershipRange.Max+1, ownershipRange.Max), - ) - - // since we've already ensured that the meta is within the ownership range, - // we know the xor will be of length zero (when the meta is equal to the ownership range) - // or 1 (when the meta is a subset of the ownership range) - xors := searchRange.Unless(*clippedMeta) - if len(xors) == 0 { - // meta is equal to the ownership range. This means the meta - // covers this entire section of the ownership range. - continue - } - - gaps = append(gaps, xors[0]) - } - - // If the leftBound is less than the ownership range max, and it's smaller than MaxUInt64, - // There is a gap between the last meta and the end of the ownership range. - // Note: we check `leftBound < math.MaxUint64` since in the loop above we clamp the - // leftBound to MaxUint64 to prevent an overflow to 0: `max(clippedMeta.Max+1, clippedMeta.Max)` - if leftBound < math.MaxUint64 && leftBound <= ownershipRange.Max { - gaps = append(gaps, v1.NewBounds(leftBound, ownershipRange.Max)) - } - - return gaps, nil -} diff --git a/pkg/bloombuild/planner/util_test.go b/pkg/bloombuild/planner/util_test.go deleted file mode 100644 index 6755478ef7290..0000000000000 --- a/pkg/bloombuild/planner/util_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package planner - -import ( - "math" - "testing" - - "github.com/prometheus/common/model" - "github.com/stretchr/testify/require" - - v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" -) - -func TestSplitFingerprintKeyspaceByFactor(t *testing.T) { - for _, tt := range []struct { - name string - factor int - }{ - { - name: "Factor is 0", - factor: 0, - }, - { - name: "Factor is 1", - factor: 1, - }, - { - name: "Factor is 256", - factor: 256, - }, - } { - t.Run(tt.name, func(t *testing.T) { - got := SplitFingerprintKeyspaceByFactor(tt.factor) - - if tt.factor == 0 { - require.Empty(t, got) - return - } - - // Check overall min and max values of the ranges. - require.Equal(t, model.Fingerprint(math.MaxUint64), got[len(got)-1].Max) - require.Equal(t, model.Fingerprint(0), got[0].Min) - - // For each range, check that the max value of the previous range is one less than the min value of the current range. - for i := 1; i < len(got); i++ { - require.Equal(t, got[i-1].Max+1, got[i].Min) - } - }) - } -} - -func Test_FindGapsInFingerprintBounds(t *testing.T) { - for _, tc := range []struct { - desc string - err bool - exp []v1.FingerprintBounds - ownershipRange v1.FingerprintBounds - metas []v1.FingerprintBounds - }{ - { - desc: "error nonoverlapping metas", - err: true, - exp: nil, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{v1.NewBounds(11, 20)}, - }, - { - desc: "one meta with entire ownership range", - err: false, - exp: nil, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{v1.NewBounds(0, 10)}, - }, - { - desc: "two non-overlapping metas with entire ownership range", - err: false, - exp: nil, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, 5), - v1.NewBounds(6, 10), - }, - }, - { - desc: "two overlapping metas with entire ownership range", - err: false, - exp: nil, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, 6), - v1.NewBounds(4, 10), - }, - }, - { - desc: "one meta with partial ownership range", - err: false, - exp: []v1.FingerprintBounds{ - v1.NewBounds(6, 10), - }, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, 5), - }, - }, - { - desc: "smaller subsequent meta with partial ownership range", - err: false, - exp: []v1.FingerprintBounds{ - v1.NewBounds(8, 10), - }, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, 7), - v1.NewBounds(3, 4), - }, - }, - { - desc: "hole in the middle", - err: false, - exp: []v1.FingerprintBounds{ - v1.NewBounds(4, 5), - }, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, 3), - v1.NewBounds(6, 10), - }, - }, - { - desc: "holes on either end", - err: false, - exp: []v1.FingerprintBounds{ - v1.NewBounds(0, 2), - v1.NewBounds(8, 10), - }, - ownershipRange: v1.NewBounds(0, 10), - metas: []v1.FingerprintBounds{ - v1.NewBounds(3, 5), - v1.NewBounds(6, 7), - }, - }, - { - desc: "full ownership range with single meta", - err: false, - exp: nil, - ownershipRange: v1.NewBounds(0, math.MaxUint64), - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, math.MaxUint64), - }, - }, - { - desc: "full ownership range with multiple metas", - err: false, - exp: nil, - ownershipRange: v1.NewBounds(0, math.MaxUint64), - // Three metas covering the whole 0 - MaxUint64 - metas: []v1.FingerprintBounds{ - v1.NewBounds(0, math.MaxUint64/3), - v1.NewBounds(math.MaxUint64/3+1, math.MaxUint64/2), - v1.NewBounds(math.MaxUint64/2+1, math.MaxUint64), - }, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - gaps, err := FindGapsInFingerprintBounds(tc.ownershipRange, tc.metas) - if tc.err { - require.Error(t, err) - return - } - require.Equal(t, tc.exp, gaps) - }) - } -} diff --git a/pkg/bloombuild/protos/compat.go b/pkg/bloombuild/protos/compat.go index 468278e77dbea..7c910d405ad9b 100644 --- a/pkg/bloombuild/protos/compat.go +++ b/pkg/bloombuild/protos/compat.go @@ -249,7 +249,7 @@ func (r *TaskResult) ToProtoTaskResult() *ProtoTaskResult { } protoMetas = append(protoMetas, &ProtoMeta{ - MetaRef: meta.MetaRef.String(), + MetaRef: meta.String(), SourcesTSDBs: metaRefs, BlockRefs: blockRefs, }) diff --git a/pkg/bloomgateway/bloomgateway.go b/pkg/bloomgateway/bloomgateway.go index 3c42f68ef0ddf..ca8a8b7fcd43b 100644 --- a/pkg/bloomgateway/bloomgateway.go +++ b/pkg/bloomgateway/bloomgateway.go @@ -352,7 +352,7 @@ func filterChunkRefs(req *logproto.FilterChunkRefRequest, responses []v1.Output) // dedupe outputs, merging the same series. // This returns an Iterator[v1.Output] - dedupedResps := iter.NewDedupingIter[v1.Output, v1.Output]( + dedupedResps := iter.NewDedupingIter( // eq func(o1, o2 v1.Output) bool { return o1.Fp == o2.Fp diff --git a/pkg/bloomgateway/client.go b/pkg/bloomgateway/client.go index a873d04960b47..b4ba69369f554 100644 --- a/pkg/bloomgateway/client.go +++ b/pkg/bloomgateway/client.go @@ -301,12 +301,12 @@ func mergeSeries(input [][]*logproto.GroupedChunkRefs, buf []*logproto.GroupedCh iters = append(iters, iter.NewPeekIter(iter.NewSliceIter(inp))) } - heapIter := v1.NewHeapIterator[*logproto.GroupedChunkRefs]( + heapIter := v1.NewHeapIterator( func(a, b *logproto.GroupedChunkRefs) bool { return a.Fingerprint < b.Fingerprint }, iters..., ) - dedupeIter := iter.NewDedupingIter[*logproto.GroupedChunkRefs, *logproto.GroupedChunkRefs]( + dedupeIter := iter.NewDedupingIter( // eq func(a, b *logproto.GroupedChunkRefs) bool { return a.Fingerprint == b.Fingerprint }, // from diff --git a/pkg/bloomgateway/client_pool.go b/pkg/bloomgateway/client_pool.go index b784511e201bf..ebf2da9f514c4 100644 --- a/pkg/bloomgateway/client_pool.go +++ b/pkg/bloomgateway/client_pool.go @@ -76,14 +76,6 @@ func (p *JumpHashClientPool) Stop() { _ = services.StopAndAwaitTerminated(context.Background(), p.Service) } -func (p *JumpHashClientPool) AddrForFingerprint(fp uint64) (string, error) { - addr, err := p.FromUInt64(fp) - if err != nil { - return "", err - } - return addr.String(), nil -} - func (p *JumpHashClientPool) Addr(key string) (string, error) { addr, err := p.FromString(key) if err != nil { diff --git a/pkg/bloomgateway/metrics.go b/pkg/bloomgateway/metrics.go index 4eeffbf8ad682..690f95354a23b 100644 --- a/pkg/bloomgateway/metrics.go +++ b/pkg/bloomgateway/metrics.go @@ -23,7 +23,6 @@ const ( type clientMetrics struct { clientRequests *prometheus.CounterVec requestLatency *prometheus.HistogramVec - clients prometheus.Gauge } func newClientMetrics(registerer prometheus.Registerer) *clientMetrics { @@ -41,12 +40,6 @@ func newClientMetrics(registerer prometheus.Registerer) *clientMetrics { Help: "Time (in seconds) spent serving requests when using the bloom gateway", Buckets: instrument.DefBuckets, }, []string{"operation", "status_code"}), - clients: promauto.With(registerer).NewGauge(prometheus.GaugeOpts{ - Namespace: constants.Loki, - Subsystem: "bloom_gateway", - Name: "clients", - Help: "The current number of bloom gateway clients.", - }), } } diff --git a/pkg/bloomgateway/multiplexing.go b/pkg/bloomgateway/multiplexing.go index 2aee9dc32c48b..7f929a1e19c6a 100644 --- a/pkg/bloomgateway/multiplexing.go +++ b/pkg/bloomgateway/multiplexing.go @@ -18,17 +18,20 @@ const ( Day = 24 * time.Hour ) -type tokenSettings struct { - nGramLen int -} - type wrappedError struct { mu sync.Mutex err error } func (e *wrappedError) Error() string { - return e.err.Error() + e.mu.Lock() + err := e.err + e.mu.Unlock() + + if err == nil { + return "" + } + return err.Error() } func (e *wrappedError) Set(err error) { diff --git a/pkg/bloomgateway/multiplexing_test.go b/pkg/bloomgateway/multiplexing_test.go index e6b97679e1ef8..d290817ef4be7 100644 --- a/pkg/bloomgateway/multiplexing_test.go +++ b/pkg/bloomgateway/multiplexing_test.go @@ -108,7 +108,7 @@ func TestTask_RequestIterator(t *testing.T) { } // merge the request iterators using the heap sort iterator - it := v1.NewHeapIterator[v1.Request](func(r1, r2 v1.Request) bool { return r1.Fp < r2.Fp }, iters...) + it := v1.NewHeapIterator(func(r1, r2 v1.Request) bool { return r1.Fp < r2.Fp }, iters...) // first item require.True(t, it.Next()) diff --git a/pkg/bloomgateway/processor.go b/pkg/bloomgateway/processor.go index 2b44b1e5459c1..9851166fb2de8 100644 --- a/pkg/bloomgateway/processor.go +++ b/pkg/bloomgateway/processor.go @@ -168,7 +168,7 @@ func (p *processor) processBlock(_ context.Context, bq *bloomshipper.CloseableBl iters = append(iters, it) } - logger := log.With(p.logger, "block", bq.BlockRef.String()) + logger := log.With(p.logger, "block", bq.String()) fq := blockQuerier.Fuse(iters, logger) start := time.Now() diff --git a/pkg/bloomgateway/querier.go b/pkg/bloomgateway/querier.go index dfc3746380ab3..211372b84bcc5 100644 --- a/pkg/bloomgateway/querier.go +++ b/pkg/bloomgateway/querier.go @@ -149,7 +149,7 @@ func (bq *BloomQuerier) FilterChunkRefs(ctx context.Context, tenant string, from // We can perform requests sequentially, because most of the time the request // only covers a single day, and if not, it's at most two days. for _, s := range partitionSeriesByDay(from, through, grouped) { - day := bloomshipper.NewInterval(s.day.Time, s.day.Time.Add(Day)) + day := bloomshipper.NewInterval(s.day.Time, s.day.Add(Day)) blocks, skipped, err := bq.blockResolver.Resolve(ctx, tenant, day, s.series) if err != nil { return nil, err diff --git a/pkg/bloomgateway/stats.go b/pkg/bloomgateway/stats.go index fe0046a2f11bd..76fad12ff9e31 100644 --- a/pkg/bloomgateway/stats.go +++ b/pkg/bloomgateway/stats.go @@ -13,7 +13,7 @@ type Stats struct { ChunksRequested, ChunksFiltered int SeriesRequested, SeriesFiltered int QueueTime *atomic.Duration - MetasFetchTime, BlocksFetchTime *atomic.Duration + BlocksFetchTime *atomic.Duration ProcessingTime, TotalProcessingTime *atomic.Duration PostProcessingTime *atomic.Duration ProcessedBlocks *atomic.Int32 // blocks processed for this specific request @@ -31,7 +31,6 @@ func ContextWithEmptyStats(ctx context.Context) (*Stats, context.Context) { ProcessedBlocks: atomic.NewInt32(0), ProcessedBlocksTotal: atomic.NewInt32(0), QueueTime: atomic.NewDuration(0), - MetasFetchTime: atomic.NewDuration(0), BlocksFetchTime: atomic.NewDuration(0), ProcessingTime: atomic.NewDuration(0), TotalProcessingTime: atomic.NewDuration(0), @@ -54,7 +53,6 @@ func FromContext(ctx context.Context) *Stats { // aggregates the total duration func (s *Stats) Duration() (dur time.Duration) { dur += s.QueueTime.Load() - dur += s.MetasFetchTime.Load() dur += s.BlocksFetchTime.Load() dur += s.ProcessingTime.Load() dur += s.PostProcessingTime.Load() @@ -82,7 +80,6 @@ func (s *Stats) KVArgs() []any { "chunks_remaining", chunksRemaining, "filter_ratio", filterRatio, "queue_time", s.QueueTime.Load(), - "metas_fetch_time", s.MetasFetchTime.Load(), "blocks_fetch_time", s.BlocksFetchTime.Load(), "processing_time", s.ProcessingTime.Load(), "post_processing_time", s.PostProcessingTime.Load(), @@ -97,13 +94,6 @@ func (s *Stats) AddQueueTime(t time.Duration) { s.QueueTime.Add(t) } -func (s *Stats) AddMetasFetchTime(t time.Duration) { - if s == nil { - return - } - s.MetasFetchTime.Add(t) -} - func (s *Stats) AddBlocksFetchTime(t time.Duration) { if s == nil { return diff --git a/pkg/bloomgateway/util.go b/pkg/bloomgateway/util.go index bb130019d4381..868fdf2ac6ed5 100644 --- a/pkg/bloomgateway/util.go +++ b/pkg/bloomgateway/util.go @@ -4,7 +4,6 @@ import ( "sort" "github.com/prometheus/common/model" - "golang.org/x/exp/slices" "github.com/grafana/loki/v3/pkg/logproto" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -34,23 +33,6 @@ func daysForRange(from, through model.Time) []model.Time { return days } -// getFromThrough assumes a list of ShortRefs sorted by From time -func getFromThrough(refs []*logproto.ShortRef) (model.Time, model.Time) { - if len(refs) == 0 { - return model.Earliest, model.Latest - } - - if len(refs) == 1 { - return refs[0].From, refs[0].Through - } - - maxItem := slices.MaxFunc(refs, func(a, b *logproto.ShortRef) int { - return int(a.Through) - int(b.Through) - }) - - return refs[0].From, maxItem.Through -} - // convertToChunkRefs converts a []*logproto.ShortRef into v1.ChunkRefs func convertToChunkRefs(refs []*logproto.ShortRef) v1.ChunkRefs { result := make(v1.ChunkRefs, 0, len(refs)) diff --git a/pkg/bloomgateway/util_test.go b/pkg/bloomgateway/util_test.go index f2be3b0665dd4..2838c9e5e8c5c 100644 --- a/pkg/bloomgateway/util_test.go +++ b/pkg/bloomgateway/util_test.go @@ -31,23 +31,6 @@ func mktime(s string) model.Time { return model.TimeFromUnix(ts.Unix()) } -func TestGetFromThrough(t *testing.T) { - chunks := []*logproto.ShortRef{ - {From: 0, Through: 6}, - {From: 1, Through: 5}, - {From: 2, Through: 9}, - {From: 3, Through: 8}, - {From: 4, Through: 7}, - } - from, through := getFromThrough(chunks) - require.Equal(t, model.Time(0), from) - require.Equal(t, model.Time(9), through) - - // assert that slice order did not change - require.Equal(t, model.Time(0), chunks[0].From) - require.Equal(t, model.Time(4), chunks[len(chunks)-1].From) -} - func TestTruncateDay(t *testing.T) { expected := mktime("2024-01-24 00:00") diff --git a/pkg/storage/bloom/v1/archive_test.go b/pkg/storage/bloom/v1/archive_test.go index f91039cac3691..b000a09ac9d78 100644 --- a/pkg/storage/bloom/v1/archive_test.go +++ b/pkg/storage/bloom/v1/archive_test.go @@ -22,10 +22,7 @@ func TestArchive(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.None, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.None), SeriesPageSize: 100, BloomPageSize: 10 << 10, }, @@ -33,7 +30,7 @@ func TestArchive(t *testing.T) { ) require.Nil(t, err) - itr := v2.NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.Nil(t, err) @@ -104,10 +101,7 @@ func TestArchiveCompression(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.None, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.None), SeriesPageSize: 100, BloomPageSize: 10 << 10, }, @@ -115,7 +109,7 @@ func TestArchiveCompression(t *testing.T) { ) require.Nil(t, err) - itr := v2.NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.Nil(t, err) diff --git a/pkg/storage/bloom/v1/block.go b/pkg/storage/bloom/v1/block.go index c309cb7fec29c..7ae55ae222c23 100644 --- a/pkg/storage/bloom/v1/block.go +++ b/pkg/storage/bloom/v1/block.go @@ -137,7 +137,7 @@ func (bq *BlockQuerier) Schema() (Schema, error) { func (bq *BlockQuerier) Reset() error { bq.blooms.Reset() - return bq.LazySeriesIter.Seek(0) + return bq.Seek(0) } func (bq *BlockQuerier) Err() error { diff --git a/pkg/storage/bloom/v1/block_writer.go b/pkg/storage/bloom/v1/block_writer.go index a50c2f81e4b8a..483a5425640c8 100644 --- a/pkg/storage/bloom/v1/block_writer.go +++ b/pkg/storage/bloom/v1/block_writer.go @@ -14,7 +14,6 @@ import ( ) const ( - FileMode = 0644 BloomFileName = "bloom" SeriesFileName = "series" ) diff --git a/pkg/storage/bloom/v1/bloom.go b/pkg/storage/bloom/v1/bloom.go index 82c85bd9f441b..da283794923e4 100644 --- a/pkg/storage/bloom/v1/bloom.go +++ b/pkg/storage/bloom/v1/bloom.go @@ -47,18 +47,6 @@ func (b *Bloom) Encode(enc *encoding.Encbuf) error { return nil } -func (b *Bloom) DecodeCopy(dec *encoding.Decbuf) error { - ln := dec.Uvarint() - data := dec.Bytes(ln) - - _, err := b.ReadFrom(bytes.NewReader(data)) - if err != nil { - return errors.Wrap(err, "decoding copy of bloom filter") - } - - return nil -} - func (b *Bloom) Decode(dec *encoding.Decbuf) error { ln := dec.Uvarint() data := dec.Bytes(ln) diff --git a/pkg/storage/bloom/v1/bloom_builder.go b/pkg/storage/bloom/v1/bloom_builder.go index ea54ba248f7c4..9829d9ffc380a 100644 --- a/pkg/storage/bloom/v1/bloom_builder.go +++ b/pkg/storage/bloom/v1/bloom_builder.go @@ -28,20 +28,9 @@ func NewBloomBlockBuilder(opts BlockOptions, writer io.WriteCloser) *BloomBlockB } } -func (b *BloomBlockBuilder) WriteSchema() error { - b.scratch.Reset() - b.opts.Schema.Encode(b.scratch) - if _, err := b.writer.Write(b.scratch.Get()); err != nil { - return errors.Wrap(err, "writing schema") - } - b.writtenSchema = true - b.offset += b.scratch.Len() - return nil -} - func (b *BloomBlockBuilder) Append(bloom *Bloom) (BloomOffset, error) { if !b.writtenSchema { - if err := b.WriteSchema(); err != nil { + if err := b.writeSchema(); err != nil { return BloomOffset{}, errors.Wrap(err, "writing schema") } } @@ -63,6 +52,21 @@ func (b *BloomBlockBuilder) Append(bloom *Bloom) (BloomOffset, error) { }, nil } +func (b *BloomBlockBuilder) writeSchema() error { + if b.writtenSchema { + return nil + } + + b.scratch.Reset() + b.opts.Schema.Encode(b.scratch) + if _, err := b.writer.Write(b.scratch.Get()); err != nil { + return errors.Wrap(err, "writing schema") + } + b.writtenSchema = true + b.offset += b.scratch.Len() + return nil +} + func (b *BloomBlockBuilder) Close() (uint32, error) { if b.page.Count() > 0 { if err := b.flushPage(); err != nil { diff --git a/pkg/storage/bloom/v1/bloom_tokenizer.go b/pkg/storage/bloom/v1/bloom_tokenizer.go index 939c91c214398..2cf75b9fbd12a 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer.go @@ -126,12 +126,12 @@ func (bt *BloomTokenizer) Populate(blooms v2iter.SizedIterator[*Bloom], chks v2i } func (bt *BloomTokenizer) sendBloom(ch chan<- *BloomCreation, bloom *Bloom, info indexingInfo) { - fillRatio := bloom.ScalableBloomFilter.FillRatio() + fillRatio := bloom.FillRatio() bt.metrics.hammingWeightRatio.Observe(fillRatio) bt.metrics.estimatedCount.Observe( - float64(estimatedCount(bloom.ScalableBloomFilter.Capacity(), fillRatio)), + float64(estimatedCount(bloom.Capacity(), fillRatio)), ) - bt.metrics.bloomSize.Observe(float64(bloom.ScalableBloomFilter.Capacity() / eightBits)) + bt.metrics.bloomSize.Observe(float64(bloom.Capacity() / eightBits)) bt.metrics.bloomsTotal.Inc() ch <- &BloomCreation{ Bloom: bloom, @@ -184,7 +184,7 @@ func (bt *BloomTokenizer) addChunkToBloom(bloom *Bloom, ref ChunkRef, entryIter } // maxBloomSize is in bytes, but blooms operate at the bit level; adjust - collision, full = bloom.ScalableBloomFilter.TestAndAddWithMaxSize([]byte(tok), bt.maxBloomSize*eightBits) + collision, full = bloom.TestAndAddWithMaxSize([]byte(tok), bt.maxBloomSize*eightBits) if collision { collisionInserts++ diff --git a/pkg/storage/bloom/v1/bloom_tokenizer_test.go b/pkg/storage/bloom/v1/bloom_tokenizer_test.go index f4c7ec7d831c4..ec5dd475481d4 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer_test.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer_test.go @@ -173,7 +173,7 @@ func TestTokenizerPopulateWontExceedMaxSize(t *testing.T) { var ct int for created := range ch { ct++ - capacity := created.Bloom.ScalableBloomFilter.Capacity() / 8 + capacity := created.Bloom.Capacity() / 8 t.Log(ct, int(capacity), maxSize) require.Less(t, int(capacity), maxSize) } diff --git a/pkg/storage/bloom/v1/bounds.go b/pkg/storage/bloom/v1/bounds.go index d33a3dec6aa63..aebcece85138f 100644 --- a/pkg/storage/bloom/v1/bounds.go +++ b/pkg/storage/bloom/v1/bounds.go @@ -5,11 +5,9 @@ import ( "hash" "math" "strings" - "unsafe" "github.com/pkg/errors" "github.com/prometheus/common/model" - "golang.org/x/exp/slices" iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" @@ -41,13 +39,6 @@ func BoundsFromProto(pb logproto.FPBounds) FingerprintBounds { return FingerprintBounds(pb) } -// Unsafe cast to avoid allocation. This _requires_ that the underlying types are the same -// which is checked by the compiler above -func MultiBoundsFromProto(pb []logproto.FPBounds) MultiFingerprintBounds { - //nolint:unconvert - return MultiFingerprintBounds(*(*MultiFingerprintBounds)(unsafe.Pointer(&pb))) -} - // ParseBoundsFromAddr parses a fingerprint bounds from a string func ParseBoundsFromAddr(s string) (FingerprintBounds, error) { parts := strings.Split(s, "-") @@ -207,40 +198,6 @@ func (b FingerprintBounds) Range() uint64 { return uint64(b.Max - b.Min) } -type MultiFingerprintBounds []FingerprintBounds - -func (mb MultiFingerprintBounds) Union(target FingerprintBounds) MultiFingerprintBounds { - if len(mb) == 0 { - return MultiFingerprintBounds{target} - } - if len(mb) == 1 { - return mb[0].Union(target) - } - - mb = append(mb, target) - slices.SortFunc(mb, func(a, b FingerprintBounds) int { - if a.Less(b) { - return -1 - } else if a.Equal(b) { - return 0 - } - return 1 - }) - - var union MultiFingerprintBounds - for i := 0; i < len(mb); i++ { - j := len(union) - 1 // index of last item of union - if j >= 0 && union[j].Max >= mb[i].Min-1 { - union[j] = NewBounds(union[j].Min, max(mb[i].Max, union[j].Max)) - } else { - union = append(union, mb[i]) - } - } - - mb = union - return mb -} - // unused, but illustrative type BoundedIter[V any] struct { iter.Iterator[V] @@ -249,7 +206,7 @@ type BoundedIter[V any] struct { func (bi *BoundedIter[V]) Next() bool { for bi.Iterator.Next() { - switch bi.cmp(bi.Iterator.At()) { + switch bi.cmp(bi.At()) { case Before: continue case After: diff --git a/pkg/storage/bloom/v1/bounds_test.go b/pkg/storage/bloom/v1/bounds_test.go index 5baaf07e900df..e6f64827e10d8 100644 --- a/pkg/storage/bloom/v1/bounds_test.go +++ b/pkg/storage/bloom/v1/bounds_test.go @@ -17,17 +17,6 @@ func TestBoundsFromProto(t *testing.T) { assert.Equal(t, NewBounds(10, 2000), bounds) } -func TestMultiBoundsFromProto(t *testing.T) { - bounds := MultiBoundsFromProto([]logproto.FPBounds{ - {Min: 10, Max: 2000}, - {Min: 2001, Max: 4000}, - }) - assert.Equal(t, MultiFingerprintBounds{ - NewBounds(10, 2000), - NewBounds(2001, 4000), - }, bounds) -} - func Test_ParseFingerprint(t *testing.T) { t.Parallel() fp, err := model.ParseFingerprint("7d0") @@ -150,132 +139,3 @@ func Test_FingerprintBounds_Unless(t *testing.T) { }, NewBounds(5, 25).Unless(target)) assert.Nil(t, NewBounds(14, 15).Unless(target)) } - -func Test_MultiFingerprintBounds(t *testing.T) { - for _, tc := range []struct { - desc string - mb MultiFingerprintBounds - target FingerprintBounds - exp MultiFingerprintBounds - }{ - { - desc: "no elements", - mb: MultiFingerprintBounds{}, - target: NewBounds(0, 9), - exp: MultiFingerprintBounds{ - NewBounds(0, 9), - }, - }, - { - desc: "single element before", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - }, - target: NewBounds(15, 19), - exp: MultiFingerprintBounds{ - NewBounds(5, 9), - NewBounds(15, 19), - }, - }, - { - desc: "single element after", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - }, - target: NewBounds(0, 3), - exp: MultiFingerprintBounds{ - NewBounds(0, 3), - NewBounds(5, 9), - }, - }, - { - desc: "single element overlapping", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - }, - target: NewBounds(0, 14), - exp: MultiFingerprintBounds{ - NewBounds(0, 14), - }, - }, - { - desc: "multiple elements single overlapping", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - NewBounds(15, 19), - }, - target: NewBounds(0, 6), - exp: MultiFingerprintBounds{ - NewBounds(0, 9), - NewBounds(15, 19), - }, - }, - { - desc: "multiple elements single overlapping", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - NewBounds(15, 19), - }, - target: NewBounds(11, 25), - exp: MultiFingerprintBounds{ - NewBounds(5, 9), - NewBounds(11, 25), - }, - }, - { - desc: "multiple elements combining overlapping", - mb: MultiFingerprintBounds{ - NewBounds(5, 9), - NewBounds(15, 19), - }, - target: NewBounds(9, 15), - exp: MultiFingerprintBounds{ - NewBounds(5, 19), - }, - }, - { - desc: "combination", - mb: MultiFingerprintBounds{ - NewBounds(0, 2), - NewBounds(5, 9), - NewBounds(15, 19), - NewBounds(25, 29), - }, - target: NewBounds(9, 15), - exp: MultiFingerprintBounds{ - NewBounds(0, 2), - NewBounds(5, 19), - NewBounds(25, 29), - }, - }, - { - desc: "overlapping ranges", - mb: MultiFingerprintBounds{ - NewBounds(0, 6), - NewBounds(5, 15), - }, - target: NewBounds(8, 10), - exp: MultiFingerprintBounds{ - NewBounds(0, 15), - }, - }, - { - desc: "disjoint ranges and target is between", - mb: MultiFingerprintBounds{ - NewBounds(0, 9), - NewBounds(30, 39), - }, - target: NewBounds(15, 19), - exp: MultiFingerprintBounds{ - NewBounds(0, 9), - NewBounds(15, 19), - NewBounds(30, 39), - }, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - res := tc.mb.Union(tc.target) - assert.Equal(t, tc.exp, res) - }) - } -} diff --git a/pkg/storage/bloom/v1/builder.go b/pkg/storage/bloom/v1/builder.go index 0d291b5a9ea28..fa5f5aa047a7b 100644 --- a/pkg/storage/bloom/v1/builder.go +++ b/pkg/storage/bloom/v1/builder.go @@ -67,10 +67,8 @@ func (b BlockOptions) Encode(enc *encoding.Encbuf) { } func NewBlockOptions(enc compression.Codec, maxBlockSizeBytes, maxBloomSizeBytes uint64) BlockOptions { - opts := NewBlockOptionsFromSchema(Schema{ - version: CurrentSchemaVersion, - encoding: enc, - }, maxBloomSizeBytes) + schema := NewSchema(CurrentSchemaVersion, enc) + opts := NewBlockOptionsFromSchema(schema, maxBloomSizeBytes) opts.BlockSize = maxBlockSizeBytes opts.UnencodedBlockOptions.MaxBloomSizeBytes = maxBloomSizeBytes return opts @@ -209,7 +207,7 @@ func NewMergeBuilder( // because blooms dont contain the label-set (only the fingerprint), // in the case of a fingerprint collision we simply treat it as one // series with multiple chunks. - combinedSeriesIter := iter.NewDedupingIter[*Series, *Series]( + combinedSeriesIter := iter.NewDedupingIter( // eq func(s1, s2 *Series) bool { return s1.Fingerprint == s2.Fingerprint @@ -223,7 +221,7 @@ func NewMergeBuilder( Chunks: s1.Chunks.Union(s2.Chunks), } }, - iter.NewPeekIter[*Series](store), + iter.NewPeekIter(store), ) return &MergeBuilder{ @@ -295,7 +293,7 @@ func (mb *MergeBuilder) processNextSeries( chunksCopied += len(nextInStore.Chunks) - len(chunksToAdd) preExistingBlooms = nextInBlocks.Blooms // we also need to carry over existing indexed fields from the series metadata - info.indexedFields.Union(nextInBlocks.Series.Meta.Fields) + info.indexedFields.Union(nextInBlocks.Series.Fields) } chunksIndexed += len(chunksToAdd) diff --git a/pkg/storage/bloom/v1/builder_test.go b/pkg/storage/bloom/v1/builder_test.go index 662c1375809be..a1917bc096a7c 100644 --- a/pkg/storage/bloom/v1/builder_test.go +++ b/pkg/storage/bloom/v1/builder_test.go @@ -42,10 +42,7 @@ func TestBlockOptions_BloomPageSize(t *testing.T) { func TestBlockOptions_RoundTrip(t *testing.T) { t.Parallel() opts := BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, BlockSize: 10 << 20, @@ -100,10 +97,7 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { desc := fmt.Sprintf("%s/%s", tc.desc, enc) t.Run(desc, func(t *testing.T) { blockOpts := BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: enc, - }, + Schema: NewSchema(CurrentSchemaVersion, enc), SeriesPageSize: 100, BloomPageSize: 10 << 10, BlockSize: tc.maxBlockSize, @@ -192,7 +186,7 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { func dedupedBlocks(blocks []iter.PeekIterator[*SeriesWithBlooms]) iter.Iterator[*SeriesWithBlooms] { orderedBlocks := NewHeapIterForSeriesWithBloom(blocks...) - return iter.NewDedupingIter[*SeriesWithBlooms]( + return iter.NewDedupingIter( func(a *SeriesWithBlooms, b *SeriesWithBlooms) bool { return a.Series.Fingerprint == b.Series.Fingerprint }, @@ -203,7 +197,7 @@ func dedupedBlocks(blocks []iter.PeekIterator[*SeriesWithBlooms]) iter.Iterator[ } return b }, - iter.NewPeekIter[*SeriesWithBlooms](orderedBlocks), + iter.NewPeekIter(orderedBlocks), ) } @@ -215,10 +209,7 @@ func TestMergeBuilder(t *testing.T) { blocks := make([]iter.PeekIterator[*SeriesWithBlooms], 0, nBlocks) data, _ := MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) blockOpts := BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, } @@ -244,10 +235,10 @@ func TestMergeBuilder(t *testing.T) { ) require.Nil(t, err) - itr := iter.NewSliceIter[SeriesWithBlooms](data[min:max]) + itr := iter.NewSliceIter(data[min:max]) _, err = builder.BuildFrom(itr) require.Nil(t, err) - blocks = append(blocks, iter.NewPeekIter[*SeriesWithBlooms](NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize).Iter())) + blocks = append(blocks, iter.NewPeekIter(NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize).Iter())) } // We're not testing the ability to extend a bloom in this test @@ -264,8 +255,8 @@ func TestMergeBuilder(t *testing.T) { // storage should contain references to all the series we ingested, // regardless of block allocation/overlap. - storeItr := iter.NewMapIter[SeriesWithBlooms, *Series]( - iter.NewSliceIter[SeriesWithBlooms](data), + storeItr := iter.NewMapIter( + iter.NewSliceIter(data), func(swb SeriesWithBlooms) *Series { return &swb.Series.Series }, @@ -287,16 +278,16 @@ func TestMergeBuilder(t *testing.T) { block := NewBlock(reader, NewMetrics(nil)) querier := NewBlockQuerier(block, &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize) - EqualIterators[*SeriesWithBlooms]( + EqualIterators( t, func(a, b *SeriesWithBlooms) { require.Equal(t, a.Series.Series, b.Series.Series, "expected series %+v, got %+v", a.Series.Series, b.Series.Series) - require.Equal(t, a.Series.Meta.Fields, b.Series.Meta.Fields, "expected fields %+v, got %+v", a.Series.Meta.Fields, b.Series.Meta.Fields) + require.Equal(t, a.Series.Fields, b.Series.Fields, "expected fields %+v, got %+v", a.Series.Fields, b.Series.Fields) // TODO(chaudum): Investigate why offsets not match // This has not been tested before, so I'm not too worried about something being broken. // require.Equal(t, a.Series.Meta.Offsets, b.Series.Meta.Offsets, "expected offsets %+v, got %+v", a.Series.Meta.Offsets, b.Series.Meta.Offsets) }, - iter.NewSliceIter[*SeriesWithBlooms](PointerSlice(data)), + iter.NewSliceIter(PointerSlice(data)), querier.Iter(), ) } @@ -312,10 +303,7 @@ func TestMergeBuilderFingerprintCollision(t *testing.T) { reader := NewByteReader(indexBuf, bloomsBuf) blockOpts := BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, } @@ -409,10 +397,7 @@ func TestBlockReset(t *testing.T) { writer := NewMemoryBlockWriter(indexBuf, bloomsBuf) reader := NewByteReader(indexBuf, bloomsBuf) - schema := Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - } + schema := NewSchema(CurrentSchemaVersion, compression.Snappy) builder, err := NewBlockBuilder( BlockOptions{ @@ -424,7 +409,7 @@ func TestBlockReset(t *testing.T) { ) require.Nil(t, err) - itr := iter.NewSliceIter[SeriesWithBlooms](data) + itr := iter.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) @@ -434,7 +419,7 @@ func TestBlockReset(t *testing.T) { for i := 0; i < len(rounds); i++ { for querier.Next() { - rounds[i] = append(rounds[i], querier.At().Series.Fingerprint) + rounds[i] = append(rounds[i], querier.At().Fingerprint) } err = querier.Seek(0) // reset at end @@ -465,10 +450,9 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { } blockOpts := BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, // test with different encodings? - }, + // test with different encodings? + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), + SeriesPageSize: 100, BloomPageSize: 10 << 10, } @@ -487,7 +471,7 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { require.Nil(t, err) // each set of copies gets a different slice of the data minIdx, maxIdx := i*len(xs)/len(sets), (i+1)*len(xs)/len(sets) - itr := iter.NewSliceIter[SeriesWithBlooms](xs[minIdx:maxIdx]) + itr := iter.NewSliceIter(xs[minIdx:maxIdx]) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) @@ -509,12 +493,12 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { var store []iter.PeekIterator[*SeriesWithBlooms] for _, x := range data { - blocks = append(blocks, iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](x))) - store = append(store, iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](x))) + blocks = append(blocks, iter.NewPeekIter(iter.NewSliceIter(x))) + store = append(store, iter.NewPeekIter(iter.NewSliceIter(x))) } orderedStore := NewHeapIterForSeriesWithBloom(store...) - dedupedStore := iter.NewDedupingIter[*SeriesWithBlooms, *Series]( + dedupedStore := iter.NewDedupingIter( func(a *SeriesWithBlooms, b *Series) bool { return a.Series.Fingerprint == b.Fingerprint }, @@ -527,7 +511,7 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { } return b }, - iter.NewPeekIter[*SeriesWithBlooms](orderedStore), + iter.NewPeekIter(orderedStore), ) // We're not testing the ability to extend a bloom in this test @@ -568,9 +552,9 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { // ensure the new block contains one copy of all the data // by comparing it against an iterator over the source data mergedBlockQuerier := NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize) - sourceItr := iter.NewSliceIter[*SeriesWithBlooms](PointerSlice[SeriesWithBlooms](xs)) + sourceItr := iter.NewSliceIter(PointerSlice(xs)) - EqualIterators[*SeriesWithBlooms]( + EqualIterators( t, func(a, b *SeriesWithBlooms) { require.Equal(t, a.Series.Fingerprint, b.Series.Fingerprint) diff --git a/pkg/storage/bloom/v1/dedupe_test.go b/pkg/storage/bloom/v1/dedupe_test.go index 8c4dd43629b5a..a75c8064030d8 100644 --- a/pkg/storage/bloom/v1/dedupe_test.go +++ b/pkg/storage/bloom/v1/dedupe_test.go @@ -18,7 +18,7 @@ func TestMergeDedupeIter(t *testing.T) { ) for i := 0; i < len(queriers); i++ { - queriers[i] = iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](dataPtr)) + queriers[i] = iter.NewPeekIter(iter.NewSliceIter(dataPtr)) } mbq := NewHeapIterForSeriesWithBloom(queriers...) @@ -28,11 +28,11 @@ func TestMergeDedupeIter(t *testing.T) { merge := func(a, _ *SeriesWithBlooms) *SeriesWithBlooms { return a } - deduper := iter.NewDedupingIter[*SeriesWithBlooms, *SeriesWithBlooms]( + deduper := iter.NewDedupingIter( eq, iter.Identity[*SeriesWithBlooms], merge, - iter.NewPeekIter[*SeriesWithBlooms](mbq), + iter.NewPeekIter(mbq), ) for i := 0; i < len(data); i++ { diff --git a/pkg/storage/bloom/v1/filter/buckets.go b/pkg/storage/bloom/v1/filter/buckets.go index 95c55f394e1fa..89836ba441610 100644 --- a/pkg/storage/bloom/v1/filter/buckets.go +++ b/pkg/storage/bloom/v1/filter/buckets.go @@ -17,10 +17,6 @@ import ( "math/bits" ) -type BucketGetter interface { - Get(bucket uint) uint32 -} - // Buckets is a fast, space-efficient array of buckets where each bucket can // store up to a configured maximum value. type Buckets struct { diff --git a/pkg/storage/bloom/v1/filter/scalable.go b/pkg/storage/bloom/v1/filter/scalable.go index 3e59a99b011f9..bc3b84a271a83 100644 --- a/pkg/storage/bloom/v1/filter/scalable.go +++ b/pkg/storage/bloom/v1/filter/scalable.go @@ -71,9 +71,7 @@ type ScalableBloomFilter struct { const fillCheckFraction = 100 // NewScalableBloomFilter creates a new Scalable Bloom Filter with the -// specified target false-positive rate and tightening ratio. Use -// NewDefaultScalableBloomFilter if you don't want to calculate these -// parameters. +// specified target false-positive rate and tightening ratio. func NewScalableBloomFilter(hint uint, fpRate, r float64) *ScalableBloomFilter { s := &ScalableBloomFilter{ filters: make([]*PartitionedBloomFilter, 0, 1), @@ -88,11 +86,6 @@ func NewScalableBloomFilter(hint uint, fpRate, r float64) *ScalableBloomFilter { return s } -// NewDefaultScalableBloomFilter creates a new Scalable Bloom Filter. -func NewDefaultScalableBloomFilter() *ScalableBloomFilter { - return NewScalableBloomFilter(10e3, 0.1, 0.8) -} - // Capacity returns the current Scalable Bloom Filter capacity, which is the // sum of the capacities for the contained series of Bloom filters. func (s *ScalableBloomFilter) Capacity() uint { @@ -210,14 +203,6 @@ func (s *ScalableBloomFilter) TestAndAddWithMaxSize(data []byte, maxSize int) (e return member, full } -// Reset restores the Bloom filter to its original state. It returns the filter -// to allow for chaining. -func (s *ScalableBloomFilter) Reset() *ScalableBloomFilter { - s.filters = make([]*PartitionedBloomFilter, 0, 1) - s.addFilter() - return s -} - func (s *ScalableBloomFilter) nextFilterCapacity() (m uint, fpRate float64) { fpRate = s.fp * math.Pow(s.r, float64(len(s.filters))) diff --git a/pkg/storage/bloom/v1/filter/scalable_test.go b/pkg/storage/bloom/v1/filter/scalable_test.go index 2456277f2e93a..bf46bfba4ec16 100644 --- a/pkg/storage/bloom/v1/filter/scalable_test.go +++ b/pkg/storage/bloom/v1/filter/scalable_test.go @@ -17,24 +17,6 @@ import ( "github.com/d4l3k/messagediff" ) -// Ensures that NewDefaultScalableBloomFilter creates a Scalable Bloom Filter -// with hint = 10000 and r = 0.8. -func TestNewDefaultScalableBloomFilter(t *testing.T) { - f := NewDefaultScalableBloomFilter() - - if f.fp != 0.1 { - t.Errorf("Expected 0.1, got %f", f.fp) - } - - if f.hint != 10000 { - t.Errorf("Expected 10000, got %d", f.hint) - } - - if f.r != 0.8 { - t.Errorf("Expected 0.8, got %f", f.r) - } -} - // Ensures that K returns the number of hash functions used in each Bloom // filter. func TestScalableBloomK(t *testing.T) { @@ -111,34 +93,6 @@ func TestScalableBloomTestAndAdd(t *testing.T) { } } -// Ensures that Reset removes all Bloom filters and resets the initial one. -func TestScalableBloomReset(t *testing.T) { - f := NewScalableBloomFilter(10, 0.1, 0.8) - for i := 0; i < 1000; i++ { - f.Add([]byte(strconv.Itoa(i))) - } - - if len(f.filters) < 2 { - t.Errorf("Expected more than 1 filter, got %d", len(f.filters)) - } - - if f.Reset() != f { - t.Error("Returned ScalableBloomFilter should be the same instance") - } - - if len(f.filters) != 1 { - t.Errorf("Expected 1 filter, got %d", len(f.filters)) - } - - for _, partition := range f.filters[0].partitions { - for i := uint(0); i < partition.Count(); i++ { - if partition.Get(i) != 0 { - t.Error("Expected all bits to be unset") - } - } - } -} - // Ensures that ScalableBloomFilter can be serialized and deserialized without errors. func TestScalableBloomGob(t *testing.T) { f := NewScalableBloomFilter(10, 0.1, 0.8) diff --git a/pkg/storage/bloom/v1/fuse.go b/pkg/storage/bloom/v1/fuse.go index f579ce6527849..147a81502c336 100644 --- a/pkg/storage/bloom/v1/fuse.go +++ b/pkg/storage/bloom/v1/fuse.go @@ -137,14 +137,14 @@ type FusedQuerier struct { } func NewFusedQuerier(bq *BlockQuerier, inputs []iter.PeekIterator[Request], logger log.Logger) *FusedQuerier { - heap := NewHeapIterator[Request]( + heap := NewHeapIterator( func(a, b Request) bool { return a.Fp < b.Fp }, inputs..., ) - merging := iter.NewDedupingIter[Request, []Request]( + merging := iter.NewDedupingIter( func(a Request, b []Request) bool { return a.Fp == b[0].Fp }, @@ -152,7 +152,7 @@ func NewFusedQuerier(bq *BlockQuerier, inputs []iter.PeekIterator[Request], logg func(a Request, b []Request) []Request { return append(b, a) }, - iter.NewPeekIter[Request](heap), + iter.NewPeekIter(heap), ) return &FusedQuerier{ bq: bq, @@ -263,9 +263,10 @@ func (fq *FusedQuerier) runSeries(_ Schema, series *SeriesWithMeta, reqs []Reque Missing ChunkRefs // chunks that do not exist in the blooms and cannot be queried InBlooms ChunkRefs // chunks which do exist in the blooms and can be queried - found map[int]bool // map of the index in `InBlooms` to whether the chunk - // was found in _any_ of the blooms for the series. In order to - // be eligible for removal, a chunk must be found in _no_ blooms. + // Map of the index in `InBlooms` to whether the chunk was found in _any_ + // of the blooms for the series. In order to be eligible for removal, a + // chunk must be found in _no_ blooms. + found map[int]bool } inputs := make([]inputChunks, 0, len(reqs)) @@ -354,7 +355,6 @@ func (fq *FusedQuerier) runSeries(_ Schema, series *SeriesWithMeta, reqs []Reque } for i, req := range reqs { - removals := removalsFor(inputs[i].InBlooms, inputs[i].found) req.Recorder.record( diff --git a/pkg/storage/bloom/v1/fuse_test.go b/pkg/storage/bloom/v1/fuse_test.go index 4a22b91e70099..3283dc6ccdb59 100644 --- a/pkg/storage/bloom/v1/fuse_test.go +++ b/pkg/storage/bloom/v1/fuse_test.go @@ -58,17 +58,14 @@ func TestFusedQuerier(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, }, writer, ) require.Nil(t, err) - itr := v2.NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.NoError(t, err) require.False(t, itr.Next()) @@ -99,7 +96,7 @@ func TestFusedQuerier(t *testing.T) { var itrs []v2.PeekIterator[Request] for _, reqs := range inputs { - itrs = append(itrs, v2.NewPeekIter[Request](v2.NewSliceIter[Request](reqs))) + itrs = append(itrs, v2.NewPeekIter(v2.NewSliceIter(reqs))) } resps := make([][]Output, nReqs) @@ -145,10 +142,7 @@ func TestFusedQuerier_MultiPage(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10, // So we force one bloom per page }, @@ -294,17 +288,14 @@ func TestLazyBloomIter_Seek_ResetError(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10, // So we force one series per page }, writer, ) require.Nil(t, err) - itr := v2.NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.NoError(t, err) require.False(t, itr.Next()) @@ -352,10 +343,7 @@ func TestFusedQuerier_SkipsEmptyBlooms(t *testing.T) { builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.None, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, }, @@ -379,7 +367,7 @@ func TestFusedQuerier_SkipsEmptyBlooms(t *testing.T) { Blooms: v2.NewSliceIter([]*Bloom{NewBloom()}), } - itr := v2.NewSliceIter[SeriesWithBlooms]([]SeriesWithBlooms{data}) + itr := v2.NewSliceIter([]SeriesWithBlooms{data}) _, err = builder.BuildFrom(itr) require.NoError(t, err) require.False(t, itr.Next()) @@ -394,7 +382,7 @@ func TestFusedQuerier_SkipsEmptyBlooms(t *testing.T) { } err = NewBlockQuerier(block, BloomPagePool, DefaultMaxPageSize).Fuse( []v2.PeekIterator[Request]{ - v2.NewPeekIter[Request](v2.NewSliceIter[Request]([]Request{req})), + v2.NewPeekIter(v2.NewSliceIter([]Request{req})), }, log.NewNopLogger(), ).Run() @@ -413,17 +401,14 @@ func setupBlockForBenchmark(b *testing.B) (*BlockQuerier, [][]Request, []chan Ou builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 256 << 10, // 256k BloomPageSize: 1 << 20, // 1MB }, writer, ) require.Nil(b, err) - itr := v2.NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.Nil(b, err) block := NewBlock(reader, NewMetrics(nil)) @@ -485,7 +470,7 @@ func BenchmarkBlockQuerying(b *testing.B) { for i := 0; i < b.N; i++ { itrs = itrs[:0] for _, reqs := range requestChains { - itrs = append(itrs, v2.NewPeekIter[Request](v2.NewSliceIter[Request](reqs))) + itrs = append(itrs, v2.NewPeekIter(v2.NewSliceIter(reqs))) } fused := querier.Fuse(itrs, log.NewNopLogger()) _ = fused.Run() diff --git a/pkg/storage/bloom/v1/index_querier.go b/pkg/storage/bloom/v1/index_querier.go index fe05f7bcddfda..cd1f548978169 100644 --- a/pkg/storage/bloom/v1/index_querier.go +++ b/pkg/storage/bloom/v1/index_querier.go @@ -5,15 +5,8 @@ import ( "github.com/efficientgo/core/errors" "github.com/prometheus/common/model" - - iter "github.com/grafana/loki/v3/pkg/iter/v2" ) -type SeriesIterator interface { - iter.Iterator[*SeriesWithMeta] - Reset() -} - type LazySeriesIter struct { b *Block diff --git a/pkg/storage/bloom/v1/merge.go b/pkg/storage/bloom/v1/merge.go index 0e94d0d506408..53348dcf333cd 100644 --- a/pkg/storage/bloom/v1/merge.go +++ b/pkg/storage/bloom/v1/merge.go @@ -69,11 +69,6 @@ func (mbq *HeapIterator[T]) At() T { return mbq.cache } -func (mbq *HeapIterator[T]) push(x iter.PeekIterator[T]) { - mbq.itrs = append(mbq.itrs, x) - mbq.up(mbq.Len() - 1) -} - func (mbq *HeapIterator[T]) pop() (T, bool) { for { if mbq.Len() == 0 { diff --git a/pkg/storage/bloom/v1/merge_test.go b/pkg/storage/bloom/v1/merge_test.go index f57c629d75429..9256cdf9b8252 100644 --- a/pkg/storage/bloom/v1/merge_test.go +++ b/pkg/storage/bloom/v1/merge_test.go @@ -21,7 +21,7 @@ func TestMergeBlockQuerier_NonOverlapping(t *testing.T) { for j := 0; j < numSeries/numQueriers; j++ { ptrs = append(ptrs, &data[i*numSeries/numQueriers+j]) } - queriers = append(queriers, v2.NewPeekIter[*SeriesWithBlooms](v2.NewSliceIter[*SeriesWithBlooms](ptrs))) + queriers = append(queriers, v2.NewPeekIter(v2.NewSliceIter(ptrs))) } mbq := NewHeapIterForSeriesWithBloom(queriers...) @@ -46,11 +46,7 @@ func TestMergeBlockQuerier_Duplicate(t *testing.T) { for i := 0; i < numQueriers; i++ { queriers = append( queriers, - v2.NewPeekIter[*SeriesWithBlooms]( - v2.NewSliceIter[*SeriesWithBlooms]( - PointerSlice[SeriesWithBlooms](data), - ), - ), + v2.NewPeekIter(v2.NewSliceIter(PointerSlice(data))), ) } @@ -79,7 +75,7 @@ func TestMergeBlockQuerier_Overlapping(t *testing.T) { slices[i%numQueriers] = append(slices[i%numQueriers], &data[i]) } for i := 0; i < numQueriers; i++ { - queriers = append(queriers, v2.NewPeekIter[*SeriesWithBlooms](v2.NewSliceIter[*SeriesWithBlooms](slices[i]))) + queriers = append(queriers, v2.NewPeekIter(v2.NewSliceIter(slices[i]))) } mbq := NewHeapIterForSeriesWithBloom(queriers...) diff --git a/pkg/storage/bloom/v1/reader.go b/pkg/storage/bloom/v1/reader.go index d589aa19c4927..245ead867ff1d 100644 --- a/pkg/storage/bloom/v1/reader.go +++ b/pkg/storage/bloom/v1/reader.go @@ -61,7 +61,7 @@ func (r *ByteReader) TarEntries() (iter.Iterator[TarEntry], error) { }, } - return iter.NewSliceIter[TarEntry](entries), err + return iter.NewSliceIter(entries), err } func (r *ByteReader) Cleanup() error { @@ -162,7 +162,7 @@ func (r *DirectoryBlockReader) TarEntries() (iter.Iterator[TarEntry], error) { }, } - return iter.NewSliceIter[TarEntry](entries), nil + return iter.NewSliceIter(entries), nil } func (r *DirectoryBlockReader) Cleanup() error { diff --git a/pkg/storage/bloom/v1/schema.go b/pkg/storage/bloom/v1/schema.go index 7c0271434b2b4..0a7e2881a3a3f 100644 --- a/pkg/storage/bloom/v1/schema.go +++ b/pkg/storage/bloom/v1/schema.go @@ -33,7 +33,6 @@ const ( var ( SupportedVersions = []Version{V3} - ErrInvalidSchemaVersion = errors.New("invalid schema version") ErrUnsupportedSchemaVersion = errors.New("unsupported schema version") ) @@ -42,10 +41,10 @@ type Schema struct { encoding compression.Codec } -func NewSchema() Schema { +func NewSchema(version Version, encoding compression.Codec) Schema { return Schema{ - version: CurrentSchemaVersion, - encoding: compression.None, + version: version, + encoding: encoding, } } @@ -80,7 +79,6 @@ func (s *Schema) Encode(enc *encoding.Encbuf) { enc.PutBE32(magicNumber) enc.PutByte(byte(s.version)) enc.PutByte(byte(s.encoding)) - } func (s *Schema) DecodeFrom(r io.ReadSeeker) error { diff --git a/pkg/storage/bloom/v1/test_util.go b/pkg/storage/bloom/v1/test_util.go index 4d036ba4809df..c2f1f3e8f8d30 100644 --- a/pkg/storage/bloom/v1/test_util.go +++ b/pkg/storage/bloom/v1/test_util.go @@ -28,17 +28,14 @@ func MakeBlock(t testing.TB, nth int, fromFp, throughFp model.Fingerprint, fromT builder, err := NewBlockBuilder( BlockOptions{ - Schema: Schema{ - version: CurrentSchemaVersion, - encoding: compression.Snappy, - }, + Schema: NewSchema(CurrentSchemaVersion, compression.Snappy), SeriesPageSize: 100, BloomPageSize: 10 << 10, }, writer, ) require.Nil(t, err) - itr := iter.NewSliceIter[SeriesWithBlooms](data) + itr := iter.NewSliceIter(data) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) diff --git a/pkg/storage/bloom/v1/util.go b/pkg/storage/bloom/v1/util.go index 6745ccaec7c61..31a51d8d2e862 100644 --- a/pkg/storage/bloom/v1/util.go +++ b/pkg/storage/bloom/v1/util.go @@ -26,10 +26,6 @@ var ( SeriesPagePool = mempool.NewBytePoolAllocator(1<<10, 128<<10, 2) ) -func newCRC32() hash.Hash32 { - return crc32.New(castagnoliTable) -} - type ChecksumPool struct { sync.Pool } diff --git a/pkg/storage/bloom/v1/versioned_builder.go b/pkg/storage/bloom/v1/versioned_builder.go index 4f1881c441e70..8844ddf43eb11 100644 --- a/pkg/storage/bloom/v1/versioned_builder.go +++ b/pkg/storage/bloom/v1/versioned_builder.go @@ -81,7 +81,7 @@ func (b *V3Builder) BuildFrom(itr iter.Iterator[SeriesWithBlooms]) (uint32, erro return 0, errors.Wrap(err, "iterating blooms") } - blockFull, err := b.AddSeries(at.Series.Series, offsets, at.Series.Meta.Fields) + blockFull, err := b.AddSeries(at.Series.Series, offsets, at.Series.Fields) if err != nil { return 0, errors.Wrapf(err, "writing series") } diff --git a/pkg/storage/bloom/v1/versioned_builder_test.go b/pkg/storage/bloom/v1/versioned_builder_test.go index 9154daf77fc77..1e4a0f5a93b26 100644 --- a/pkg/storage/bloom/v1/versioned_builder_test.go +++ b/pkg/storage/bloom/v1/versioned_builder_test.go @@ -16,10 +16,7 @@ import ( // characterized by small page sizes func smallBlockOpts(v Version, enc compression.Codec) BlockOptions { return BlockOptions{ - Schema: Schema{ - version: v, - encoding: enc, - }, + Schema: NewSchema(v, enc), SeriesPageSize: 100, BloomPageSize: 2 << 10, BlockSize: 0, // unlimited @@ -55,11 +52,11 @@ func TestV3Roundtrip(t *testing.T) { block := NewBlock(reader, NewMetrics(nil)) querier := NewBlockQuerier(block, &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize).Iter() - CompareIterators[SeriesWithBlooms, *SeriesWithBlooms]( + CompareIterators( t, func(t *testing.T, a SeriesWithBlooms, b *SeriesWithBlooms) { - require.Equal(t, a.Series.Series.Fingerprint, b.Series.Series.Fingerprint) - require.ElementsMatch(t, a.Series.Series.Chunks, b.Series.Series.Chunks) + require.Equal(t, a.Series.Fingerprint, b.Series.Fingerprint) + require.ElementsMatch(t, a.Series.Chunks, b.Series.Chunks) bloomsA, err := v2.Collect(a.Blooms) require.NoError(t, err) bloomsB, err := v2.Collect(b.Blooms) diff --git a/pkg/storage/chunk/cache/resultscache/cache.go b/pkg/storage/chunk/cache/resultscache/cache.go index 0dfc4d49aae0a..974036f940e0c 100644 --- a/pkg/storage/chunk/cache/resultscache/cache.go +++ b/pkg/storage/chunk/cache/resultscache/cache.go @@ -289,10 +289,10 @@ func merge(extents []Extent, acc *accumulator) ([]Extent, error) { return nil, err } return append(extents, Extent{ - Start: acc.Extent.Start, - End: acc.Extent.End, + Start: acc.Start, + End: acc.End, Response: anyResp, - TraceId: acc.Extent.TraceId, + TraceId: acc.TraceId, }), nil } @@ -386,7 +386,7 @@ func (s ResultsCache) partition(req Request, extents []Extent) ([]Request, []Res // If start and end are the same (valid in promql), start == req.GetEnd() and we won't do the query. // But we should only do the request if we don't have a valid cached response for it. - if req.GetStart() == req.GetEnd() && len(cachedResponses) == 0 { + if req.GetStart().Equal(req.GetEnd()) && len(cachedResponses) == 0 { requests = append(requests, req) }
chore
remove unused code from blooms (#14539)
13a6c33e32565fcf689f06516fb842681b5ac36e
2025-02-14 02:49:31
Cyril Tovena
feat(dataob): Implement SelectSamples (#16251)
false
diff --git a/pkg/dataobj/querier/iter.go b/pkg/dataobj/querier/iter.go new file mode 100644 index 0000000000000..cf370edbd9dc6 --- /dev/null +++ b/pkg/dataobj/querier/iter.go @@ -0,0 +1,137 @@ +package querier + +import ( + "context" + "io" + "sync" + + "github.com/grafana/loki/v3/pkg/dataobj" + "github.com/grafana/loki/v3/pkg/iter" + "github.com/grafana/loki/v3/pkg/logproto" + "github.com/grafana/loki/v3/pkg/logql/log" + "github.com/grafana/loki/v3/pkg/logql/syntax" +) + +var ( + recordsPool = sync.Pool{ + New: func() interface{} { + records := make([]dataobj.Record, 1024) + return &records + }, + } + samplesPool = sync.Pool{ + New: func() interface{} { + samples := make([]logproto.Sample, 0, 1024) + return &samples + }, + } +) + +func newSampleIterator(ctx context.Context, + streams map[int64]dataobj.Stream, + extractor syntax.SampleExtractor, + reader *dataobj.LogsReader, +) (iter.SampleIterator, error) { + bufPtr := recordsPool.Get().(*[]dataobj.Record) + defer recordsPool.Put(bufPtr) + buf := *bufPtr + + var ( + iterators []iter.SampleIterator + prevStreamID int64 = -1 + streamExtractor log.StreamSampleExtractor + series = map[string]*logproto.Series{} + streamHash uint64 + ) + + for { + n, err := reader.Read(ctx, buf) + if err != nil && err != io.EOF { + return nil, err + } + + // Handle end of stream or empty read + if n == 0 { + iterators = appendIteratorFromSeries(iterators, series) + break + } + + // Process records in the current batch + for _, record := range buf[:n] { + stream, ok := streams[record.StreamID] + if !ok { + continue + } + + // Handle stream transition + if prevStreamID != record.StreamID { + iterators = appendIteratorFromSeries(iterators, series) + clear(series) + streamExtractor = extractor.ForStream(stream.Labels) + streamHash = streamExtractor.BaseLabels().Hash() + prevStreamID = record.StreamID + } + + // Process the record + timestamp := record.Timestamp.UnixNano() + value, parsedLabels, ok := streamExtractor.ProcessString(timestamp, record.Line, record.Metadata...) + if !ok { + continue + } + + // Get or create series for the parsed labels + labelString := parsedLabels.String() + s, exists := series[labelString] + if !exists { + s = createNewSeries(labelString, streamHash) + series[labelString] = s + } + + // Add sample to the series + s.Samples = append(s.Samples, logproto.Sample{ + Timestamp: timestamp, + Value: value, + Hash: 0, // todo write a test to verify that we should not try to dedupe when we don't have a hash + }) + } + } + + if len(iterators) == 0 { + return iter.NoopSampleIterator, nil + } + + return iter.NewSortSampleIterator(iterators), nil +} + +// createNewSeries creates a new Series for the given labels and stream hash +func createNewSeries(labels string, streamHash uint64) *logproto.Series { + samplesPtr := samplesPool.Get().(*[]logproto.Sample) + samples := *samplesPtr + return &logproto.Series{ + Labels: labels, + Samples: samples[:0], + StreamHash: streamHash, + } +} + +// appendIteratorFromSeries appends a new SampleIterator to the given list of iterators +func appendIteratorFromSeries(iterators []iter.SampleIterator, series map[string]*logproto.Series) []iter.SampleIterator { + if len(series) == 0 { + return iterators + } + + seriesResult := make([]logproto.Series, 0, len(series)) + for _, s := range series { + seriesResult = append(seriesResult, *s) + } + + return append(iterators, iter.SampleIteratorWithClose( + iter.NewMultiSeriesIterator(seriesResult), + func() error { + for _, s := range seriesResult { + samplesPool.Put(&s.Samples) + } + return nil + }, + )) +} diff --git a/pkg/dataobj/querier/metadata.go b/pkg/dataobj/querier/metadata.go index eccb4afd3c991..4b3d0f49c0f48 100644 --- a/pkg/dataobj/querier/metadata.go +++ b/pkg/dataobj/querier/metadata.go @@ -17,6 +17,13 @@ import ( "github.com/grafana/loki/v3/pkg/logql" ) +var streamsPool = sync.Pool{ + New: func() any { + streams := make([]dataobj.Stream, 1024) + return &streams + }, +} + // SelectSeries implements querier.Store func (s *Store) SelectSeries(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) { objects, err := s.objectsForTimeRange(ctx, req.Start, req.End) @@ -129,13 +136,6 @@ func (s *Store) LabelValuesForMetricName(ctx context.Context, _ string, from, th return values, nil } -var streamsPool = sync.Pool{ - New: func() any { - streams := make([]dataobj.Stream, 1024) - return &streams - }, -} - // streamProcessor handles processing of unique series with custom collection logic type streamProcessor struct { predicate dataobj.StreamsPredicate @@ -146,61 +146,25 @@ type streamProcessor struct { // newStreamProcessor creates a new streamProcessor with the given parameters func newStreamProcessor(start, end time.Time, matchers []*labels.Matcher, objects []*dataobj.Object, shard logql.Shard) *streamProcessor { - // Create a time range predicate - var predicate dataobj.StreamsPredicate = dataobj.TimeRangePredicate[dataobj.StreamsPredicate]{ - StartTime: start, - EndTime: end, - IncludeStart: true, - IncludeEnd: true, - } - - // If there are any matchers, combine them with an AND predicate - if len(matchers) > 0 { - predicate = dataobj.AndPredicate[dataobj.StreamsPredicate]{ - Left: predicate, - Right: matchersToPredicate(matchers), - } - } - return &streamProcessor{ - predicate: predicate, + predicate: streamPredicate(matchers, start, end), seenSeries: &sync.Map{}, objects: objects, shard: shard, } } -// matchersToPredicate converts a list of matchers to a dataobj.StreamsPredicate -func matchersToPredicate(matchers []*labels.Matcher) dataobj.StreamsPredicate { - var left dataobj.StreamsPredicate - for _, matcher := range matchers { - var right dataobj.StreamsPredicate - switch matcher.Type { - case labels.MatchEqual: - right = dataobj.LabelMatcherPredicate{Name: matcher.Name, Value: matcher.Value} - default: - right = dataobj.LabelFilterPredicate{Name: matcher.Name, Keep: func(_, value string) bool { - return matcher.Matches(value) - }} - } - if left == nil { - left = right - } else { - left = dataobj.AndPredicate[dataobj.StreamsPredicate]{ - Left: left, - Right: right, - } - } - } - return left -} - // ProcessParallel processes series from multiple readers in parallel func (sp *streamProcessor) ProcessParallel(ctx context.Context, onNewStream func(uint64, dataobj.Stream)) error { readers, err := shardStreamReaders(ctx, sp.objects, sp.shard) if err != nil { return err } + defer func() { + for _, reader := range readers { + streamReaderPool.Put(reader) + } + }() // set predicate on all readers for _, reader := range readers { @@ -263,17 +227,8 @@ func labelsToSeriesIdentifier(labels labels.Labels) logproto.SeriesIdentifier { // shardStreamReaders fetches metadata of objects in parallel and shards them into a list of StreamsReaders func shardStreamReaders(ctx context.Context, objects []*dataobj.Object, shard logql.Shard) ([]*dataobj.StreamsReader, error) { - // fetch all metadata of objects in parallel - g, ctx := errgroup.WithContext(ctx) - metadatas := make([]dataobj.Metadata, len(objects)) - for i, obj := range objects { - g.Go(func() error { - var err error - metadatas[i], err = obj.Metadata(ctx) - return err - }) - } - if err := g.Wait(); err != nil { + metadatas, err := fetchMetadatas(ctx, objects) + if err != nil { return nil, err } // sectionIndex tracks the global section number across all objects to ensure consistent sharding @@ -289,7 +244,8 @@ func shardStreamReaders(ctx context.Context, objects []*dataobj.Object, shard lo continue } } - reader := dataobj.NewStreamsReader(objects[i], j) + reader := streamReaderPool.Get().(*dataobj.StreamsReader) + reader.Reset(objects[i], j) readers = append(readers, reader) sectionIndex++ } diff --git a/pkg/dataobj/querier/metadata_test.go b/pkg/dataobj/querier/metadata_test.go new file mode 100644 index 0000000000000..dc61297540621 --- /dev/null +++ b/pkg/dataobj/querier/metadata_test.go @@ -0,0 +1,323 @@ +package querier + +import ( + "context" + "sort" + "testing" + "time" + + "github.com/grafana/dskit/user" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/labels" + "github.com/stretchr/testify/require" + + "github.com/grafana/loki/v3/pkg/logproto" + "github.com/grafana/loki/v3/pkg/logql" +) + +func TestStore_SelectSeries(t *testing.T) { + const testTenant = "test-tenant" + builder := newTestDataBuilder(t, testTenant) + defer builder.close() + + // Setup test data + now := setupTestData(t, builder) + + store := NewStore(builder.bucket) + ctx := user.InjectOrgID(context.Background(), testTenant) + + tests := []struct { + name string + selector string + want []string + }{ + { + name: "select all series", + selector: ``, + want: []string{ + `{app="foo", env="prod"}`, + `{app="foo", env="dev"}`, + `{app="bar", env="prod"}`, + `{app="bar", env="dev"}`, + `{app="baz", env="prod", team="a"}`, + }, + }, + { + name: "select with equality matcher", + selector: `{app="foo"}`, + want: []string{ + `{app="foo", env="prod"}`, + `{app="foo", env="dev"}`, + }, + }, + { + name: "select with regex matcher", + selector: `{app=~"foo|bar"}`, + want: []string{ + `{app="foo", env="prod"}`, + `{app="foo", env="dev"}`, + `{app="bar", env="prod"}`, + `{app="bar", env="dev"}`, + }, + }, + { + name: "select with negative equality matcher", + selector: `{app=~".+", app!="foo"}`, + want: []string{ + `{app="bar", env="prod"}`, + `{app="bar", env="dev"}`, + `{app="baz", env="prod", team="a"}`, + }, + }, + { + name: "select with negative regex matcher", + selector: `{app=~".+", app!~"foo|bar"}`, + want: []string{ + `{app="baz", env="prod", team="a"}`, + }, + }, + { + name: "select with multiple matchers", + selector: `{app="foo", env="prod"}`, + want: []string{ + `{app="foo", env="prod"}`, + }, + }, + { + name: "select with regex and equality matchers", + selector: `{app=~"foo|bar", env="prod"}`, + want: []string{ + `{app="foo", env="prod"}`, + `{app="bar", env="prod"}`, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + series, err := store.SelectSeries(ctx, logql.SelectLogParams{ + QueryRequest: &logproto.QueryRequest{ + Start: now.Add(-time.Hour), + End: now.Add(time.Hour), + Plan: planFromString(tt.selector), + Selector: tt.selector, + }, + }) + require.NoError(t, err) + + var got []string + for _, s := range series { + got = append(got, labelsFromSeriesID(s)) + } + require.ElementsMatch(t, tt.want, got) + }) + } + + t.Run("sharding", func(t *testing.T) { + // Query first shard + series1, err := store.SelectSeries(ctx, logql.SelectLogParams{ + QueryRequest: &logproto.QueryRequest{ + Start: now.Add(-time.Hour), + End: now.Add(time.Hour), + Plan: planFromString(`{app=~"foo|bar|baz"}`), + Selector: `{app=~"foo|bar|baz"}`, + Shards: []string{"0_of_2"}, + }, + }) + require.NoError(t, err) + require.NotEmpty(t, series1) + require.Less(t, len(series1), 5) // Should get less than all series + + // Query second shard + series2, err := store.SelectSeries(ctx, logql.SelectLogParams{ + QueryRequest: &logproto.QueryRequest{ + Start: now.Add(-time.Hour), + End: now.Add(time.Hour), + Plan: planFromString(`{app=~"foo|bar|baz"}`), + Selector: `{app=~"foo|bar|baz"}`, + Shards: []string{"1_of_2"}, + }, + }) + require.NoError(t, err) + require.NotEmpty(t, series2) + + // Combined shards should equal all series + var allSeries []string + for _, s := range append(series1, series2...) { + allSeries = append(allSeries, labelsFromSeriesID(s)) + } + + want := []string{ + `{app="foo", env="prod"}`, + `{app="foo", env="dev"}`, + `{app="bar", env="prod"}`, + `{app="bar", env="dev"}`, + `{app="baz", env="prod", team="a"}`, + } + require.ElementsMatch(t, want, allSeries) + }) +} + +func TestStore_LabelNamesForMetricName(t *testing.T) { + const testTenant = "test-tenant" + builder := newTestDataBuilder(t, testTenant) + defer builder.close() + + // Setup test data + now := setupTestData(t, builder) + + store := NewStore(builder.bucket) + ctx := user.InjectOrgID(context.Background(), testTenant) + + tests := []struct { + name string + matchers []*labels.Matcher + want []string + }{ + { + name: "no matchers", + matchers: nil, + want: []string{"app", "env", "team"}, + }, + { + name: "with equality matcher", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), + }, + want: []string{"app", "env"}, + }, + { + name: "with regex matcher", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchRegexp, "app", "foo|bar"), + }, + want: []string{"app", "env"}, + }, + { + name: "with negative matcher", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchNotEqual, "app", "foo"), + }, + want: []string{"app", "env", "team"}, + }, + { + name: "with negative regex matcher", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchNotRegexp, "app", "foo|bar"), + }, + want: []string{"app", "env", "team"}, + }, + { + name: "with multiple matchers", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), + labels.MustNewMatcher(labels.MatchEqual, "env", "prod"), + }, + want: []string{"app", "env"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + names, err := store.LabelNamesForMetricName(ctx, "", model.TimeFromUnixNano(now.Add(-time.Hour).UnixNano()), model.TimeFromUnixNano(now.Add(time.Hour).UnixNano()), "", tt.matchers...) + require.NoError(t, err) + require.ElementsMatch(t, tt.want, names) + }) + } +} + +func TestStore_LabelValuesForMetricName(t *testing.T) { + const testTenant = "test-tenant" + builder := newTestDataBuilder(t, testTenant) + defer builder.close() + + // Setup test data + now := setupTestData(t, builder) + + store := NewStore(builder.bucket) + ctx := user.InjectOrgID(context.Background(), testTenant) + + tests := []struct { + name string + labelName string + matchers []*labels.Matcher + want []string + }{ + { + name: "app label without matchers", + labelName: "app", + matchers: nil, + want: []string{"bar", "baz", "foo"}, + }, + { + name: "env label without matchers", + labelName: "env", + matchers: nil, + want: []string{"dev", "prod"}, + }, + { + name: "team label without matchers", + labelName: "team", + matchers: nil, + want: []string{"a"}, + }, + { + name: "env label with app equality matcher", + labelName: "env", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), + }, + want: []string{"dev", "prod"}, + }, + { + name: "env label with app regex matcher", + labelName: "env", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchRegexp, "app", "foo|bar"), + }, + want: []string{"dev", "prod"}, + }, + { + name: "env label with app negative matcher", + labelName: "env", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchNotEqual, "app", "foo"), + }, + want: []string{"dev", "prod"}, + }, + { + name: "env label with app negative regex matcher", + labelName: "env", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchNotRegexp, "app", "foo|bar"), + }, + want: []string{"prod"}, + }, + { + name: "env label with multiple matchers", + labelName: "env", + matchers: []*labels.Matcher{ + labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), + labels.MustNewMatcher(labels.MatchEqual, "env", "prod"), + }, + want: []string{"prod"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + values, err := store.LabelValuesForMetricName(ctx, "", model.TimeFromUnixNano(now.Add(-time.Hour).UnixNano()), model.TimeFromUnixNano(now.Add(time.Hour).UnixNano()), "", tt.labelName, tt.matchers...) + require.NoError(t, err) + require.Equal(t, tt.want, values) + }) + } +} + +func labelsFromSeriesID(id logproto.SeriesIdentifier) string { + ls := make(labels.Labels, 0, len(id.Labels)) + for _, l := range id.Labels { + ls = append(ls, labels.Label{Name: l.Key, Value: l.Value}) + } + sort.Sort(ls) + return ls.String() +} diff --git a/pkg/dataobj/querier/store.go b/pkg/dataobj/querier/store.go index 65e7b6d0749b4..9d5a43c2cff47 100644 --- a/pkg/dataobj/querier/store.go +++ b/pkg/dataobj/querier/store.go @@ -4,18 +4,23 @@ import ( "context" "flag" "fmt" + "io" + "slices" + "sync" "time" "github.com/grafana/dskit/tenant" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" "github.com/thanos-io/objstore" + "golang.org/x/sync/errgroup" "github.com/grafana/loki/v3/pkg/dataobj" "github.com/grafana/loki/v3/pkg/dataobj/metastore" "github.com/grafana/loki/v3/pkg/iter" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql" + "github.com/grafana/loki/v3/pkg/logql/syntax" "github.com/grafana/loki/v3/pkg/querier" "github.com/grafana/loki/v3/pkg/storage/chunk" storageconfig "github.com/grafana/loki/v3/pkg/storage/config" @@ -23,7 +28,36 @@ import ( "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" ) -var _ querier.Store = &Store{} +var ( + _ querier.Store = &Store{} + + noShard = logql.Shard{ + PowerOfTwo: &index.ShardAnnotation{ + Shard: uint32(0), + Of: uint32(1), + }, + } + + shardedObjectsPool = sync.Pool{ + New: func() any { + return &shardedObject{ + streams: make(map[int64]dataobj.Stream), + streamsIDs: make([]int64, 0, 1024), + logReaders: make([]*dataobj.LogsReader, 0, 16), + } + }, + } + logReaderPool = sync.Pool{ + New: func() any { + return &dataobj.LogsReader{} + }, + } + streamReaderPool = sync.Pool{ + New: func() any { + return &dataobj.StreamsReader{} + }, + } +) type Config struct { Enabled bool `yaml:"enabled" doc:"description=Enable the dataobj querier."` @@ -42,10 +76,12 @@ func (c *Config) Validate() error { return nil } +// Store implements querier.Store for querying data objects. type Store struct { bucket objstore.Bucket } +// NewStore creates a new Store. func NewStore(bucket objstore.Bucket) *Store { return &Store{ bucket: bucket, @@ -59,9 +95,22 @@ func (s *Store) SelectLogs(_ context.Context, _ logql.SelectLogParams) (iter.Ent } // SelectSamples implements querier.Store -func (s *Store) SelectSamples(_ context.Context, _ logql.SelectSampleParams) (iter.SampleIterator, error) { - // TODO: Implement - return iter.NoopSampleIterator, nil +func (s *Store) SelectSamples(ctx context.Context, req logql.SelectSampleParams) (iter.SampleIterator, error) { + objects, err := s.objectsForTimeRange(ctx, req.Start, req.End) + if err != nil { + return nil, err + } + + shard, err := parseShards(req.Shards) + if err != nil { + return nil, err + } + expr, err := req.Expr() + if err != nil { + return nil, err + } + + return selectSamples(ctx, objects, shard, expr, req.Start, req.End) } // Stats implements querier.Store @@ -82,6 +131,7 @@ func (s *Store) GetShards(_ context.Context, _ string, _ model.Time, _ model.Tim return &logproto.ShardsResponse{}, nil } +// objectsForTimeRange returns data objects for the given time range. func (s *Store) objectsForTimeRange(ctx context.Context, from, through time.Time) ([]*dataobj.Object, error) { userID, err := tenant.TenantID(ctx) if err != nil { @@ -99,11 +149,249 @@ func (s *Store) objectsForTimeRange(ctx context.Context, from, through time.Time return objects, nil } -var noShard = logql.Shard{ - PowerOfTwo: &index.ShardAnnotation{ - Shard: uint32(1), - Of: uint32(1), - }, +func selectSamples(ctx context.Context, objects []*dataobj.Object, shard logql.Shard, expr syntax.SampleExpr, start, end time.Time) (iter.SampleIterator, error) { + selector, err := expr.Selector() + if err != nil { + return nil, err + } + + shardedObjects, err := shardObjects(ctx, objects, shard) + if err != nil { + return nil, err + } + defer func() { + for _, obj := range shardedObjects { + obj.reset() + shardedObjectsPool.Put(obj) + } + }() + streamsPredicate := streamPredicate(selector.Matchers(), start, end) + // TODO: support more predicates and combine with log.Pipeline. + logsPredicate := dataobj.TimeRangePredicate[dataobj.LogsPredicate]{ + StartTime: start, + EndTime: end, + IncludeStart: true, + IncludeEnd: false, + } + + g, ctx := errgroup.WithContext(ctx) + iterators := make([]iter.SampleIterator, len(shardedObjects)) + + for i, obj := range shardedObjects { + g.Go(func() error { + iterator, err := obj.selectSamples(ctx, streamsPredicate, logsPredicate, expr) + if err != nil { + return err + } + iterators[i] = iterator + return nil + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + + return iter.NewSortSampleIterator(iterators), nil +} + +type shardedObject struct { + streamReader *dataobj.StreamsReader + logReaders []*dataobj.LogsReader + + streamsIDs []int64 + streams map[int64]dataobj.Stream +} + +func shardObjects( + ctx context.Context, + objects []*dataobj.Object, + shard logql.Shard, +) ([]*shardedObject, error) { + metadatas, err := fetchMetadatas(ctx, objects) + if err != nil { + return nil, err + } + + // sectionIndex tracks the global section number across all objects to ensure consistent sharding + var sectionIndex uint64 + shardedReaders := make([]*shardedObject, 0, len(objects)) + + for i, metadata := range metadatas { + var reader *shardedObject + + for j := 0; j < metadata.LogsSections; j++ { + if shard.PowerOfTwo != nil && shard.PowerOfTwo.Of > 1 { + if sectionIndex%uint64(shard.PowerOfTwo.Of) != uint64(shard.PowerOfTwo.Shard) { + sectionIndex++ + continue + } + } + + if reader == nil { + reader = shardedObjectsPool.Get().(*shardedObject) + reader.streamReader = streamReaderPool.Get().(*dataobj.StreamsReader) + reader.streamReader.Reset(objects[i], j) + } + logReader := logReaderPool.Get().(*dataobj.LogsReader) + logReader.Reset(objects[i], j) + reader.logReaders = append(reader.logReaders, logReader) + sectionIndex++ + } + // if reader is not nil, it means we have at least one log reader + if reader != nil { + shardedReaders = append(shardedReaders, reader) + } + } + + return shardedReaders, nil +} + +func (s *shardedObject) reset() { + streamReaderPool.Put(s.streamReader) + for i, reader := range s.logReaders { + logReaderPool.Put(reader) + s.logReaders[i] = nil + } + s.streamReader = nil + s.logReaders = s.logReaders[:0] + s.streamsIDs = s.streamsIDs[:0] + clear(s.streams) +} + +func (s *shardedObject) selectSamples(ctx context.Context, streamsPredicate dataobj.StreamsPredicate, logsPredicate dataobj.LogsPredicate, expr syntax.SampleExpr) (iter.SampleIterator, error) { + if err := s.setPredicate(streamsPredicate, logsPredicate); err != nil { + return nil, err + } + + if err := s.matchStreams(ctx); err != nil { + return nil, err + } + + iterators := make([]iter.SampleIterator, len(s.logReaders)) + g, ctx := errgroup.WithContext(ctx) + + for i, reader := range s.logReaders { + g.Go(func() error { + // extractor is not thread safe, so we need to create a new one for each object + extractor, err := expr.Extractor() + if err != nil { + return err + } + iter, err := newSampleIterator(ctx, s.streams, extractor, reader) + if err != nil { + return err + } + iterators[i] = iter + return nil + }) + } + + if err := g.Wait(); err != nil { + return nil, err + } + + return iter.NewSortSampleIterator(iterators), nil +} + +func (s *shardedObject) setPredicate(streamsPredicate dataobj.StreamsPredicate, logsPredicate dataobj.LogsPredicate) error { + if err := s.streamReader.SetPredicate(streamsPredicate); err != nil { + return err + } + for _, reader := range s.logReaders { + if err := reader.SetPredicate(logsPredicate); err != nil { + return err + } + } + return nil +} + +func (s *shardedObject) matchStreams(ctx context.Context) error { + streamsPtr := streamsPool.Get().(*[]dataobj.Stream) + defer streamsPool.Put(streamsPtr) + streams := *streamsPtr + + for { + n, err := s.streamReader.Read(ctx, streams) + if err != nil && err != io.EOF { + return err + } + if n == 0 { + break + } + + for _, stream := range streams[:n] { + s.streams[stream.ID] = stream + s.streamsIDs = append(s.streamsIDs, stream.ID) + } + } + // setup log readers to filter streams + for _, reader := range s.logReaders { + if err := reader.MatchStreams(slices.Values(s.streamsIDs)); err != nil { + return err + } + } + return nil +} + +// fetchMetadatas fetches metadata of objects in parallel +func fetchMetadatas(ctx context.Context, objects []*dataobj.Object) ([]dataobj.Metadata, error) { + g, ctx := errgroup.WithContext(ctx) + metadatas := make([]dataobj.Metadata, len(objects)) + for i, obj := range objects { + g.Go(func() error { + var err error + metadatas[i], err = obj.Metadata(ctx) + return err + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + return metadatas, nil +} + +// streamPredicate creates a dataobj.StreamsPredicate from a list of matchers and a time range +func streamPredicate(matchers []*labels.Matcher, start, end time.Time) dataobj.StreamsPredicate { + var predicate dataobj.StreamsPredicate = dataobj.TimeRangePredicate[dataobj.StreamsPredicate]{ + StartTime: start, + EndTime: end, + IncludeStart: true, + IncludeEnd: true, + } + + // If there are any matchers, combine them with an AND predicate + if len(matchers) > 0 { + predicate = dataobj.AndPredicate[dataobj.StreamsPredicate]{ + Left: predicate, + Right: matchersToPredicate(matchers), + } + } + return predicate +} + +// matchersToPredicate converts a list of matchers to a dataobj.StreamsPredicate +func matchersToPredicate(matchers []*labels.Matcher) dataobj.StreamsPredicate { + var left dataobj.StreamsPredicate + for _, matcher := range matchers { + var right dataobj.StreamsPredicate + switch matcher.Type { + case labels.MatchEqual: + right = dataobj.LabelMatcherPredicate{Name: matcher.Name, Value: matcher.Value} + default: + right = dataobj.LabelFilterPredicate{Name: matcher.Name, Keep: func(_, value string) bool { + return matcher.Matches(value) + }} + } + if left == nil { + left = right + } else { + left = dataobj.AndPredicate[dataobj.StreamsPredicate]{ + Left: left, + Right: right, + } + } + } + return left } func parseShards(shards []string) (logql.Shard, error) { diff --git a/pkg/dataobj/querier/store_test.go b/pkg/dataobj/querier/store_test.go index a2877c77fbd4f..07e63103a3975 100644 --- a/pkg/dataobj/querier/store_test.go +++ b/pkg/dataobj/querier/store_test.go @@ -5,15 +5,13 @@ import ( "context" "os" "path/filepath" - "sort" "testing" "time" "github.com/go-kit/log" + "github.com/google/go-cmp/cmp" "github.com/grafana/dskit/user" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/common/model" - "github.com/prometheus/prometheus/model/labels" "github.com/stretchr/testify/require" "github.com/thanos-io/objstore" "github.com/thanos-io/objstore/providers/filesystem" @@ -21,379 +19,229 @@ import ( "github.com/grafana/loki/v3/pkg/dataobj" "github.com/grafana/loki/v3/pkg/dataobj/metastore" "github.com/grafana/loki/v3/pkg/dataobj/uploader" + "github.com/grafana/loki/v3/pkg/iter" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql" "github.com/grafana/loki/v3/pkg/logql/syntax" "github.com/grafana/loki/v3/pkg/querier/plan" ) -func TestStore_SelectSeries(t *testing.T) { +func TestStore_SelectSamples(t *testing.T) { const testTenant = "test-tenant" builder := newTestDataBuilder(t, testTenant) defer builder.close() // Setup test data now := setupTestData(t, builder) - store := NewStore(builder.bucket) ctx := user.InjectOrgID(context.Background(), testTenant) tests := []struct { name string selector string - want []string + start time.Time + end time.Time + shards []string + want []sampleWithLabels }{ { - name: "select all series", - selector: ``, - want: []string{ - `{app="foo", env="prod"}`, - `{app="foo", env="dev"}`, - `{app="bar", env="prod"}`, - `{app="bar", env="dev"}`, - `{app="baz", env="prod", team="a"}`, + name: "select all samples in range", + selector: `rate({app=~".+"}[1h])`, + start: now, + end: now.Add(time.Hour), + want: []sampleWithLabels{ + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(5 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(8 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(10 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(12 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(15 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(18 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(20 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(22 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(25 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(30 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(32 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(35 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(38 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(40 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(42 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(45 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(50 * time.Second).UnixNano(), Value: 1}}, }, }, { - name: "select with equality matcher", - selector: `{app="foo"}`, - want: []string{ - `{app="foo", env="prod"}`, - `{app="foo", env="dev"}`, + name: "select with time range filter", + selector: `rate({app="baz", env="prod", team="a"}[1h])`, + start: now.Add(20 * time.Second), + end: now.Add(40 * time.Second), + want: []sampleWithLabels{ + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(22 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(32 * time.Second).UnixNano(), Value: 1}}, }, }, { - name: "select with regex matcher", - selector: `{app=~"foo|bar"}`, - want: []string{ - `{app="foo", env="prod"}`, - `{app="foo", env="dev"}`, - `{app="bar", env="prod"}`, - `{app="bar", env="dev"}`, + name: "select with label matcher", + selector: `rate({app="foo"}[1h])`, + start: now, + end: now.Add(time.Hour), + want: []sampleWithLabels{ + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(10 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(20 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(30 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(35 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(45 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(50 * time.Second).UnixNano(), Value: 1}}, }, }, { - name: "select with negative equality matcher", - selector: `{app=~".+", app!="foo"}`, - want: []string{ - `{app="bar", env="prod"}`, - `{app="bar", env="dev"}`, - `{app="baz", env="prod", team="a"}`, + name: "select with regex matcher", + selector: `rate({app=~"foo|bar", env="prod"}[1h])`, + start: now, + end: now.Add(time.Hour), + want: []sampleWithLabels{ + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: 3600000000000, Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: 3605000000000, Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: 3615000000000, Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: 3625000000000, Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: 3630000000000, Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: 3640000000000, Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: 3645000000000, Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: 3650000000000, Value: 1}}, }, }, { - name: "select with negative regex matcher", - selector: `{app=~".+", app!~"foo|bar"}`, - want: []string{ - `{app="baz", env="prod", team="a"}`, + name: "select first shard", + selector: `rate({app=~".+"}[1h])`, + start: now, + end: now.Add(time.Hour), + shards: []string{"0_of_2"}, + want: []sampleWithLabels{ + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(5 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(8 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(12 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(15 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(18 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(22 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(25 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(32 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(38 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(40 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="baz", env="prod", team="a"}`, Samples: logproto.Sample{Timestamp: now.Add(42 * time.Second).UnixNano(), Value: 1}}, }, }, { - name: "select with multiple matchers", - selector: `{app="foo", env="prod"}`, - want: []string{ - `{app="foo", env="prod"}`, + name: "select second shard", + selector: `rate({app=~".+"}[1h])`, + start: now, + end: now.Add(time.Hour), + shards: []string{"1_of_2"}, + want: []sampleWithLabels{ + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(10 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(20 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(30 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="dev"}`, Samples: logproto.Sample{Timestamp: now.Add(35 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(45 * time.Second).UnixNano(), Value: 1}}, + {Labels: `{app="foo", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(50 * time.Second).UnixNano(), Value: 1}}, }, }, { - name: "select with regex and equality matchers", - selector: `{app=~"foo|bar", env="prod"}`, - want: []string{ - `{app="foo", env="prod"}`, - `{app="bar", env="prod"}`, + name: "select all samples in range with a filter", + selector: `count_over_time({app=~".+"} |= "bar2"[1h])`, + start: now, + end: now.Add(time.Hour), + want: []sampleWithLabels{ + {Labels: `{app="bar", env="prod"}`, Samples: logproto.Sample{Timestamp: now.Add(15 * time.Second).UnixNano(), Value: 1}}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - series, err := store.SelectSeries(ctx, logql.SelectLogParams{ - QueryRequest: &logproto.QueryRequest{ - Start: now.Add(-time.Hour), - End: now.Add(time.Hour), + it, err := store.SelectSamples(ctx, logql.SelectSampleParams{ + SampleQueryRequest: &logproto.SampleQueryRequest{ + Start: tt.start, + End: tt.end, Plan: planFromString(tt.selector), Selector: tt.selector, + Shards: tt.shards, }, }) require.NoError(t, err) - - var got []string - for _, s := range series { - got = append(got, labelsFromSeriesID(s)) - } - require.ElementsMatch(t, tt.want, got) - }) - } - - t.Run("sharding", func(t *testing.T) { - // Query first shard - series1, err := store.SelectSeries(ctx, logql.SelectLogParams{ - QueryRequest: &logproto.QueryRequest{ - Start: now.Add(-time.Hour), - End: now.Add(time.Hour), - Plan: planFromString(`{app=~"foo|bar|baz"}`), - Selector: `{app=~"foo|bar|baz"}`, - Shards: []string{"0_of_2"}, - }, - }) - require.NoError(t, err) - require.NotEmpty(t, series1) - require.Less(t, len(series1), 5) // Should get less than all series - - // Query second shard - series2, err := store.SelectSeries(ctx, logql.SelectLogParams{ - QueryRequest: &logproto.QueryRequest{ - Start: now.Add(-time.Hour), - End: now.Add(time.Hour), - Plan: planFromString(`{app=~"foo|bar|baz"}`), - Selector: `{app=~"foo|bar|baz"}`, - Shards: []string{"1_of_2"}, - }, - }) - require.NoError(t, err) - require.NotEmpty(t, series2) - - // Combined shards should equal all series - var allSeries []string - for _, s := range append(series1, series2...) { - allSeries = append(allSeries, labelsFromSeriesID(s)) - } - - want := []string{ - `{app="foo", env="prod"}`, - `{app="foo", env="dev"}`, - `{app="bar", env="prod"}`, - `{app="bar", env="dev"}`, - `{app="baz", env="prod", team="a"}`, - } - require.ElementsMatch(t, want, allSeries) - }) -} - -func TestStore_LabelNamesForMetricName(t *testing.T) { - const testTenant = "test-tenant" - builder := newTestDataBuilder(t, testTenant) - defer builder.close() - - // Setup test data - now := setupTestData(t, builder) - - store := NewStore(builder.bucket) - ctx := user.InjectOrgID(context.Background(), testTenant) - - tests := []struct { - name string - matchers []*labels.Matcher - want []string - }{ - { - name: "no matchers", - matchers: nil, - want: []string{"app", "env", "team"}, - }, - { - name: "with equality matcher", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), - }, - want: []string{"app", "env"}, - }, - { - name: "with regex matcher", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchRegexp, "app", "foo|bar"), - }, - want: []string{"app", "env"}, - }, - { - name: "with negative matcher", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchNotEqual, "app", "foo"), - }, - want: []string{"app", "env", "team"}, - }, - { - name: "with negative regex matcher", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchNotRegexp, "app", "foo|bar"), - }, - want: []string{"app", "env", "team"}, - }, - { - name: "with multiple matchers", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), - labels.MustNewMatcher(labels.MatchEqual, "env", "prod"), - }, - want: []string{"app", "env"}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - names, err := store.LabelNamesForMetricName(ctx, "", model.TimeFromUnixNano(now.Add(-time.Hour).UnixNano()), model.TimeFromUnixNano(now.Add(time.Hour).UnixNano()), "", tt.matchers...) - require.NoError(t, err) - require.ElementsMatch(t, tt.want, names) - }) - } -} - -func TestStore_LabelValuesForMetricName(t *testing.T) { - const testTenant = "test-tenant" - builder := newTestDataBuilder(t, testTenant) - defer builder.close() - - // Setup test data - now := setupTestData(t, builder) - - store := NewStore(builder.bucket) - ctx := user.InjectOrgID(context.Background(), testTenant) - - tests := []struct { - name string - labelName string - matchers []*labels.Matcher - want []string - }{ - { - name: "app label without matchers", - labelName: "app", - matchers: nil, - want: []string{"bar", "baz", "foo"}, - }, - { - name: "env label without matchers", - labelName: "env", - matchers: nil, - want: []string{"dev", "prod"}, - }, - { - name: "team label without matchers", - labelName: "team", - matchers: nil, - want: []string{"a"}, - }, - { - name: "env label with app equality matcher", - labelName: "env", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), - }, - want: []string{"dev", "prod"}, - }, - { - name: "env label with app regex matcher", - labelName: "env", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchRegexp, "app", "foo|bar"), - }, - want: []string{"dev", "prod"}, - }, - { - name: "env label with app negative matcher", - labelName: "env", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchNotEqual, "app", "foo"), - }, - want: []string{"dev", "prod"}, - }, - { - name: "env label with app negative regex matcher", - labelName: "env", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchNotRegexp, "app", "foo|bar"), - }, - want: []string{"prod"}, - }, - { - name: "env label with multiple matchers", - labelName: "env", - matchers: []*labels.Matcher{ - labels.MustNewMatcher(labels.MatchEqual, "app", "foo"), - labels.MustNewMatcher(labels.MatchEqual, "env", "prod"), - }, - want: []string{"prod"}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - values, err := store.LabelValuesForMetricName(ctx, "", model.TimeFromUnixNano(now.Add(-time.Hour).UnixNano()), model.TimeFromUnixNano(now.Add(time.Hour).UnixNano()), "", tt.labelName, tt.matchers...) + samples, err := readAllSamples(it) require.NoError(t, err) - require.Equal(t, tt.want, values) + if diff := cmp.Diff(tt.want, samples); diff != "" { + t.Errorf("samples mismatch (-want +got):\n%s", diff) + } }) } } func setupTestData(t *testing.T, builder *testDataBuilder) time.Time { t.Helper() - now := time.Now() + now := time.Unix(0, int64(time.Hour)) + + // Data before the query range (should not be included in results) + builder.addStream( + `{app="foo", env="prod"}`, + logproto.Entry{Timestamp: now.Add(-2 * time.Hour), Line: "foo_before1"}, + logproto.Entry{Timestamp: now.Add(-2 * time.Hour).Add(30 * time.Second), Line: "foo_before2"}, + logproto.Entry{Timestamp: now.Add(-2 * time.Hour).Add(45 * time.Second), Line: "foo_before3"}, + ) + builder.flush() - // First object with app=foo series + // Data within query range builder.addStream( `{app="foo", env="prod"}`, logproto.Entry{Timestamp: now, Line: "foo1"}, - logproto.Entry{Timestamp: now.Add(time.Second), Line: "foo2"}, + logproto.Entry{Timestamp: now.Add(30 * time.Second), Line: "foo2"}, + logproto.Entry{Timestamp: now.Add(45 * time.Second), Line: "foo3"}, + logproto.Entry{Timestamp: now.Add(50 * time.Second), Line: "foo4"}, ) builder.addStream( `{app="foo", env="dev"}`, - logproto.Entry{Timestamp: now, Line: "foo3"}, - logproto.Entry{Timestamp: now.Add(time.Second), Line: "foo4"}, + logproto.Entry{Timestamp: now.Add(10 * time.Second), Line: "foo5"}, + logproto.Entry{Timestamp: now.Add(20 * time.Second), Line: "foo6"}, + logproto.Entry{Timestamp: now.Add(35 * time.Second), Line: "foo7"}, ) builder.flush() - // Second object with app=bar series builder.addStream( `{app="bar", env="prod"}`, - logproto.Entry{Timestamp: now, Line: "bar1"}, - logproto.Entry{Timestamp: now.Add(time.Second), Line: "bar2"}, + logproto.Entry{Timestamp: now.Add(5 * time.Second), Line: "bar1"}, + logproto.Entry{Timestamp: now.Add(15 * time.Second), Line: "bar2"}, + logproto.Entry{Timestamp: now.Add(25 * time.Second), Line: "bar3"}, + logproto.Entry{Timestamp: now.Add(40 * time.Second), Line: "bar4"}, ) builder.addStream( `{app="bar", env="dev"}`, - logproto.Entry{Timestamp: now, Line: "bar3"}, - logproto.Entry{Timestamp: now.Add(time.Second), Line: "bar4"}, + logproto.Entry{Timestamp: now.Add(8 * time.Second), Line: "bar5"}, + logproto.Entry{Timestamp: now.Add(18 * time.Second), Line: "bar6"}, + logproto.Entry{Timestamp: now.Add(38 * time.Second), Line: "bar7"}, ) builder.flush() - // Third object with app=baz series builder.addStream( `{app="baz", env="prod", team="a"}`, - logproto.Entry{Timestamp: now, Line: "baz1"}, - logproto.Entry{Timestamp: now.Add(time.Second), Line: "baz2"}, + logproto.Entry{Timestamp: now.Add(12 * time.Second), Line: "baz1"}, + logproto.Entry{Timestamp: now.Add(22 * time.Second), Line: "baz2"}, + logproto.Entry{Timestamp: now.Add(32 * time.Second), Line: "baz3"}, + logproto.Entry{Timestamp: now.Add(42 * time.Second), Line: "baz4"}, ) builder.flush() - return now -} - -func labelsFromSeriesID(id logproto.SeriesIdentifier) string { - ls := make(labels.Labels, 0, len(id.Labels)) - for _, l := range id.Labels { - ls = append(ls, labels.Label{Name: l.Key, Value: l.Value}) - } - sort.Sort(ls) - return ls.String() -} - -func mustParseSeriesID(s string) logproto.SeriesIdentifier { - ls, err := syntax.ParseLabels(s) - if err != nil { - panic(err) - } - return logproto.SeriesIdentifier{ - Labels: labelsToSeriesLabels(ls), - } -} + // Data after the query range (should not be included in results) + builder.addStream( + `{app="foo", env="prod"}`, + logproto.Entry{Timestamp: now.Add(2 * time.Hour), Line: "foo_after1"}, + logproto.Entry{Timestamp: now.Add(2 * time.Hour).Add(30 * time.Second), Line: "foo_after2"}, + logproto.Entry{Timestamp: now.Add(2 * time.Hour).Add(45 * time.Second), Line: "foo_after3"}, + ) + builder.flush() -func labelsToSeriesLabels(ls labels.Labels) []logproto.SeriesIdentifier_LabelsEntry { - entries := make([]logproto.SeriesIdentifier_LabelsEntry, 0, len(ls)) - for _, l := range ls { - entries = append(entries, logproto.SeriesIdentifier_LabelsEntry{ - Key: l.Name, - Value: l.Value, - }) - } - return entries + return now } func planFromString(s string) *plan.QueryPlan { @@ -483,3 +331,22 @@ func (b *testDataBuilder) close() { require.NoError(b.t, b.bucket.Close()) os.RemoveAll(b.dir) } + +type sampleWithLabels struct { + Labels string + Samples logproto.Sample +} + +// Helper function to read all samples from an iterator +func readAllSamples(it iter.SampleIterator) ([]sampleWithLabels, error) { + var result []sampleWithLabels + defer it.Close() + for it.Next() { + sample := it.At() + result = append(result, sampleWithLabels{ + Labels: it.Labels(), + Samples: sample, + }) + } + return result, it.Err() +} diff --git a/pkg/iter/sample_iterator.go b/pkg/iter/sample_iterator.go index cac1cac6c83e4..28c2af94ba95e 100644 --- a/pkg/iter/sample_iterator.go +++ b/pkg/iter/sample_iterator.go @@ -253,11 +253,13 @@ Outer: heap.Pop(i.heap) previous := i.buffer var dupe bool - for _, t := range previous { - if t.Sample.Hash == sample.Hash { - i.stats.AddDuplicates(1) - dupe = true - break + if sample.Hash != 0 { + for _, t := range previous { + if t.Sample.Hash == sample.Hash { + i.stats.AddDuplicates(1) + dupe = true + break + } } } if !dupe { @@ -277,10 +279,12 @@ Outer: sample.Timestamp != i.buffer[0].Timestamp { break } - for _, t := range previous { - if t.Hash == sample.Hash { - i.stats.AddDuplicates(1) - continue inner + if sample.Hash != 0 { + for _, t := range previous { + if t.Hash == sample.Hash { + i.stats.AddDuplicates(1) + continue inner + } } } i.buffer = append(i.buffer, sampleWithLabels{ diff --git a/pkg/iter/sample_iterator_test.go b/pkg/iter/sample_iterator_test.go index b42c6ff59cf21..08c384db418b9 100644 --- a/pkg/iter/sample_iterator_test.go +++ b/pkg/iter/sample_iterator_test.go @@ -491,3 +491,53 @@ func TestDedupeMergeSampleIterator(t *testing.T) { require.Equal(t, 1., it.At().Value) require.Equal(t, xxhash.Sum64String("3"), it.At().Hash) } + +func TestMergeSampleIteratorZeroHash(t *testing.T) { + // Create series with samples that have zero hashes but same timestamps + series1 := logproto.Series{ + Labels: `{foo="bar"}`, + StreamHash: hashLabels(`{foo="bar"}`), + Samples: []logproto.Sample{ + {Timestamp: 1, Value: 1.0, Hash: 0}, // Zero hash + {Timestamp: 1, Value: 2.0, Hash: 0}, // Zero hash, same timestamp + {Timestamp: 2, Value: 3.0, Hash: 42}, // Non-zero hash + }, + } + + series2 := logproto.Series{ + Labels: `{foo="bar"}`, + StreamHash: hashLabels(`{foo="bar"}`), + Samples: []logproto.Sample{ + {Timestamp: 1, Value: 4.0, Hash: 0}, // Zero hash, same timestamp + {Timestamp: 2, Value: 3.0, Hash: 42}, // Non-zero hash, should be deduplicated + }, + } + + it := NewMergeSampleIterator(context.Background(), []SampleIterator{ + NewSeriesIterator(series1), + NewSeriesIterator(series2), + }) + + // Should get all samples with zero hash at timestamp 1 + require.True(t, it.Next()) + require.Equal(t, `{foo="bar"}`, it.Labels()) + require.Equal(t, logproto.Sample{Timestamp: 1, Value: 1.0, Hash: 0}, it.At()) + + require.True(t, it.Next()) + require.Equal(t, `{foo="bar"}`, it.Labels()) + require.Equal(t, logproto.Sample{Timestamp: 1, Value: 2.0, Hash: 0}, it.At()) + + require.True(t, it.Next()) + require.Equal(t, `{foo="bar"}`, it.Labels()) + require.Equal(t, logproto.Sample{Timestamp: 1, Value: 4.0, Hash: 0}, it.At()) + + // Should get only one sample with non-zero hash at timestamp 2 (deduplicated) + require.True(t, it.Next()) + require.Equal(t, `{foo="bar"}`, it.Labels()) + require.Equal(t, logproto.Sample{Timestamp: 2, Value: 3.0, Hash: 42}, it.At()) + + // No more samples + require.False(t, it.Next()) + require.NoError(t, it.Err()) + require.NoError(t, it.Close()) +}
feat
Implement SelectSamples (#16251)
c66ffd125cd89f5845a75a1751186fa46d003f70
2023-10-26 14:03:30
renovate[bot]
fix(deps): update github.com/c2h5oh/datasize digest to 859f65c (main) (#10820)
false
diff --git a/go.mod b/go.mod index ddf8b367742f5..efad30c6ba83b 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/baidubce/bce-sdk-go v0.9.141 github.com/bmatcuk/doublestar v1.3.4 github.com/buger/jsonparser v1.1.1 - github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee + github.com/c2h5oh/datasize v0.0.0-20220606134207-859f65c6625b github.com/cespare/xxhash v1.1.0 github.com/cespare/xxhash/v2 v2.2.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf diff --git a/go.sum b/go.sum index a141a9213dd6a..465a01a6ac13a 100644 --- a/go.sum +++ b/go.sum @@ -387,8 +387,8 @@ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dR github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= -github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee h1:BnPxIde0gjtTnc9Er7cxvBk8DHLWhEux0SxayC8dP6I= -github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= +github.com/c2h5oh/datasize v0.0.0-20220606134207-859f65c6625b h1:6+ZFm0flnudZzdSE0JxlhR2hKnGPcNB35BjQf4RYQDY= +github.com/c2h5oh/datasize v0.0.0-20220606134207-859f65c6625b/go.mod h1:S/7n9copUssQ56c7aAgHqftWO4LTf4xY6CGWt8Bc+3M= github.com/caddyserver/caddy v1.0.4/go.mod h1:uruyfVsyMcDb3IOzSKsi1x0wOjy1my/PxOSTcD+24jM= github.com/caio/go-tdigest v2.3.0+incompatible/go.mod h1:sHQM/ubZStBUmF1WbB8FAm8q9GjDajLC5T7ydxE3JHI= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= diff --git a/vendor/github.com/c2h5oh/datasize/README.md b/vendor/github.com/c2h5oh/datasize/README.md index ac0cf8586e9f2..f6e828587f007 100644 --- a/vendor/github.com/c2h5oh/datasize/README.md +++ b/vendor/github.com/c2h5oh/datasize/README.md @@ -19,7 +19,7 @@ Just like `time` package provides `time.Second`, `time.Day` constants `datasize` Just like `time` package provides `duration.Nanoseconds() uint64 `, `duration.Hours() float64` helpers `datasize` has. * `ByteSize.Bytes() uint64` -* `ByteSize.Kilobytes() float4` +* `ByteSize.Kilobytes() float64` * `ByteSize.Megabytes() float64` * `ByteSize.Gigabytes() float64` * `ByteSize.Terabytes() float64` diff --git a/vendor/github.com/c2h5oh/datasize/datasize.go b/vendor/github.com/c2h5oh/datasize/datasize.go index 6754788162496..2ce762751c08f 100644 --- a/vendor/github.com/c2h5oh/datasize/datasize.go +++ b/vendor/github.com/c2h5oh/datasize/datasize.go @@ -215,3 +215,25 @@ BitsError: *b = 0 return &strconv.NumError{fnUnmarshalText, string(t0), ErrBits} } + +func Parse(t []byte) (ByteSize, error) { + var v ByteSize + err := v.UnmarshalText(t) + return v, err +} + +func MustParse(t []byte) ByteSize { + v, err := Parse(t) + if err != nil { + panic(err) + } + return v +} + +func ParseString(s string) (ByteSize, error) { + return Parse([]byte(s)) +} + +func MustParseString(s string) ByteSize { + return MustParse([]byte(s)) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 8e76eb21adbf8..97cf4c4cc6365 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -423,7 +423,7 @@ github.com/bmatcuk/doublestar # github.com/buger/jsonparser v1.1.1 ## explicit; go 1.13 github.com/buger/jsonparser -# github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee +# github.com/c2h5oh/datasize v0.0.0-20220606134207-859f65c6625b ## explicit github.com/c2h5oh/datasize # github.com/census-instrumentation/opencensus-proto v0.4.1
fix
update github.com/c2h5oh/datasize digest to 859f65c (main) (#10820)
80a616dcfc7fd4e26a6bf5c70407be6d45dc0370
2025-02-24 13:31:51
Sandeep Sukhani
fix: update crc64nvme to fix build issues with arm images (#16413)
false
diff --git a/go.mod b/go.mod index 43548a4f1e284..e8b457a0a353b 100644 --- a/go.mod +++ b/go.mod @@ -185,7 +185,7 @@ require ( github.com/mattn/go-runewidth v0.0.16 // indirect github.com/mdlayher/socket v0.5.1 // indirect github.com/mdlayher/vsock v1.2.1 // indirect - github.com/minio/crc64nvme v1.0.0 // indirect + github.com/minio/crc64nvme v1.0.1 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/sys/userns v0.1.0 // indirect github.com/ncw/swift v1.0.53 // indirect diff --git a/go.sum b/go.sum index 2cf92e80916e6..ddf8651bfa162 100644 --- a/go.sum +++ b/go.sum @@ -864,8 +864,8 @@ github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKju github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY= github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs= -github.com/minio/crc64nvme v1.0.0 h1:MeLcBkCTD4pAoU7TciAfwsfxgkhM2u5hCe48hSEVFr0= -github.com/minio/crc64nvme v1.0.0/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/crc64nvme v1.0.1 h1:DHQPrYPdqK7jQG/Ls5CTBZWeex/2FMS3G5XGkycuFrY= +github.com/minio/crc64nvme v1.0.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= github.com/minio/minio-go/v7 v7.0.86 h1:DcgQ0AUjLJzRH6y/HrxiZ8CXarA70PAIufXHodP4s+k= diff --git a/vendor/github.com/minio/crc64nvme/crc64_amd64.s b/vendor/github.com/minio/crc64nvme/crc64_amd64.s index 04d8cf7869a84..9782321fd0ccd 100644 --- a/vendor/github.com/minio/crc64nvme/crc64_amd64.s +++ b/vendor/github.com/minio/crc64nvme/crc64_amd64.s @@ -2,6 +2,8 @@ // Use of this source code is governed by a license that can be // found in the LICENSE file. +//go:build !noasm && !appengine && !gccgo + #include "textflag.h" TEXT ·updateAsm(SB), $0-40 diff --git a/vendor/github.com/minio/crc64nvme/crc64_arm64.s b/vendor/github.com/minio/crc64nvme/crc64_arm64.s index b61866f6306e2..229a10fb7347a 100644 --- a/vendor/github.com/minio/crc64nvme/crc64_arm64.s +++ b/vendor/github.com/minio/crc64nvme/crc64_arm64.s @@ -2,6 +2,8 @@ // Use of this source code is governed by a license that can be // found in the LICENSE file. +//go:build !noasm && !appengine && !gccgo + #include "textflag.h" TEXT ·updateAsm(SB), $0-40 diff --git a/vendor/github.com/minio/crc64nvme/crc64_other.go b/vendor/github.com/minio/crc64nvme/crc64_other.go index 1d78d74310ede..467958c69ddbf 100644 --- a/vendor/github.com/minio/crc64nvme/crc64_other.go +++ b/vendor/github.com/minio/crc64nvme/crc64_other.go @@ -7,3 +7,5 @@ package crc64nvme var hasAsm = false + +func updateAsm(crc uint64, p []byte) (checksum uint64) { panic("should not be reached") } diff --git a/vendor/modules.txt b/vendor/modules.txt index 04dd986da5d83..2169a5443fdb6 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1291,7 +1291,7 @@ github.com/mdlayher/vsock # github.com/miekg/dns v1.1.63 ## explicit; go 1.19 github.com/miekg/dns -# github.com/minio/crc64nvme v1.0.0 +# github.com/minio/crc64nvme v1.0.1 ## explicit; go 1.22 github.com/minio/crc64nvme # github.com/minio/md5-simd v1.1.2
fix
update crc64nvme to fix build issues with arm images (#16413)
db8880e6e0418ebd104eb587e6bdc51ae41d891f
2019-09-10 02:07:47
sh0rez
chore(ci/cd): breaking the circle (#990)
false
diff --git a/.circleci/config.yml b/.circleci/config.yml index a35601fd14e61..5f113ea99e2f2 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -23,28 +23,8 @@ workflows: - lint: {filters: {<<: *tags}} - test: {filters: {<<: *tags}} - - build/loki: - requires: [ lint, test ] - filters: {<<: *no-master} - - publish/loki: - requires: [ lint, test ] - filters: { <<: *tag-or-master } - - - build/canary: - requires: [ lint, test ] - filters: {<<: *no-master} - - publish/canary: - requires: [ lint, test ] - filters: { <<: *tag-or-master } - - - build/promtail: - requires: [ lint, test ] - filters: {<<: *no-master} - build/promtail-windows: requires: [ lint, test ] - - publish/promtail: - requires: [ lint, test ] - filters: { <<: *tag-or-master } - build/docker-driver: requires: [ lint, test ] @@ -58,11 +38,6 @@ workflows: filters: { <<: *only-tags } - deploy: - requires: - - publish/loki - - publish/promtail - - publish/canary - - publish/docker-driver filters: {<<: *tag-or-master} - test-helm: @@ -79,56 +54,6 @@ workflows: - image: grafana/loki-build-image:0.5.0 working_directory: /go/src/github.com/grafana/loki -.machine: &machine - machine: - image: ubuntu-1604:201903-01 - working_directory: ~/go/src/github.com/grafana/loki - environment: - APP: to-be-set - GOPATH: /home/circleci/go - -.rootless: &rootless - run: - name: rootless - command: | - sudo apt-get update && \ - sudo apt-get install -qy uidmap libseccomp-dev binfmt-support go-bindata - sudo docker run --privileged linuxkit/binfmt:v0.6 - -.img: &img - run: - name: img - # TODO: switch to https://github.com/genuinetools/img once 5a8119fb4ce7d712ca2ed589a345213fdf576268 is released - command: | - sudo curl -fSL "https://github.com/sh0rez/img/releases/download/v0.5.8/img-linux-amd64" -o "/usr/local/bin/img" - sudo chmod a+x "/usr/local/bin/img" - -# builds a container -.container: &container - <<: *machine - steps: - - checkout - - <<: *rootless - - <<: *img - - run: - name: container - command: | - make $APP-image-cross - -# builds and pushes a container -.publish: &publish - <<: *machine - steps: - - checkout - - <<: *rootless - - <<: *img - - run: - name: login - command: img login -u "$DOCKER_USER" -p "$DOCKER_PASS" - - run: - name: push image - command: make $APP-push - jobs: test: <<: *defaults @@ -149,34 +74,7 @@ jobs: name: Check Generated Files command: make BUILD_IN_CONTAINER=false check-generated-files - # Loki - build/loki: - <<: *container - environment: - APP: loki - - publish/loki: - <<: *publish - environment: - APP: loki - - # Loki - build/canary: - <<: *container - environment: - APP: loki-canary - - publish/canary: - <<: *publish - environment: - APP: loki-canary - # Promtail - build/promtail: - <<: *container - environment: - APP: promtail - build/promtail-windows: <<: *defaults steps: @@ -185,11 +83,6 @@ jobs: name: build command: make GOOS=windows promtail - publish/promtail: - <<: *publish - environment: - APP: promtail - # Docker driver build/docker-driver: <<: *defaults diff --git a/.drone/docker-manifest.tmpl b/.drone/docker-manifest.tmpl index 7ebb8c942407a..54f26489e1a7e 100644 --- a/.drone/docker-manifest.tmpl +++ b/.drone/docker-manifest.tmpl @@ -1,4 +1,4 @@ -image: grafanasaur/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}} +image: grafana/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}} {{#if build.tags}} tags: {{#each build.tags}} @@ -6,16 +6,16 @@ tags: {{/each}} {{/if}} manifests: - - image: grafanasaur/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-amd64 + - image: grafana/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-amd64 platform: architecture: amd64 os: linux - - image: grafanasaur/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-arm64 + - image: grafana/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-arm64 platform: architecture: arm64 os: linux variant: v8 - - image: grafanasaur/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-arm + - image: grafana/{{config.target}}:{{#if build.tag}}{{build.tag}}{{else}}{{build.branch}}-{{substr 0 7 build.commit}}{{/if}}-arm platform: architecture: arm os: linux diff --git a/.drone/drone.jsonnet b/.drone/drone.jsonnet index a54cad6ec2fcc..2422acd76db33 100644 --- a/.drone/drone.jsonnet +++ b/.drone/drone.jsonnet @@ -1,6 +1,8 @@ local apps = ['loki', 'loki-canary', 'promtail']; local archs = ['amd64', 'arm64', 'arm']; +local build_image_version = std.extVar('__build-image-version'); + local condition(verb) = { tagMaster: { ref: { @@ -19,14 +21,24 @@ local pipeline(name) = { steps: [], }; +local run(name, commands) = { + name: name, + image: 'grafana/loki-build-image:%s' % build_image_version, + commands: commands, +}; + +local make(target, container=true) = run(target, [ + 'make ' + (if !container then 'BUILD_IN_CONTAINER=false ' else '') + target, +]); + local docker(arch, app) = { name: '%s-image' % if $.settings.dry_run then 'build-' + app else 'publish-' + app, image: 'plugins/docker', settings: { - repo: 'grafanasaur/%s' % app, + repo: 'grafana/%s' % app, dockerfile: 'cmd/%s/Dockerfile' % app, - username: { from_secret: 'saur_username' }, - password: { from_secret: 'saur_password' }, + username: { from_secret: 'docker_username' }, + password: { from_secret: 'docker_password' }, dry_run: false, }, }; @@ -60,6 +72,7 @@ local multiarch_image(arch) = pipeline('docker-' + arch) { } for app in apps ], + depends_on: ['check'], }; local manifest(apps) = pipeline('manifest') { @@ -73,21 +86,32 @@ local manifest(apps) = pipeline('manifest') { target: app, spec: '.drone/docker-manifest.tmpl', ignore_missing: true, - username: { from_secret: 'saur_username' }, - password: { from_secret: 'saur_password' }, + username: { from_secret: 'docker_username' }, + password: { from_secret: 'docker_password' }, }, depends_on: ['clone'], } for app in apps ], -} + { depends_on: [ 'docker-%s' % arch for arch in archs - ], + ] + ['check'], }; local drone = [ + pipeline('check') { + workspace: { + base: "/go", + path: "src/github.com/grafana/loki" + }, + steps: [ + make('test', container=false) { depends_on: ['clone'] }, + make('lint', container=false) { depends_on: ['clone'] }, + make('check-generated-files', container=false) { depends_on: ['clone'] }, + ], + }, +] + [ multiarch_image(arch) for arch in archs ] + [ diff --git a/.drone/drone.yml b/.drone/drone.yml index 05290af9fb847..f273596ba91dc 100644 --- a/.drone/drone.yml +++ b/.drone/drone.yml @@ -1,4 +1,31 @@ kind: pipeline +name: check +steps: +- commands: + - make BUILD_IN_CONTAINER=false test + depends_on: + - clone + image: grafana/loki-build-image:0.5.0 + name: test +- commands: + - make BUILD_IN_CONTAINER=false lint + depends_on: + - clone + image: grafana/loki-build-image:0.5.0 + name: lint +- commands: + - make BUILD_IN_CONTAINER=false check-generated-files + depends_on: + - clone + image: grafana/loki-build-image:0.5.0 + name: check-generated-files +workspace: + base: /go + path: src/github.com/grafana/loki +--- +depends_on: +- check +kind: pipeline name: docker-amd64 platform: arch: amd64 @@ -18,10 +45,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -35,10 +62,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -52,10 +79,10 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -69,10 +96,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -86,10 +113,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -103,16 +130,18 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: include: - refs/heads/master - refs/tags/v* --- +depends_on: +- check kind: pipeline name: docker-arm64 platform: @@ -133,10 +162,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -150,10 +179,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -167,10 +196,10 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -184,10 +213,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -201,10 +230,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -218,16 +247,18 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: include: - refs/heads/master - refs/tags/v* --- +depends_on: +- check kind: pipeline name: docker-arm platform: @@ -248,10 +279,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -265,10 +296,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -282,10 +313,10 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: true password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: exclude: @@ -299,10 +330,10 @@ steps: dockerfile: cmd/loki/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki + from_secret: docker_password + repo: grafana/loki username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -316,10 +347,10 @@ steps: dockerfile: cmd/loki-canary/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/loki-canary + from_secret: docker_password + repo: grafana/loki-canary username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -333,10 +364,10 @@ steps: dockerfile: cmd/promtail/Dockerfile dry_run: false password: - from_secret: saur_password - repo: grafanasaur/promtail + from_secret: docker_password + repo: grafana/promtail username: - from_secret: saur_username + from_secret: docker_username when: ref: include: @@ -347,6 +378,7 @@ depends_on: - docker-amd64 - docker-arm64 - docker-arm +- check kind: pipeline name: manifest steps: @@ -357,11 +389,11 @@ steps: settings: ignore_missing: true password: - from_secret: saur_password + from_secret: docker_password spec: .drone/docker-manifest.tmpl target: promtail username: - from_secret: saur_username + from_secret: docker_username - depends_on: - clone image: plugins/manifest @@ -369,11 +401,11 @@ steps: settings: ignore_missing: true password: - from_secret: saur_password + from_secret: docker_password spec: .drone/docker-manifest.tmpl target: loki username: - from_secret: saur_username + from_secret: docker_username - depends_on: - clone image: plugins/manifest @@ -381,11 +413,11 @@ steps: settings: ignore_missing: true password: - from_secret: saur_password + from_secret: docker_password spec: .drone/docker-manifest.tmpl target: loki-canary username: - from_secret: saur_username + from_secret: docker_username trigger: ref: include: diff --git a/Makefile b/Makefile index 53a244b8adea9..d20a244929c45 100644 --- a/Makefile +++ b/Makefile @@ -446,4 +446,4 @@ benchmark-store: # regenerate drone yaml drone: - jsonnet .drone/drone.jsonnet | jq .drone -r | yq -y . > .drone/drone.yml + jsonnet -V __build-image-version=$(BUILD_IMAGE_VERSION) .drone/drone.jsonnet | jq .drone -r | yq -y . > .drone/drone.yml
chore
breaking the circle (#990)
712a2b69672dcf903f98b18d35737cf50f476e71
2024-04-07 22:16:33
Owen Diehl
fix(blooms): fixup bloom testing (#12494)
false
diff --git a/pkg/bloomgateway/processor.go b/pkg/bloomgateway/processor.go index 401bd9210e0ae..e076a856d981d 100644 --- a/pkg/bloomgateway/processor.go +++ b/pkg/bloomgateway/processor.go @@ -168,7 +168,7 @@ func (p *processor) processBlock(_ context.Context, blockQuerier *v1.BlockQuerie return err } - tokenizer := v1.NewNGramTokenizer(schema.NGramLen(), 0) + tokenizer := v1.NewNGramTokenizer(schema.NGramLen(), schema.NGramSkip()) iters := make([]v1.PeekingIterator[v1.Request], 0, len(tasks)) for _, task := range tasks { diff --git a/pkg/storage/bloom/v1/bloom_tester.go b/pkg/storage/bloom/v1/bloom_tester.go index dbb0f7a12aaff..80178a54deabe 100644 --- a/pkg/storage/bloom/v1/bloom_tester.go +++ b/pkg/storage/bloom/v1/bloom_tester.go @@ -1,8 +1,9 @@ package v1 import ( + "unicode/utf8" + "github.com/grafana/regexp" - regexpsyntax "github.com/grafana/regexp/syntax" "github.com/grafana/loki/v3/pkg/logql/log" "github.com/grafana/loki/v3/pkg/logql/log/pattern" @@ -70,6 +71,7 @@ func ExtractTestableLineFilters(expr syntax.Expr) []syntax.LineFilterExpr { // Use ExtractTestableLineFilters to extract testable line filters from an expression. // TODO(owen-d): limits the number of bloom lookups run. // An arbitrarily high number can overconsume cpu and is a DoS vector. +// TODO(owen-d): use for loop not recursion to protect callstack func FiltersToBloomTest(b NGramBuilder, filters ...syntax.LineFilterExpr) BloomTest { tests := make(BloomTests, 0, len(filters)) for _, f := range filters { @@ -100,21 +102,7 @@ func simpleFilterToBloomTest(b NGramBuilder, filter syntax.LineFilter) BloomTest case log.LineMatchEqual: return newStringTest(b, filter.Match) case log.LineMatchRegexp: - reg, err := regexpsyntax.Parse(filter.Match, regexpsyntax.Perl) - if err != nil { - // TODO: log error - return MatchAll - } - reg = reg.Simplify() - - simplifier := log.NewRegexSimplifier(newStringFilterFunc(b), newStringFilterFunc(b)) - matcher, ok := simplifier.Simplify(reg, false) - if !ok { - // If the regex simplifier fails, we default to MatchAll - return MatchAll - } - - return matcherFilterWrapper{filter: matcher} + return MatchAll case log.LineMatchPattern: return newPatternTest(b, filter.Match) default: @@ -189,21 +177,47 @@ func (n matchAllTest) MatchesWithPrefixBuf(_ filter.Checker, _ []byte, _ int) bo // TODO: This should be moved to tokenizer.go type NGramBuilder interface { Tokens(line string) Iterator[[]byte] + N() int + SkipFactor() int } type stringTest struct { ngrams [][]byte } -func newStringTest(b NGramBuilder, search string) stringTest { - var test stringTest - it := b.Tokens(search) - for it.Next() { - ngram := make([]byte, len(it.At())) - copy(ngram, it.At()) - test.ngrams = append(test.ngrams, ngram) +func newStringTest(b NGramBuilder, search string) (res BloomTest) { + // search string must be longer than the combined ngram length and skip factor + // in order for all possible skip offsets to have at least 1 ngram + skip := b.SkipFactor() + if ct := utf8.RuneCountInString(search); ct < b.N()+skip { + return MatchAll + } + + tests := make([]stringTest, 0, skip) + + for i := 0; i < skip+1; i++ { + searchWithOffset := search + for j := 0; j < i; j++ { + _, size := utf8.DecodeRuneInString(searchWithOffset) + // NB(owen-d): small bounds check for invalid utf8 + searchWithOffset = searchWithOffset[min(size, len(searchWithOffset)):] + } + + var test stringTest + it := b.Tokens(searchWithOffset) + for it.Next() { + ngram := make([]byte, len(it.At())) + copy(ngram, it.At()) + test.ngrams = append(test.ngrams, ngram) + } + tests = append(tests, test) + } + + res = tests[0] + for _, t := range tests[1:] { + res = newOrTest(res, t) } - return test + return res } // Matches implements the BloomTest interface @@ -228,7 +242,7 @@ func (b stringTest) MatchesWithPrefixBuf(bloom filter.Checker, buf []byte, prefi } type stringMatcherFilter struct { - test stringTest + test BloomTest } // Matches implements the log.Filterer interface @@ -244,26 +258,24 @@ func newStringFilterFunc(b NGramBuilder) log.NewMatcherFiltererFunc { } } -type notTest struct { - BloomTest -} - -func newNotTest(test BloomTest) BloomTest { - return notTest{BloomTest: test} -} - -func (b notTest) Matches(bloom filter.Checker) bool { - return !b.BloomTest.Matches(bloom) -} - -func (b notTest) MatchesWithPrefixBuf(bloom filter.Checker, buf []byte, prefixLen int) bool { - return !b.BloomTest.MatchesWithPrefixBuf(bloom, buf, prefixLen) -} - type orTest struct { left, right BloomTest } +// In addition to common `|= "foo" or "bar"`, +// orTest is particularly useful when testing skip-factors>0, which +// can result in different "sequences" of ngrams for a particular line +// and if either sequence matches the filter, the chunk is considered a match. +// For instance, with n=3,skip=1, the line "foobar" generates ngrams: +// ["foo", "oob", "oba", "bar"] +// Now let's say we want to search for the same "foobar". +// Note: we don't know which offset in the line this match may be, +// so we check every possible offset. The filter will match the ngrams: +// offset_0 creates ["foo", "oba"] +// offset_1 creates ["oob", "bar"] +// If either sequences are found in the bloom filter, the chunk is considered a match. +// Expanded, this is +// match == (("foo" && "oba") || ("oob" && "bar")) func newOrTest(left, right BloomTest) orTest { return orTest{ left: left, @@ -284,14 +296,11 @@ func newPatternTest(b NGramBuilder, match string) BloomTest { if err != nil { return MatchAll } - var test stringTest + + var res BloomTests + for _, l := range lit { - it := b.Tokens(string(l)) - for it.Next() { - ngram := make([]byte, len(it.At())) - copy(ngram, it.At()) - test.ngrams = append(test.ngrams, ngram) - } + res = append(res, newStringTest(b, string(l))) } - return test + return res } diff --git a/pkg/storage/bloom/v1/bloom_tester_test.go b/pkg/storage/bloom/v1/bloom_tester_test.go index 00db00340340f..81adbd8a86b54 100644 --- a/pkg/storage/bloom/v1/bloom_tester_test.go +++ b/pkg/storage/bloom/v1/bloom_tester_test.go @@ -3,231 +3,117 @@ package v1 import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/logql/syntax" - "github.com/grafana/loki/v3/pkg/storage/bloom/v1/filter" ) -func TestFiltersToBloomTests(t *testing.T) { +type fakeBloom []string + +// fakeBloom is a fake bloom filter that matches tokens exactly. +// It uses a tokenizer to build the tokens for a line +func newFakeBloom(tokenizer *NGramTokenizer, line string) (res fakeBloom) { + toks := tokenizer.Tokens(line) + for toks.Next() { + res = append(res, string(toks.At())) + } + return +} + +func (f fakeBloom) Test(data []byte) bool { + str := string(data) + for _, match := range f { + if str == match { + return true + } + } + return false +} + +func TestBloomQueryingLogic(t *testing.T) { + // All tested on 4skip1 + n := 4 + skip := 1 + tokenizer := NewNGramTokenizer(n, skip) + for _, tc := range []struct { - name string - query string - bloom filter.Checker - expectMatch bool + desc string + line string + query string + match bool + enabled bool }{ { - name: "No filters", - query: `{app="fake"}`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "Single filter", - query: `{app="fake"} |= "foo"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "Single filter no match", - query: `{app="fake"} |= "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: false, - }, - { - name: "two filters", - query: `{app="fake"} |= "foo" |= "bar"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "two filters no match", - query: `{app="fake"} |= "foo" |= "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: false, - }, - { - name: "notEq doesnt exist", - query: `{app="fake"} != "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "notEq exists", - query: `{app="fake"} != "foo"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match because it's NotEQ - }, - { - name: "or filter both match", - query: `{app="fake"} |= "foo" or "bar"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "or filter one right match", - query: `{app="fake"} |= "nope" or "foo"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "or filter one left match", - query: `{app="fake"} |= "foo" or "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "or filter no match", - query: `{app="fake"} |= "no" or "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: false, - }, - { - name: "Not or filter match", - query: `{app="fake"} != "nope" or "no"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "NotEq OR filter right exists", - query: `{app="fake"} != "nope" or "bar"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match because it's NotEQ - }, - { - name: "Not OR filter left exists", - query: `{app="fake"} != "foo" or "nope"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match because it's NotEQ - }, - { - name: "NotEq OR filter both exists", - query: `{app="fake"} != "foo" or "bar"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match because it's NotEQ - }, - { - name: "complex filter match", - query: `{app="fake"} |= "foo" |= "bar" or "baz" |= "fuzz" or "not" != "nope" != "no" or "none"`, - bloom: fakeBloom{"foo", "bar", "baz", "fuzz"}, - expectMatch: true, - }, - { - name: "regex match all star", - query: `{app="fake"} |~ ".*"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "regex match all plus", - query: `{app="fake"} |~ ".+"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "regex match all notEq", - query: `{app="fake"} !~ ".*"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match, - }, - { - name: "regex match", - query: `{app="fake"} |~ "nope|.*foo.*"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, + desc: "filter too short always match", + line: "foobar", + query: `{app="fake"} |= "z"`, + match: true, }, { - name: "regex no match", - query: `{app="fake"} |~ ".*not.*"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: false, + desc: "simple matcher", + line: "foobar", + query: `{app="fake"} |= "oobar"`, + match: true, }, { - name: "regex notEq right exists", - query: `{app="fake"} !~ "nope|.*foo.*"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, // Still should match because it's NotEQ + desc: "longer sequence", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |= "nopqrstuvwxyz"`, + match: true, }, { - name: "complex regex match", - query: `{app="fake"} |~ "(nope|.*not.*|.*foo.*)" or "(no|ba)" !~ "noz.*" or "(nope|not)"`, - bloom: fakeBloom{"foo", "bar", "baz", "fuzz"}, - expectMatch: true, + desc: "longer sequence nomatch", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |= "nopqrstuvwxyzzz"`, + match: false, }, { - name: "complex regex with notEq exists", - query: `{app="fake"} |~ "(nope|.*not.*|.*foo.*)" or "(no|ba)" !~ "noz.*"`, - bloom: fakeBloom{"foo", "bar", "baz", "fuzz", "noz"}, - expectMatch: true, // Still should match because it's NotEQ + desc: "pattern simple", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |> "<_>lmnopq<_>"`, + match: true, }, { - name: "line filter after line format", - query: `{app="fake"} |= "foo" | line_format "thisNewTextShouldMatch" |= "thisNewTextShouldMatch"`, - bloom: fakeBloom{"foo"}, - expectMatch: true, + desc: "pattern too short matches", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |> "<_>zzz<_>"`, + match: true, }, { - name: "pattern match exists", - query: `{app="fake"} |> "<_>foo<bar>"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, + desc: "pattern mix long success and short", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |> "<_>lmnop<_>zzz<_>"`, + match: true, }, { - name: "pattern match does not exist", - query: `{app="fake"} |> "<_>foo<bar>"`, - bloom: fakeBloom{"bar", "baz"}, - expectMatch: false, + desc: "pattern mix long fail and short", + line: "abcdefghijklmnopqrstuvwxyz", + query: `{app="fake"} |> "<_>zzzzz<_>zzz<_>"`, + match: false, }, { - name: "pattern not match exists", - query: `{app="fake"} !> "<_>foo<bar>"`, - bloom: fakeBloom{"foo", "bar"}, - expectMatch: true, - }, - { - name: "pattern not match does not exist", - query: `{app="fake"} !> "<_>foo<bar>"`, - bloom: fakeBloom{"bar", "baz"}, - expectMatch: true, - }, - { - name: "pattern all", - query: `{app="fake"} |> "<_>"`, - bloom: fakeBloom{"bar", "baz"}, - expectMatch: true, - }, - { - name: "pattern empty", - query: `{app="fake"} |> ""`, - bloom: fakeBloom{"bar", "baz"}, - expectMatch: true, + desc: "regexp disabled", + line: "foobarbaz", + query: `{app="fake"} |~ "(aaaaa|bbbbb)bazz"`, + match: true, }, } { - t.Run(tc.name, func(t *testing.T) { + + // shortcut to enable specific tests + tc.enabled = true + if !tc.enabled { + continue + } + t.Run(tc.desc, func(t *testing.T) { + bloom := newFakeBloom(tokenizer, tc.line) expr, err := syntax.ParseExpr(tc.query) - assert.NoError(t, err) + require.NoError(t, err) filters := ExtractTestableLineFilters(expr) + bloomTests := FiltersToBloomTest(tokenizer, filters...) + matched := bloomTests.Matches(bloom) - bloomTests := FiltersToBloomTest(fakeNgramBuilder{}, filters...) - assert.Equal(t, tc.expectMatch, bloomTests.Matches(tc.bloom)) - }) - } -} - -type fakeNgramBuilder struct{} + require.Equal(t, tc.match, matched) -func (f fakeNgramBuilder) Tokens(line string) Iterator[[]byte] { - return NewSliceIter[[]byte]([][]byte{[]byte(line)}) -} - -type fakeBloom []string - -func (f fakeBloom) Test(data []byte) bool { - str := string(data) - for _, match := range f { - if str == match { - return true - } + }) } - return false } diff --git a/pkg/storage/bloom/v1/bloom_tokenizer.go b/pkg/storage/bloom/v1/bloom_tokenizer.go index f529f22717639..96ad1420b303f 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer.go @@ -48,12 +48,12 @@ func NewBloomTokenizer(nGramLen, nGramSkip int, metrics *Metrics) *BloomTokenize } } -func (bt *BloomTokenizer) GetNGramLength() uint64 { - return uint64(bt.lineTokenizer.N) +func (bt *BloomTokenizer) N() uint64 { + return uint64(bt.lineTokenizer.N()) } -func (bt *BloomTokenizer) GetNGramSkip() uint64 { - return uint64(bt.lineTokenizer.Skip) +func (bt *BloomTokenizer) SkipFactor() uint64 { + return uint64(bt.lineTokenizer.SkipFactor()) } func clearCache(cache map[string]interface{}) { @@ -115,7 +115,7 @@ func (bt *BloomTokenizer) Populate(swb *SeriesWithBloom, chks Iterator[ChunkRefW chk = chks.At() itr = chk.Itr ) - tokenBuf, prefixLn = prefixedToken(bt.lineTokenizer.N, chk.Ref, tokenBuf) + tokenBuf, prefixLn = prefixedToken(bt.lineTokenizer.N(), chk.Ref, tokenBuf) // Iterate over lines in the chunk for itr.Next() && itr.Error() == nil { diff --git a/pkg/storage/bloom/v1/bloom_tokenizer_test.go b/pkg/storage/bloom/v1/bloom_tokenizer_test.go index 048c972d44c68..7d429ea8acb19 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer_test.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer_test.go @@ -82,13 +82,13 @@ func TestSetLineTokenizer(t *testing.T) { bt := NewBloomTokenizer(DefaultNGramLength, DefaultNGramSkip, metrics) // Validate defaults - require.Equal(t, bt.lineTokenizer.N, DefaultNGramLength) - require.Equal(t, bt.lineTokenizer.Skip, DefaultNGramSkip) + require.Equal(t, bt.lineTokenizer.N(), DefaultNGramLength) + require.Equal(t, bt.lineTokenizer.SkipFactor(), DefaultNGramSkip) // Set new tokenizer, and validate against that bt.lineTokenizer = NewNGramTokenizer(6, 7) - require.Equal(t, bt.lineTokenizer.N, 6) - require.Equal(t, bt.lineTokenizer.Skip, 7) + require.Equal(t, bt.lineTokenizer.N(), 6) + require.Equal(t, bt.lineTokenizer.SkipFactor(), 7) } func TestTokenizerPopulate(t *testing.T) { diff --git a/pkg/storage/bloom/v1/fuse_test.go b/pkg/storage/bloom/v1/fuse_test.go index f1cd77d9ebd4a..610a4ed7e6b8e 100644 --- a/pkg/storage/bloom/v1/fuse_test.go +++ b/pkg/storage/bloom/v1/fuse_test.go @@ -13,6 +13,18 @@ import ( "github.com/grafana/loki/v3/pkg/chunkenc" ) +// TODO(owen-d): this is unhinged from the data it represents. I'm leaving this solely so I don't +// have to refactor tests here in order to fix this elsewhere, but it can/should be fixed -- +// the skip & n len are hardcoded based on data that's passed to it elsewhere. +type fakeNgramBuilder struct{} + +func (f fakeNgramBuilder) N() int { return 4 } +func (f fakeNgramBuilder) SkipFactor() int { return 0 } + +func (f fakeNgramBuilder) Tokens(line string) Iterator[[]byte] { + return NewSliceIter[[]byte]([][]byte{[]byte(line)}) +} + func keysToBloomTest(keys [][]byte) BloomTest { var tokenizer fakeNgramBuilder tests := make(BloomTests, 0, len(keys)) diff --git a/pkg/storage/bloom/v1/tokenizer.go b/pkg/storage/bloom/v1/tokenizer.go index 557928dc750ca..4bad69771265a 100644 --- a/pkg/storage/bloom/v1/tokenizer.go +++ b/pkg/storage/bloom/v1/tokenizer.go @@ -20,19 +20,27 @@ func reassemble(buf []rune, ln, pos int, result []byte) []byte { // Iterable variants (more performant, less space) type NGramTokenizer struct { - N, Skip int + n, skip int buffer []rune // circular buffer used for ngram generation res []byte // buffer used for token generation } +func (t *NGramTokenizer) N() int { + return t.n +} + +func (t *NGramTokenizer) SkipFactor() int { + return t.skip +} + /* N-Grams (https://en.wikipedia.org/wiki/N-gram) are a series of 'n' adjacent characters in a string. These will be utilized for the bloom filters to allow for fuzzy searching. */ func NewNGramTokenizer(n, skip int) *NGramTokenizer { t := &NGramTokenizer{ - N: n, - Skip: skip, + n: n, + skip: skip, buffer: make([]rune, n+skip), res: make([]byte, 0, n*MaxRuneLen), // maximum 4 bytes per rune } @@ -45,8 +53,8 @@ func NewNGramTokenizer(n, skip int) *NGramTokenizer { // is not safe for use after subsequent calls to Next() func (t *NGramTokenizer) Tokens(line string) Iterator[[]byte] { return &NGramTokenIter{ - n: t.N, - skip: t.Skip, + n: t.N(), + skip: t.SkipFactor(), line: line, diff --git a/pkg/storage/bloom/v1/tokenizer_test.go b/pkg/storage/bloom/v1/tokenizer_test.go index 6472096cbf29e..c12788fe0f800 100644 --- a/pkg/storage/bloom/v1/tokenizer_test.go +++ b/pkg/storage/bloom/v1/tokenizer_test.go @@ -190,7 +190,7 @@ func BenchmarkTokens(b *testing.B) { { desc: "v2", f: func() func() { - buf, prefixLn := prefixedToken(v2Three.N, ChunkRef{}, nil) + buf, prefixLn := prefixedToken(v2Three.N(), ChunkRef{}, nil) return func() { itr := NewPrefixedTokenIter(buf, prefixLn, v2Three.Tokens(lorem)) for itr.Next() { @@ -207,7 +207,7 @@ func BenchmarkTokens(b *testing.B) { { desc: "v2", f: func() func() { - buf, prefixLn := prefixedToken(v2Three.N, ChunkRef{}, nil) + buf, prefixLn := prefixedToken(v2Three.N(), ChunkRef{}, nil) return func() { itr := NewPrefixedTokenIter(buf, prefixLn, v2ThreeSkip1.Tokens(lorem)) for itr.Next() { diff --git a/tools/tsdb/bloom-tester/readlib.go b/tools/tsdb/bloom-tester/readlib.go index 5886b13e2a9d2..3001b12554051 100644 --- a/tools/tsdb/bloom-tester/readlib.go +++ b/tools/tsdb/bloom-tester/readlib.go @@ -204,7 +204,7 @@ func analyzeRead(metrics *Metrics, sampler Sampler, shipper indexshipper.IndexSh bloomTokenizer.SetLineTokenizer(experiment.tokenizer) for gotIdx := range got { // for every chunk for _, queryExperiment := range queryExperiments { // for each search string - if len(queryExperiment.searchString) >= experiment.tokenizer.N+experiment.tokenizer.Skip { + if len(queryExperiment.searchString) >= experiment.tokenizer.N()+experiment.tokenizer.SkipFactor() { foundInChunk := false foundInSbf := false diff --git a/tools/tsdb/bloom-tester/tokenizer.go b/tools/tsdb/bloom-tester/tokenizer.go index c89844240455b..ac52c3de623e0 100644 --- a/tools/tsdb/bloom-tester/tokenizer.go +++ b/tools/tsdb/bloom-tester/tokenizer.go @@ -70,11 +70,11 @@ func (bt *BloomTokenizer) SetLineTokenizer(t *v1.NGramTokenizer) { } func (bt *BloomTokenizer) GetNGramLength() uint64 { - return uint64(bt.lineTokenizer.N) + return uint64(bt.lineTokenizer.N()) } func (bt *BloomTokenizer) GetNGramSkip() uint64 { - return uint64(bt.lineTokenizer.Skip) + return uint64(bt.lineTokenizer.SkipFactor()) } func newMetrics(r prometheus.Registerer, namespace, subsystem string) *metrics { @@ -146,7 +146,7 @@ func (bt *BloomTokenizer) PopulateSeriesWithBloom(seriesWithBloom *v1.SeriesWith for idx := range chunks { lc := chunks[idx].Data.(*chunkenc.Facade).LokiChunk() - tokenBuf, prefixLn := prefixedToken(bt.lineTokenizer.N, chunks[idx].ChunkRef) + tokenBuf, prefixLn := prefixedToken(bt.lineTokenizer.N(), chunks[idx].ChunkRef) chunkTotalUncompressedSize += lc.UncompressedSize() itr, err := lc.Iterator(
fix
fixup bloom testing (#12494)
717623b6c6551fedc3b25eacaa759f4135c2c984
2024-08-12 18:17:29
Vladyslav Diachenko
chore: manual changelog backport (#13852)
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index f37f14a95cc0d..dfc370a4ea44b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,203 @@ * **deps:** bumped dependencies versions to resolve CVEs ([#13789](https://github.com/grafana/loki/issues/13789)) ([34206cd](https://github.com/grafana/loki/commit/34206cd2d6290566034710ae6c2d08af8804bc91)) + +## [3.1.0](https://github.com/grafana/loki/compare/v3.0.0...v3.1.0) (2024-07-02) + + +### ⚠ BREAKING CHANGES + +* update helm chart to support distributed mode and 3.0 ([#12067](https://github.com/grafana/loki/issues/12067)) + +### Features + +* Add a version of the mixin dashboards for meta monitoring ([#12700](https://github.com/grafana/loki/issues/12700)) ([ec1a057](https://github.com/grafana/loki/commit/ec1a057a323ed1bd8de448e714a672b64140b691)) +* Add backoff to flush op ([#13140](https://github.com/grafana/loki/issues/13140)) ([9767807](https://github.com/grafana/loki/commit/9767807680cb4149c7b56345c531b62105a1b976)) +* add detected-fields command to logcli ([#12739](https://github.com/grafana/loki/issues/12739)) ([210ea93](https://github.com/grafana/loki/commit/210ea93a690b1b9746b3ff62bbd5d217a3bc8e8e)) +* Add ingester_chunks_flush_failures_total ([#12925](https://github.com/grafana/loki/issues/12925)) ([cc3694e](https://github.com/grafana/loki/commit/cc3694eecddaab579d08328cdab78a7d8a7bd720)) +* add lokitool ([#12166](https://github.com/grafana/loki/issues/12166)) ([7b7d3d4](https://github.com/grafana/loki/commit/7b7d3d4cd2c979c778d3741156f0d765a9e531b2)) +* Add metrics for number of patterns detected & evicted ([#12918](https://github.com/grafana/loki/issues/12918)) ([bc53b33](https://github.com/grafana/loki/commit/bc53b337218425af5b5ce69dcef56e27afec6647)) +* Add new Drain tokenizer that splits on most punctuation ([#13143](https://github.com/grafana/loki/issues/13143)) ([6a0fdd0](https://github.com/grafana/loki/commit/6a0fdd088091fc37e3e9424c78a2d6d587dbbb33)) +* Add pattern ingester support in SSD mode ([#12685](https://github.com/grafana/loki/issues/12685)) ([19bfef4](https://github.com/grafana/loki/commit/19bfef48cbad57468591e8214c4a5f390091f1e1)) +* add profile tagging to ingester ([#13068](https://github.com/grafana/loki/issues/13068)) ([00d3c7a](https://github.com/grafana/loki/commit/00d3c7a52d9f2b48fccb0cd5b105a2577b3d0305)) +* add recalculateOwnedStreams to check stream ownership if the ring is changed ([#13103](https://github.com/grafana/loki/issues/13103)) ([e7689b2](https://github.com/grafana/loki/commit/e7689b248dbe549b2ac61a0e335d8b5b999cc47d)) +* Add step param to Patterns Query API ([#12703](https://github.com/grafana/loki/issues/12703)) ([7b8533e](https://github.com/grafana/loki/commit/7b8533e435cf9d0466d3b147b2b3e0f6b3613fe9)) +* Add tokenizer interface for Drain Training ([#13069](https://github.com/grafana/loki/issues/13069)) ([797bb64](https://github.com/grafana/loki/commit/797bb641736a2355b4f8503c147fc0c8a814f19a)) +* add toleration for bloom components ([#12653](https://github.com/grafana/loki/issues/12653)) ([fcb2b0a](https://github.com/grafana/loki/commit/fcb2b0a16a7692ee0a705ce239375843a63246c7)) +* Add utf8 support to Pattern Lexer to support utf8 chars ([#13085](https://github.com/grafana/loki/issues/13085)) ([f6f8bab](https://github.com/grafana/loki/commit/f6f8babf83f3d90f4e6f3f9b732fe22382861f47)) +* add warnings to metadata context directly ([#12579](https://github.com/grafana/loki/issues/12579)) ([c4ac8cc](https://github.com/grafana/loki/commit/c4ac8cc009a75b616f867701c440797f655bcd1b)) +* Added getting started video ([#12975](https://github.com/grafana/loki/issues/12975)) ([8442dca](https://github.com/grafana/loki/commit/8442dca9d2341471996a73a011f206630c67e857)) +* Added Interactive Sandbox to Quickstart tutorial ([#12701](https://github.com/grafana/loki/issues/12701)) ([97212ea](https://github.com/grafana/loki/commit/97212eadf15c2b5ee2cd59b7c1df71f6177cfe7e)) +* Added video and updated Grafana Agent -> Alloy ([#13032](https://github.com/grafana/loki/issues/13032)) ([1432a3e](https://github.com/grafana/loki/commit/1432a3e84a7e5df18b8dc0e217121fd78da9e75e)) +* API: Expose optional label matcher for label names API ([#11982](https://github.com/grafana/loki/issues/11982)) ([8084259](https://github.com/grafana/loki/commit/808425953fa8a8eca3199b3664e43ceba362747a)) +* area/promtail: Added support to install wget on promtail docker image to support docker healthcheck ([#11711](https://github.com/grafana/loki/issues/11711)) ([ffe684c](https://github.com/grafana/loki/commit/ffe684c330bcd65f9b07a02d6f93bb475106becc)) +* **blooms:** Add counter metric for blocks that are not available at query time ([#12968](https://github.com/grafana/loki/issues/12968)) ([d6374bc](https://github.com/grafana/loki/commit/d6374bc2ce3041005842edd353a3bb010f467abe)) +* **blooms:** Add in-memory LRU cache for meta files ([#12862](https://github.com/grafana/loki/issues/12862)) ([fcd544c](https://github.com/grafana/loki/commit/fcd544c2d9d52b62d09e31c532a5cd2115f4d2bc)) +* **blooms:** Blooms/v2 encoding multipart series ([#13093](https://github.com/grafana/loki/issues/13093)) ([fbe7c55](https://github.com/grafana/loki/commit/fbe7c559b5ed153fb46a1965c24180011a558b85)) +* **blooms:** compute chunks once ([#12664](https://github.com/grafana/loki/issues/12664)) ([bc78d13](https://github.com/grafana/loki/commit/bc78d13d9b736bb9313403569d0f69e85663afce)) +* **blooms:** ignore individual bloom-gw failures ([#12863](https://github.com/grafana/loki/issues/12863)) ([4c9b22f](https://github.com/grafana/loki/commit/4c9b22f11077b560d21f086a84d42176e9196d5b)) +* **blooms:** ingester aware bounded impl ([#12840](https://github.com/grafana/loki/issues/12840)) ([7bbd8b5](https://github.com/grafana/loki/commit/7bbd8b5087d637ac592403c5daafda35353fe13d)) +* **bloom:** Skip attempts to filter chunks for which blooms have not been built ([#12961](https://github.com/grafana/loki/issues/12961)) ([a1b1eeb](https://github.com/grafana/loki/commit/a1b1eeb09583f04a36ebdb96f716f3f285b90adf)) +* **blooms:** limit bloom size during creation ([#12796](https://github.com/grafana/loki/issues/12796)) ([eac5622](https://github.com/grafana/loki/commit/eac56224b8e228a694090ffaee47300b23eeb13b)) +* **blooms:** record time spent resolving shards ([#12636](https://github.com/grafana/loki/issues/12636)) ([9c25985](https://github.com/grafana/loki/commit/9c25985b970865f054dfa9243cbe984d921df3c8)) +* **blooms:** Separate page buffer pools for series pages and bloom pages ([#12992](https://github.com/grafana/loki/issues/12992)) ([75ccf21](https://github.com/grafana/loki/commit/75ccf2160bfe647b1cb3daffb98869e9c1c44130)) +* Boilerplate for new bloom build planner and worker components. ([#12989](https://github.com/grafana/loki/issues/12989)) ([8978ecf](https://github.com/grafana/loki/commit/8978ecf0c85dfbe18b52632112e5be20eff411cf)) +* **cache:** Add `Cache-Control: no-cache` support for Loki instant queries. ([#12896](https://github.com/grafana/loki/issues/12896)) ([88e545f](https://github.com/grafana/loki/commit/88e545fc952d6ff55c61d079db920f00abc04865)) +* **canary:** Add test to check query results with and without cache. ([#13104](https://github.com/grafana/loki/issues/13104)) ([71507a2](https://github.com/grafana/loki/commit/71507a2b640ad071d88ee894e80235f93be73c3d)) +* Detected labels from store ([#12441](https://github.com/grafana/loki/issues/12441)) ([587a6d2](https://github.com/grafana/loki/commit/587a6d20e938f4f58e5a49563a3c267762cf89eb)) +* **detected-labels:** include labels with cardinality > 1 ([#13128](https://github.com/grafana/loki/issues/13128)) ([8be8364](https://github.com/grafana/loki/commit/8be8364435bb83dd134580ba6fc1f0bdb5474356)) +* **detectedFields:** add parser to response ([#12872](https://github.com/grafana/loki/issues/12872)) ([2b3ae48](https://github.com/grafana/loki/commit/2b3ae48d9be63183907dfd7163af6a980360c853)) +* **detectedFields:** Support multiple parsers to be returned for a single field ([#12899](https://github.com/grafana/loki/issues/12899)) ([19fef93](https://github.com/grafana/loki/commit/19fef9355fdd46911611dbec25df0f5a4e397d31)) +* Enable log volume endpoint by default ([#12628](https://github.com/grafana/loki/issues/12628)) ([397aa56](https://github.com/grafana/loki/commit/397aa56e157cbf733da548474a4bcae773e82362)) +* Enable log volume endpoint by default in helm ([#12690](https://github.com/grafana/loki/issues/12690)) ([e39677f](https://github.com/grafana/loki/commit/e39677f97b4ba27c90d9f8d2991441095e55b06e)) +* Generic logline placeholder replacement and tokenization ([#12799](https://github.com/grafana/loki/issues/12799)) ([4047902](https://github.com/grafana/loki/commit/40479029d74d588268956190d956a088aed682e1)) +* **helm:** Allow extraObject items as multiline strings ([#12397](https://github.com/grafana/loki/issues/12397)) ([af5be90](https://github.com/grafana/loki/commit/af5be900764acfe4bff54ceef164a4f660990f8a)) +* **helm:** Support for PVC Annotations for Non-Distributed Modes ([#12023](https://github.com/grafana/loki/issues/12023)) ([efdae3d](https://github.com/grafana/loki/commit/efdae3df14c47d627eb99e91466e0451db6e16f6)) +* improve performance of `first_over_time` and `last_over_time` queries by sharding them ([#11605](https://github.com/grafana/loki/issues/11605)) ([f66172e](https://github.com/grafana/loki/commit/f66172eed17f9418ab22615537c7b65b09de96e5)) +* improve syntax parser for pattern ([#12489](https://github.com/grafana/loki/issues/12489)) ([48dae44](https://github.com/grafana/loki/commit/48dae4417cca75a40d6a3bf16b0d976714e8db81)) +* include the stream we failed to create in the stream limit error message ([#12437](https://github.com/grafana/loki/issues/12437)) ([ec81991](https://github.com/grafana/loki/commit/ec81991f4d7f6d83a34dffb073d60c330c69e94d)) +* Increase drain max depth from 8 -> 30 ([#13063](https://github.com/grafana/loki/issues/13063)) ([d0a2859](https://github.com/grafana/loki/commit/d0a285926b7257d54cf948ba644c619a4b49a871)) +* Introduce `index audit` to `lokitool` ([#13008](https://github.com/grafana/loki/issues/13008)) ([47f0236](https://github.com/grafana/loki/commit/47f0236ea8f33a67a0a1abf6e6d6b3582661c4ba)) +* loki/main.go: Log which config file path is used on startup ([#12985](https://github.com/grafana/loki/issues/12985)) ([7a3338e](https://github.com/grafana/loki/commit/7a3338ead82e4c577652ab86e9a55faf200ac05a)) +* new stream count limiter ([#13006](https://github.com/grafana/loki/issues/13006)) ([1111595](https://github.com/grafana/loki/commit/1111595179c77f9303ebdfd362f14b1ac50044cb)) +* Optimize log parsing performance by using unsafe package ([#13223](https://github.com/grafana/loki/issues/13223)) ([9f31b25](https://github.com/grafana/loki/commit/9f31b25253502f035cfb6a831bcea7f778f427dd)) +* parameterise the MaximumEventAgeInSeconds, LogGroupName, and IAMRoleName for lambda-promtail CloudFormation template ([#12728](https://github.com/grafana/loki/issues/12728)) ([8892dc8](https://github.com/grafana/loki/commit/8892dc89231ebe7b05fc1c4e0b7647f328f9c1ce)) +* **promtail:** Support of RFC3164 aka BSD Syslog ([#12810](https://github.com/grafana/loki/issues/12810)) ([be41525](https://github.com/grafana/loki/commit/be4152576e6d8cb280fd65604199db7157981f07)) +* Querier: Split gRPC client into two. ([#12726](https://github.com/grafana/loki/issues/12726)) ([7b6f057](https://github.com/grafana/loki/commit/7b6f0577c3277b84230f0f2deba747b01ca2b2fa)) +* **reporting:** Report cpu usage ([#12970](https://github.com/grafana/loki/issues/12970)) ([87288d3](https://github.com/grafana/loki/commit/87288d37f9e9c1e90295bf785adbc4bfdb66fb30)) +* split detected fields queries ([#12491](https://github.com/grafana/loki/issues/12491)) ([6c33809](https://github.com/grafana/loki/commit/6c33809015bef8078b17dcb6b0701e930132f042)) +* Support negative numbers in LogQL ([#13091](https://github.com/grafana/loki/issues/13091)) ([6df81db](https://github.com/grafana/loki/commit/6df81db978b0157ab96fa0629a311f919dad1e8a)) +* Tune Patterns query drain instance ([#13137](https://github.com/grafana/loki/issues/13137)) ([30df31e](https://github.com/grafana/loki/commit/30df31e28b5c360ffed2dea3b47f515e4e24146d)) +* Update getting started demo to Loki 3.0 ([#12723](https://github.com/grafana/loki/issues/12723)) ([282e385](https://github.com/grafana/loki/commit/282e38548ceb96b1c518010c47b8eabf4317e8fd)) +* update helm chart to support distributed mode and 3.0 ([#12067](https://github.com/grafana/loki/issues/12067)) ([79b876b](https://github.com/grafana/loki/commit/79b876b65d55c54f4d532e98dc24743dea8bedec)) +* Update Loki monitoring docs to new meta monitoring helm ([#13176](https://github.com/grafana/loki/issues/13176)) ([b4d44f8](https://github.com/grafana/loki/commit/b4d44f89f997e59c84e69ed075341bb6e1371d08)) +* Updated best practises for labels ([#12749](https://github.com/grafana/loki/issues/12749)) ([6ebfbe6](https://github.com/grafana/loki/commit/6ebfbe658bbd92e3599ca4aff3bcfdd302d3cc32)) +* Updated SS and microservices deployment docs ([#13083](https://github.com/grafana/loki/issues/13083)) ([1b80458](https://github.com/grafana/loki/commit/1b80458e2eff2d41b9126a7529ee32ae1e269f05)) + + +### Bug Fixes + +* `codec` not initialized in downstream roundtripper ([#12873](https://github.com/grafana/loki/issues/12873)) ([b6049f6](https://github.com/grafana/loki/commit/b6049f6792492d5753626e5845b0094199463966)) +* Add a missing `continue` in fuse which may cause incorrect bloom test result ([#12650](https://github.com/grafana/loki/issues/12650)) ([0d1ebeb](https://github.com/grafana/loki/commit/0d1ebebd3afe9504506aaed0b7827318eb2d9cfe)) +* Add copyString function to symbolizer to avoid retaining memory ([#13146](https://github.com/grafana/loki/issues/13146)) ([86b119a](https://github.com/grafana/loki/commit/86b119ac7ba206d294eb257f99c308fe8452bd58)) +* add detected_level info when the info word appears on log message ([#13218](https://github.com/grafana/loki/issues/13218)) ([c9bfa3e](https://github.com/grafana/loki/commit/c9bfa3ebbf362b3d056879f0ef5f3e656f28c500)) +* Add missing Helm helper loki.hpa.apiVersion ([#12755](https://github.com/grafana/loki/issues/12755)) ([3070ea7](https://github.com/grafana/loki/commit/3070ea70bb05bffced6a8304f506b03ed4c8e2aa)) +* Add missing OTLP endpoint to nginx config ([#12709](https://github.com/grafana/loki/issues/12709)) ([8096748](https://github.com/grafana/loki/commit/8096748f1f205e766deab9438c4b2bc587facfc5)) +* add missing parentheses in meta monitoring dashboards ([#12802](https://github.com/grafana/loki/issues/12802)) ([151d0a5](https://github.com/grafana/loki/commit/151d0a58ac9f5aa67f944e6729720f5f70d07e27)) +* add retry middleware to the "limited" query roundtripper ([#13161](https://github.com/grafana/loki/issues/13161)) ([bb864b3](https://github.com/grafana/loki/commit/bb864b3ad63d61f5b091a9cc04246da2f44b2157)) +* allow cluster label override in bloom dashboards ([#13012](https://github.com/grafana/loki/issues/13012)) ([987e551](https://github.com/grafana/loki/commit/987e551f9e21b9a612dd0b6a3e60503ce6fe13a8)) +* **blooms:** bloomshipper no longer returns empty metas on fetch ([#13130](https://github.com/grafana/loki/issues/13130)) ([ad279e5](https://github.com/grafana/loki/commit/ad279e518cb252ef7e26283ec16540846dbd3acf)) +* **blooms:** Clean block directories recursively on startup ([#12895](https://github.com/grafana/loki/issues/12895)) ([7b77e31](https://github.com/grafana/loki/commit/7b77e310982147162777f9febfbcd98ec8a8c383)) +* **blooms:** Correctly return unfiltered chunks for series that are not mapped to any block ([#12774](https://github.com/grafana/loki/issues/12774)) ([c36b114](https://github.com/grafana/loki/commit/c36b1142c7acd6a13a3634ddbef71254040cff73)) +* **blooms:** Deduplicate filtered series and chunks ([#12791](https://github.com/grafana/loki/issues/12791)) ([3bf2d1f](https://github.com/grafana/loki/commit/3bf2d1fea08593bdf10dc8a6827998a6d8a8243c)) +* **blooms:** Disable metas cache on bloom gateway ([#12959](https://github.com/grafana/loki/issues/12959)) ([00bdd2f](https://github.com/grafana/loki/commit/00bdd2f5b703991b280317ceff0fcf2eed1847d9)) +* **blooms:** Do not fail requests when fetching metas from cache fails ([#12838](https://github.com/grafana/loki/issues/12838)) ([667076d](https://github.com/grafana/loki/commit/667076d9359c56118f1149f31a94c8a44bc171c7)) +* **blooms:** dont break iterator conventions ([#12808](https://github.com/grafana/loki/issues/12808)) ([1665e85](https://github.com/grafana/loki/commit/1665e853a0a6aa63f535bcc5a4bb67775723cc87)) +* **blooms:** Fix `partitionSeriesByDay` function ([#12900](https://github.com/grafana/loki/issues/12900)) ([738c274](https://github.com/grafana/loki/commit/738c274a5828aab4d88079c38400ddc705c0cb5d)) +* **blooms:** Fix a regression introduced with [#12774](https://github.com/grafana/loki/issues/12774) ([#12776](https://github.com/grafana/loki/issues/12776)) ([ecefb49](https://github.com/grafana/loki/commit/ecefb495084a59d25778af520041766e087598ba)) +* **blooms:** Fix findGaps when ownership goes to MaxUInt64 and that is covered by existing meta ([#12558](https://github.com/grafana/loki/issues/12558)) ([0ee2a61](https://github.com/grafana/loki/commit/0ee2a6126ae40a1d666f500c19efd639763f1bae)) +* **blooms:** Fully deduplicate chunks from FilterChunkRef responses ([#12807](https://github.com/grafana/loki/issues/12807)) ([a0f358f](https://github.com/grafana/loki/commit/a0f358fcc8295d93ee38b67738e8d90045c50dab)) +* **blooms:** Handle not found metas gracefully ([#12853](https://github.com/grafana/loki/issues/12853)) ([37c8822](https://github.com/grafana/loki/commit/37c88220b3a7f8268c48f1bf37f4eb11cdba1b5f)) +* **blooms:** Reset error on LazyBloomIter.Seek ([#12806](https://github.com/grafana/loki/issues/12806)) ([76ba24e](https://github.com/grafana/loki/commit/76ba24e3d8ce5e3c872442ce9d64505605ef0f53)) +* change log level since this is a known case ([#13029](https://github.com/grafana/loki/issues/13029)) ([ca030a5](https://github.com/grafana/loki/commit/ca030a5c4335b0258e83aebd8779ea4d348003f3)) +* close res body ([#12444](https://github.com/grafana/loki/issues/12444)) ([616977a](https://github.com/grafana/loki/commit/616977a942b63fb2ee7545e155abe246f6175308)) +* Correctly encode step when translating proto to http internally ([#13171](https://github.com/grafana/loki/issues/13171)) ([740551b](https://github.com/grafana/loki/commit/740551bb31e0c1806de8d87f02fa4f507aa24092)) +* crrect initialization of a few slices ([#12674](https://github.com/grafana/loki/issues/12674)) ([0eba448](https://github.com/grafana/loki/commit/0eba448fc70b78ca7cd612831c9d3be116faa7a2)) +* Defer closing blocks iter after checking error from loadWorkForGap ([#12934](https://github.com/grafana/loki/issues/12934)) ([cb1f5d9](https://github.com/grafana/loki/commit/cb1f5d9fca2908bd31a3c6bef38d49fe084d2939)) +* Do not filter out chunks for store when `From==Through` and `From==start` ([#13117](https://github.com/grafana/loki/issues/13117)) ([d9cc513](https://github.com/grafana/loki/commit/d9cc513fd2decf96d047d388136417c03ccdc682)) +* **docs:** broken link in getting started readme ([#12736](https://github.com/grafana/loki/issues/12736)) ([425a2d6](https://github.com/grafana/loki/commit/425a2d690c13592abf32f2ed2475676c3422ac51)) +* **docs:** Move promtail configuration to the correct doc ([#12737](https://github.com/grafana/loki/issues/12737)) ([1161846](https://github.com/grafana/loki/commit/1161846e19105e2669a5b388998722c23bd0f2f4)) +* Ensure Drain patterns are valid for LogQL pattern match filter ([#12815](https://github.com/grafana/loki/issues/12815)) ([fd2301f](https://github.com/grafana/loki/commit/fd2301fd62b18eb345bc43868b40343efc1a1f10)) +* errors reported by the race detector ([#13174](https://github.com/grafana/loki/issues/13174)) ([2b19dac](https://github.com/grafana/loki/commit/2b19dac82a97b1d75075eb87a4f7fdfed003c072)), closes [#8586](https://github.com/grafana/loki/issues/8586) +* Fix bloom deleter PR after merge ([#13167](https://github.com/grafana/loki/issues/13167)) ([c996349](https://github.com/grafana/loki/commit/c99634978cb189744946e6dc388f0cc4183e98f2)) +* Fix compactor matcher in the loki-deletion dashboard ([#12790](https://github.com/grafana/loki/issues/12790)) ([a03846b](https://github.com/grafana/loki/commit/a03846b4367cbb5a0aa445e539d92ae41e3f481a)) +* Fix duplicate enqueue item problem in bloom download queue when do sync download ([#13114](https://github.com/grafana/loki/issues/13114)) ([f98ff7f](https://github.com/grafana/loki/commit/f98ff7f58400b5f5a425fae003fb959bfb8c6454)) +* Fix for how the loop sync is done ([#12941](https://github.com/grafana/loki/issues/12941)) ([5cd850e](https://github.com/grafana/loki/commit/5cd850e0d02151c6f9c6285189b887b4929cfa12)) +* Fix incorrect sorting of chunks in bloom-filtered response since `ChunkRef.Cmp` method is used in reverse ([#12999](https://github.com/grafana/loki/issues/12999)) ([670cd89](https://github.com/grafana/loki/commit/670cd89aa8ffb8b852bca05fd0adb554e93ce796)) +* Fix indentation of query range values in helm ([#12577](https://github.com/grafana/loki/issues/12577)) ([9823f20](https://github.com/grafana/loki/commit/9823f2030a294e6dc9c50d6f956a7691df5d53df)) +* Fix log level detection ([#12651](https://github.com/grafana/loki/issues/12651)) ([6904a65](https://github.com/grafana/loki/commit/6904a6520d3b5599404b339577c7c3311e635da9)) +* Fix panic on requesting out-of-order Pattern samples ([#13010](https://github.com/grafana/loki/issues/13010)) ([2171f64](https://github.com/grafana/loki/commit/2171f6409f7157888df9637a635664c67b7ca844)) +* fix parsing of default per tenant otlp config ([#12836](https://github.com/grafana/loki/issues/12836)) ([7cc9a93](https://github.com/grafana/loki/commit/7cc9a9386a8f89dbec6a25435180ed4625ae6490)) +* fix setting of info log level when trying to detect level from log lines ([#12635](https://github.com/grafana/loki/issues/12635)) ([0831802](https://github.com/grafana/loki/commit/0831802a99243f9fe61f6cc8795739bf67e8d8e9)) +* Fix the lokitool imports ([#12673](https://github.com/grafana/loki/issues/12673)) ([6dce988](https://github.com/grafana/loki/commit/6dce98870d8c5c7054b3444d2fe4e66dad262a53)) +* Fixes read & backend replicas settings ([#12828](https://github.com/grafana/loki/issues/12828)) ([d751134](https://github.com/grafana/loki/commit/d7511343bcdfe77a6213599827ce0093b2949c18)) +* helm: Set compactor addr for distributed mode. ([#12748](https://github.com/grafana/loki/issues/12748)) ([521d40a](https://github.com/grafana/loki/commit/521d40a96a5c1c65c786c73ec374580fe767dd3b)) +* **helm:** Fix GEL image tag, bucket name and proxy URLs ([#12878](https://github.com/grafana/loki/issues/12878)) ([67ed2f7](https://github.com/grafana/loki/commit/67ed2f7092c8c0d97ba0bec08fde7ede65faa33f)) +* **helm:** fix query-frontend and ruler targetPort 'http-metrics' in Service template ([#13024](https://github.com/grafana/loki/issues/13024)) ([1ab9d27](https://github.com/grafana/loki/commit/1ab9d271c354caf0ba589691e6477fb9a19039f0)) +* **helm:** fix queryScheduler servicemonitor ([#12753](https://github.com/grafana/loki/issues/12753)) ([8101e21](https://github.com/grafana/loki/commit/8101e21f9973b8261de0ee3eb34fa4d7b88ddaac)) +* **helm:** fixed ingress paths mapping ([#12932](https://github.com/grafana/loki/issues/12932)) ([5ada92b](https://github.com/grafana/loki/commit/5ada92b190c671055bb09ca2dd234b6bac49289e)) +* **helm:** only default bucket names when using minio ([#12548](https://github.com/grafana/loki/issues/12548)) ([2e32ec5](https://github.com/grafana/loki/commit/2e32ec52d8766c0a5a75be30585402f1dce52cc5)) +* **helm:** Removed duplicate bucketNames from documentation and fixed key name `deploymentMode` ([#12641](https://github.com/grafana/loki/issues/12641)) ([0d8ff9e](https://github.com/grafana/loki/commit/0d8ff9ee7929b8facbdb469abe344c320d3bd5ce)) +* incorrect compactor matcher in loki-deletion dashboard mixin ([#12567](https://github.com/grafana/loki/issues/12567)) ([006f88c](https://github.com/grafana/loki/commit/006f88cef19d4d1fe14a40287ccdf534f6975475)) +* **indexstats:** do not collect stats from "IndexStats" lookups for other query types ([#12978](https://github.com/grafana/loki/issues/12978)) ([1f5291a](https://github.com/grafana/loki/commit/1f5291a4a3bd3c98c190d9a5dda32bbd78f18c3b)) +* Ingester zoneAwareReplication ([#12659](https://github.com/grafana/loki/issues/12659)) ([9edb0ce](https://github.com/grafana/loki/commit/9edb0ce140c4fe716a62e81e0fce747d92954f4c)) +* Introduce feature flag for [last|first]_over_time sharding. ([#13067](https://github.com/grafana/loki/issues/13067)) ([6e45550](https://github.com/grafana/loki/commit/6e4555010eab5a2b12caf9af2df5f0991362d754)) +* Invalidate caches when pipeline wrappers are disabled ([#12903](https://github.com/grafana/loki/issues/12903)) ([a772ed7](https://github.com/grafana/loki/commit/a772ed705c6506992cd1f2364b11fa60c1879f57)) +* **ksonnet:** Do not generate rbac for consul if you are using memberlist ([#12688](https://github.com/grafana/loki/issues/12688)) ([2d62fca](https://github.com/grafana/loki/commit/2d62fca05d6ec82196b46c956733c89439660754)) +* lambda-promtail, update s3 filename regex to allow finding of log files from AWS GovCloud regions ([#12482](https://github.com/grafana/loki/issues/12482)) ([7a81d26](https://github.com/grafana/loki/commit/7a81d264a4ba54efdb1d79d382fd4188c036aaee)) +* loki version prefix in Makefile ([#12514](https://github.com/grafana/loki/issues/12514)) ([dff72d2](https://github.com/grafana/loki/commit/dff72d2a52094fb2a831b5930cbfc67759b0978d)) +* loki-operational.libsonnet ([#12789](https://github.com/grafana/loki/issues/12789)) ([51a841f](https://github.com/grafana/loki/commit/51a841f20dbcbcb233836373ee246fb723ef70ba)) +* make detected fields work for both json and proto ([#12682](https://github.com/grafana/loki/issues/12682)) ([f68d1f7](https://github.com/grafana/loki/commit/f68d1f7fafa1ec55e90d3a253ef2ee8bb9c2e342)) +* make the tsdb filenames correctly reproducible from the identifier ([#12536](https://github.com/grafana/loki/issues/12536)) ([ec888ec](https://github.com/grafana/loki/commit/ec888ec8a564c7a93937c785c0540e7d2bcde20e)) +* Missing password for Loki-Canary when loki.auth_enabled is true ([#12411](https://github.com/grafana/loki/issues/12411)) ([68b23dc](https://github.com/grafana/loki/commit/68b23dc2b5c74b9175d5e24fb445748c422cb7b6)) +* mixin generation when cluster label is changed ([#12613](https://github.com/grafana/loki/issues/12613)) ([1ba7a30](https://github.com/grafana/loki/commit/1ba7a303566610363c0c36c87e7bc6bb492dfc93)) +* **mixin:** dashboards $__auto fix ([#12707](https://github.com/grafana/loki/issues/12707)) ([91ef72f](https://github.com/grafana/loki/commit/91ef72f742fe1f8621af15d8190c5c0d4d613ab9)) +* Mixins - Add missing log datasource on loki-deletion ([#13011](https://github.com/grafana/loki/issues/13011)) ([1948899](https://github.com/grafana/loki/commit/1948899999107e7f27f4b9faace64942abcdb41f)) +* **mixins:** Align loki-writes mixins with loki-reads ([#13022](https://github.com/grafana/loki/issues/13022)) ([757b776](https://github.com/grafana/loki/commit/757b776de39bf0fc0c6d1dd74e4a245d7a99023a)) +* **nix:** lambda-promtail vendor hash ([#12763](https://github.com/grafana/loki/issues/12763)) ([ae180d6](https://github.com/grafana/loki/commit/ae180d6e070946eb5359ecd63a9e01e02f160ce3)) +* not owned stream count ([#13030](https://github.com/grafana/loki/issues/13030)) ([4901a5c](https://github.com/grafana/loki/commit/4901a5c452fa6822a645f56e20e704db9366182a)) +* **operator:** add alertmanager client config to ruler template ([#13182](https://github.com/grafana/loki/issues/13182)) ([6148c37](https://github.com/grafana/loki/commit/6148c3760d701768e442186d4e7d574c7dc16c91)) +* **operator:** Bump golang builder to 1.21.9 ([#12503](https://github.com/grafana/loki/issues/12503)) ([f680ee0](https://github.com/grafana/loki/commit/f680ee0453d1b7d315774591293927b988bca223)) +* **operator:** Configure Loki to use virtual-host-style URLs for S3 AWS endpoints ([#12469](https://github.com/grafana/loki/issues/12469)) ([0084262](https://github.com/grafana/loki/commit/0084262269f4e2cb94d04e0cc0d40e9666177f06)) +* **operator:** Improve API documentation for schema version ([#13122](https://github.com/grafana/loki/issues/13122)) ([3a9f50f](https://github.com/grafana/loki/commit/3a9f50f5099a02e662b8ac10ddad0b36cd844161)) +* **operator:** Use a minimum value for replay memory ceiling ([#13066](https://github.com/grafana/loki/issues/13066)) ([4f3ed77](https://github.com/grafana/loki/commit/4f3ed77cb92c2ffd605743237e609c28f7841728)) +* Optimize regular initialization ([#12926](https://github.com/grafana/loki/issues/12926)) ([a46d14f](https://github.com/grafana/loki/commit/a46d14fb05ea14dd39095d2d71cd037acc2dfc51)) +* **orFilters:** fix multiple or filters would get wrong filtertype ([#13169](https://github.com/grafana/loki/issues/13169)) ([9981e9e](https://github.com/grafana/loki/commit/9981e9e40d4eda1a88d1aee0483cec1c098b92c7)) +* **otel:** Map 500 errors to 503 ([#13173](https://github.com/grafana/loki/issues/13173)) ([b31e04e](https://github.com/grafana/loki/commit/b31e04e3f1b7424cc52b518dc974a382a25bf045)) +* **packaging:** Require online network in systemd unit file for Loki and Promtail ([#12741](https://github.com/grafana/loki/issues/12741)) ([57f78b5](https://github.com/grafana/loki/commit/57f78b574ac9aa16f8322fb0edc4c7f0ec3cf6fa)) +* panics when ingester response is nil ([#12946](https://github.com/grafana/loki/issues/12946)) ([3cc28aa](https://github.com/grafana/loki/commit/3cc28aaf0ec08373fb104327827e6a062807e7ff)) +* promtail race fixes ([#12656](https://github.com/grafana/loki/issues/12656)) ([4e04d07](https://github.com/grafana/loki/commit/4e04d07168a8c5cb7086ced8486c6d584faa1045)) +* promtail; clean up metrics generated from logs after a config reload. ([#11882](https://github.com/grafana/loki/issues/11882)) ([39a7181](https://github.com/grafana/loki/commit/39a7181a600e9dc848dd3c0b0163c07242a46278)) +* **promtail:** Fix bug with Promtail config reloading getting stuck indefinitely ([#12795](https://github.com/grafana/loki/issues/12795)) ([4d761ac](https://github.com/grafana/loki/commit/4d761acd85b90cbdcafdf8d2547f0db14f6ae4dd)) +* **promtail:** Fix UDP receiver on syslog transport ([#10708](https://github.com/grafana/loki/issues/10708)) ([a00f1f1](https://github.com/grafana/loki/commit/a00f1f1b0b8f536f2cdac2f8857eb40c716aa696)) +* **promtail:** Handle docker logs when a log is split in multiple frames ([#12374](https://github.com/grafana/loki/issues/12374)) ([c0113db](https://github.com/grafana/loki/commit/c0113db4e8c4647188db6477d2ab265eda8dbb6c)) +* properly return http status codes from ingester to querier for RPC function calls ([#13134](https://github.com/grafana/loki/issues/13134)) ([691b174](https://github.com/grafana/loki/commit/691b1741386716095a4926cea5d5bb53caa88d9a)) +* **query sharding:** Generalize avg -> sum/count sharding using existing binop mapper ([#12599](https://github.com/grafana/loki/issues/12599)) ([11e7687](https://github.com/grafana/loki/commit/11e768726fb25f905de880ad2f5495b0f7fba156)) +* **regression:** reverts grafana/loki[#13039](https://github.com/grafana/loki/issues/13039) to prevent use-after-free corruptions ([#13162](https://github.com/grafana/loki/issues/13162)) ([41c5ee2](https://github.com/grafana/loki/commit/41c5ee21fc80177b50e74515ca568223e86ae56a)) +* Remove Hardcoded Bucket Name from EventBridge Example CloudFormation Template ([#12609](https://github.com/grafana/loki/issues/12609)) ([8c18463](https://github.com/grafana/loki/commit/8c18463285f214ba5b0b9a127bbe0071a2ec7d69)) +* remove unneccessary disk panels for ssd read path ([#13014](https://github.com/grafana/loki/issues/13014)) ([8d9fb68](https://github.com/grafana/loki/commit/8d9fb68ae5d4f26ddc2ae184a1cb6a3b2a2c2127)) +* remove unused parameter causing lint error ([#12801](https://github.com/grafana/loki/issues/12801)) ([33e82ec](https://github.com/grafana/loki/commit/33e82ec133b133e79666f7eec7d8d69954aa2aa3)) +* **spans:** corrects early-close for a few spans ([#12887](https://github.com/grafana/loki/issues/12887)) ([93aaf29](https://github.com/grafana/loki/commit/93aaf29e681053a1d23dcf855cfe92af8415260d)) +* temporarily moving from alloy -> alloy dev ([#13062](https://github.com/grafana/loki/issues/13062)) ([7ffe0fb](https://github.com/grafana/loki/commit/7ffe0fb6490e171e0100cb35ce6fde9377eff237)) +* Track bytes discarded by ingester. ([#12981](https://github.com/grafana/loki/issues/12981)) ([88c6711](https://github.com/grafana/loki/commit/88c671162f70e075f6aa43599aa560fe7b4b5627)) +* Update expected patterns when pruning ([#13079](https://github.com/grafana/loki/issues/13079)) ([2923a7d](https://github.com/grafana/loki/commit/2923a7d95818055a6ae9557d4b2f733b1af826f3)) +* update to build image 0.33.2, fixes bug with promtail windows DNS resolution ([#12732](https://github.com/grafana/loki/issues/12732)) ([759f42d](https://github.com/grafana/loki/commit/759f42dd50bb4896f5e568691ef32245bb8fb25a)) +* updated all dockerfiles go1.22 ([#12708](https://github.com/grafana/loki/issues/12708)) ([71a8f2c](https://github.com/grafana/loki/commit/71a8f2c2b11b419bd8c0af1f859671e5d8730448)) +* Updated Loki Otlp Ingest Configuration ([#12648](https://github.com/grafana/loki/issues/12648)) ([ff88f3c](https://github.com/grafana/loki/commit/ff88f3c3088a235eef5153a9d6414c161797a180)) +* upgrade old plugin for the loki-operational dashboard. ([#13016](https://github.com/grafana/loki/issues/13016)) ([d3c9cec](https://github.com/grafana/loki/commit/d3c9cec22891b45ed1cb93a9eacc5dad6a117fc5)) +* Use an intermediate env variable in GH workflow ([#12905](https://github.com/grafana/loki/issues/12905)) ([772616c](https://github.com/grafana/loki/commit/772616cd8f5cbac70374dd4a53f1714fb49a7a3b)) +* Use to the proper config names in warning messages ([#12114](https://github.com/grafana/loki/issues/12114)) ([4a05964](https://github.com/grafana/loki/commit/4a05964d5520d46d149f2a4e4709eee36c7fb418)) +* **workflows:** don't run metric collector on forks ([#12687](https://github.com/grafana/loki/issues/12687)) ([7253444](https://github.com/grafana/loki/commit/72534449a07cd9f410973f2d01772024e8e4b7ba)) + + +### Performance Improvements + +* **blooms:** Resolve bloom blocks on index gateway and shard by block address ([#12720](https://github.com/grafana/loki/issues/12720)) ([5540c92](https://github.com/grafana/loki/commit/5540c92d50fe25356231e05995d24a7ca342084b)) +* Improve Detected labels API ([#12816](https://github.com/grafana/loki/issues/12816)) ([e7fdeb9](https://github.com/grafana/loki/commit/e7fdeb974aff62c5775b9f98ebb2228000b28c8d)) +* Introduce fixed size memory pool for bloom querier ([#13039](https://github.com/grafana/loki/issues/13039)) ([fc26431](https://github.com/grafana/loki/commit/fc264310ce64fc082965a5d7f036e45a5a399c61)) +* Replace channel check with atomic bool in tailer.send() ([#12976](https://github.com/grafana/loki/issues/12976)) ([4a5edf1](https://github.com/grafana/loki/commit/4a5edf1a2af9e8af1842dc8d9b5482659d61031e)) +* TSDB: Add fast-path to `inversePostingsForMatcher` ([#12679](https://github.com/grafana/loki/issues/12679)) ([402d1d7](https://github.com/grafana/loki/commit/402d1d7c48ab4eb77835f4ebb9ef7cabf1dd7449)) + + +## [3.0.1](https://github.com/grafana/loki/compare/v3.0.0...v3.0.1) (2024-08-09) + + +### Bug Fixes + +* **deps:** bumped dependencies versions to resolve CVEs ([#13833](https://github.com/grafana/loki/pull/13833)) ([e13011d](https://github.com/grafana/loki/commit/e13011d91a77501ca4f659df9cf33f23085d3a35)) +* Fix nil pointer dereference in bloomstore initialisation ([#12869](https://github.com/grafana/loki/issues/12869)) ([167b468](https://github.com/grafana/loki/commit/167b468598bc70bbed6eed44826d3f9b85e1e0b8)), closes [#12270](https://github.com/grafana/loki/issues/12270) + + ## [3.0.0](https://github.com/grafana/loki/compare/v2.9.6...v3.0.0) (2024-04-08) Starting with the 3.0 release we began using [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) and [release-please](https://github.com/googleapis/release-please) to generate the changelog. As a result the format has changed slightly from previous releases. @@ -122,6 +319,15 @@ Starting with the 3.0 release we began using [conventional commits](https://www. * **loki** Background Cache: Fixes a bug that is causing the background queue size to be incremented twice for each enqueued item. [11776](https://github.com/grafana/loki/pull/11776) * **loki**: Parsing: String array elements were not being parsed correctly in JSON processing [11921](https://github.com/grafana/loki/pull/11921) + +## [2.9.10](https://github.com/grafana/loki/compare/v2.9.9...v2.9.10) (2024-08-09) + + +### Bug Fixes + +* Update dependencies versions to remove CVE ([#13835](https://github.com/grafana/loki/pull/13835)) ([567bef2](https://github.com/grafana/loki/commit/567bef286376663407c54f5da07fa00963ba5485)) + + ## [2.9.9](https://github.com/grafana/loki/compare/v2.9.8...v2.9.9) (2024-07-04) ### All Changes
chore
manual changelog backport (#13852)
a35ebceca5338b8e6aa92fe5d5e4e63b959f39c1
2025-02-11 00:59:23
Paul Rogers
chore(ci): Republish lambda promtail images (#16165)
false
diff --git a/.github/release-workflows.jsonnet b/.github/release-workflows.jsonnet index fd6f22f86bfde..5ae2b34fa2665 100644 --- a/.github/release-workflows.jsonnet +++ b/.github/release-workflows.jsonnet @@ -40,6 +40,100 @@ local weeklyImageJobs = { promtail: build.weeklyImage('promtail', 'clients/cmd/promtail', platform=platforms.all), }; +local lambdaPromtailJob = + job.new() + + job.withNeeds(['check']) + + job.withEnv({ + BUILD_TIMEOUT: imageBuildTimeoutMin, + GO_VERSION: goVersion, + IMAGE_PREFIX: 'public.ecr.aws/grafana', + RELEASE_LIB_REF: releaseLibRef, + RELEASE_REPO: 'grafana/loki', + REPO: 'loki', + }) + + job.withOutputs({ + image_digest_linux_amd64: '${{ steps.digest.outputs.digest_linux_amd64 }}', + image_digest_linux_arm64: '${{ steps.digest.outputs.digest_linux_arm64 }}', + image_name: '${{ steps.weekly-version.outputs.image_name }}', + image_tag: '${{ steps.weekly-version.outputs.image_version }}', + }) + + job.withStrategy({ + 'fail-fast': true, + matrix: { + include: [ + { arch: 'linux/amd64', runs_on: ['github-hosted-ubuntu-x64-small'] }, + { arch: 'linux/arm64', runs_on: ['github-hosted-ubuntu-arm64-small'] }, + ], + }, + }) + + { 'runs-on': '${{ matrix.runs_on }}' } + + job.withSteps([ + step.new('pull release library code', 'actions/checkout@v4') + + step.with({ + path: 'lib', + ref: '${{ env.RELEASE_LIB_REF }}', + repository: 'grafana/loki-release', + }), + step.new('pull code to release', 'actions/checkout@v4') + + step.with({ + path: 'release', + repository: '${{ env.RELEASE_REPO }}', + }), + step.new('setup node', 'actions/setup-node@v4') + + step.with({ + 'node-version': '20', + }), + step.new('Set up Docker buildx', 'docker/setup-buildx-action@v3'), + step.new('get-secrets', 'grafana/shared-workflows/actions/[email protected]') + + { id: 'get-secrets' } + + step.with({ + repo_secrets: ||| + ECR_ACCESS_KEY=aws-credentials:access_key_id + ECR_SECRET_KEY=aws-credentials:secret_access_key + |||, + }), + step.new('Configure AWS credentials', 'aws-actions/configure-aws-credentials@v4') + + step.with({ + 'aws-access-key-id': '${{ env.ECR_ACCESS_KEY }}', + 'aws-secret-access-key': '${{ env.ECR_SECRET_KEY }}', + 'aws-region': 'us-east-1', + }), + step.new('Login to Amazon ECR Public', 'aws-actions/amazon-ecr-login@v2') + + step.with({ + 'registry-type': 'public', + }), + step.new('Get weekly version') + + { id: 'weekly-version' } + + { 'working-directory': 'release' } + + step.withRun(||| + version=$(./tools/image-tag) + echo "image_version=$version" >> $GITHUB_OUTPUT + echo "image_name=${{ env.IMAGE_PREFIX }}/lambda-promtail" >> $GITHUB_OUTPUT + echo "image_full_name=${{ env.IMAGE_PREFIX }}/lambda-promtail:$version" >> $GITHUB_OUTPUT + |||), + step.new('Prepare tag name') + + { id: 'prepare-tag' } + + step.withRun(||| + arch=$(echo ${{ matrix.arch }} | cut -d'/' -f2) + echo "IMAGE_TAG=${{ steps.weekly-version.outputs.image_name }}:${{ steps.weekly-version.outputs.image_version }}-${arch}" >> $GITHUB_OUTPUT + |||), + step.new('Build and push', 'docker/build-push-action@v6') + + { id: 'build-push' } + + { 'timeout-minutes': '${{ fromJSON(env.BUILD_TIMEOUT) }}' } + + step.with({ + 'build-args': ||| + IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} + GO_VERSION=${{ env.GO_VERSION }} + |||, + context: 'release', + file: 'release/tools/lambda-promtail/Dockerfile', + outputs: 'type=image,push=true', + platform: '${{ matrix.arch }}', + provenance: false, + tags: '${{ steps.prepare-tag.outputs.IMAGE_TAG }}', + }), + ]); + { 'patch-release-pr.yml': std.manifestYamlDoc( lokiRelease.releasePRWorkflow( @@ -150,6 +244,8 @@ local weeklyImageJobs = { GO_VERSION: goVersion, }) for name in std.objectFields(weeklyImageJobs) + } + { + 'lambda-promtail-image': lambdaPromtailJob, } + { ['%s-manifest' % name]: job.new() diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 33687f191b1da..dffe7a56b341a 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,17 +1,15 @@ -name: "check" - -on: - pull_request: - push: - branches: - - main - -jobs: - check: - uses: "grafana/loki-release/.github/workflows/check.yml@main" - with: - build_image: "grafana/loki-build-image:0.34.5" - golang_ci_lint_version: "v1.60.3" - release_lib_ref: "main" - skip_validation: false - use_github_app_token: true +"jobs": + "check": + "uses": "grafana/loki-release/.github/workflows/check.yml@main" + "with": + "build_image": "grafana/loki-build-image:0.34.5" + "golang_ci_lint_version": "v1.60.3" + "release_lib_ref": "main" + "skip_validation": false + "use_github_app_token": true +"name": "check" +"on": + "pull_request": {} + "push": + "branches": + - "main" \ No newline at end of file diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml index 1c5bf213d670a..9dcecc67a0a50 100644 --- a/.github/workflows/images.yml +++ b/.github/workflows/images.yml @@ -1,345 +1,413 @@ -name: "Publish images" - -on: - push: - branches: - - "k[0-9]+*" - - "main" - workflow_dispatch: {} - -permissions: - contents: "write" - id-token: "write" - pull-requests: "write" - -env: - BUILD_TIMEOUT: "60" - GO_VERSION: "1.23.6" - IMAGE_PREFIX: "grafana" - RELEASE_LIB_REF: "main" - RELEASE_REPO: "grafana/loki" - -jobs: - check: - uses: "grafana/loki-release/.github/workflows/check.yml@main" - with: - build_image: "grafana/loki-build-image:0.34.5" - golang_ci_lint_version: "v1.60.3" - release_lib_ref: "main" - skip_validation: false - use_github_app_token: true - - loki-canary-boringcrypto-image: - needs: ["check"] - runs-on: "${{ matrix.runs_on }}" - outputs: - image_digest_linux_amd64: "${{ steps.digest.outputs.digest_linux_amd64 }}" - image_digest_linux_arm: "${{ steps.digest.outputs.digest_linux_arm }}" - image_digest_linux_arm64: "${{ steps.digest.outputs.digest_linux_arm64 }}" - image_name: "${{ steps.weekly-version.outputs.image_name }}" - image_tag: "${{ steps.weekly-version.outputs.image_version }}" - steps: - - name: "pull release library code" - uses: "actions/checkout@v4" - with: - path: "lib" - ref: "${{ env.RELEASE_LIB_REF }}" - repository: "grafana/loki-release" - - - name: "pull code to release" - uses: "actions/checkout@v4" - with: - path: "release" - repository: "${{ env.RELEASE_REPO }}" - - - name: "setup node" - uses: "actions/setup-node@v4" - with: - node-version: "20" - - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - - id: "weekly-version" - name: "Get weekly version" - working-directory: "release" - run: | - version=$(./tools/image-tag) - echo "image_version=$version" >> $GITHUB_OUTPUT - echo "image_name=${{ env.IMAGE_PREFIX }}/loki-canary-boringcrypto" >> $GITHUB_OUTPUT - echo "image_full_name=${{ env.IMAGE_PREFIX }}/loki-canary-boringcrypto:$version" >> $GITHUB_OUTPUT - - - id: "platform" - name: "Parse image platform" - working-directory: "release" - run: | - platform="$(echo "${{ matrix.arch }}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" - echo "platform=${platform}" >> $GITHUB_OUTPUT - echo "platform_short=$(echo ${{ matrix.arch }} | cut -d / -f 2)" >> $GITHUB_OUTPUT - - - id: "build-push" - name: "Build and push" - timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" - uses: "docker/build-push-action@v6" - with: - build-args: | - IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} - GO_VERSION=${{ env.GO_VERSION }} - context: "release" - file: "release/cmd/loki-canary-boringcrypto/Dockerfile" - outputs: "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" - platforms: "${{ matrix.arch }}" - provenance: true - tags: "${{ steps.weekly-version.outputs.image_name }}" - - - id: "digest" - name: "Process image digest" - working-directory: "release" - run: | - arch=$(echo ${{ matrix.arch }} | tr "/" "_") - echo "digest_$arch=${{ steps.build-push.outputs.digest }}" >> $GITHUB_OUTPUT - - strategy: - fail-fast: true - matrix: - include: - - arch: "linux/amd64" - runs_on: "github-hosted-ubuntu-x64-small" - - arch: "linux/arm64" - runs_on: "github-hosted-ubuntu-arm64-small" - - arch: "linux/arm" - runs_on: "github-hosted-ubuntu-arm64-small" - - loki-canary-boringcrypto-manifest: - needs: ["loki-canary-boringcrypto-image"] - runs-on: "ubuntu-latest" - steps: - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - - name: "Publish multi-arch manifest" - run: | - # Unfortunately there is no better way atm than having a separate named output for each digest - echo 'linux/arm64 ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_amd64 }}' - echo 'linux/amd64 ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm64 }}' - echo 'linux/arm ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm }}' - IMAGE=${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}:${{ needs.loki-canary-boringcrypto-image.outputs.image_tag }} - echo "Create multi-arch manifest for $IMAGE" - docker buildx imagetools create -t $IMAGE \ - ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_amd64 }} \ - ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm64 }} \ - ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm }} - docker buildx imagetools inspect $IMAGE - - loki-canary-image: - env: - BUILD_TIMEOUT: 60 - GO_VERSION: "1.23.6" - IMAGE_PREFIX: "grafana" - RELEASE_LIB_REF: "main" - RELEASE_REPO: "grafana/loki" - needs: - - check - outputs: - image_digest_linux_amd64: "${{ steps.digest.outputs.digest_linux_amd64 }}" - image_digest_linux_arm: "${{ steps.digest.outputs.digest_linux_arm }}" - image_digest_linux_arm64: "${{ steps.digest.outputs.digest_linux_arm64 }}" - image_name: "${{ steps.weekly-version.outputs.image_name }}" - image_tag: "${{ steps.weekly-version.outputs.image_version }}" - runs-on: "${{ matrix.runs_on }}" - steps: - - name: "pull release library code" - uses: "actions/checkout@v4" - with: - path: "lib" - ref: "${{ env.RELEASE_LIB_REF }}" - repository: "grafana/loki-release" - - name: "pull code to release" - uses: "actions/checkout@v4" - with: - path: "release" - repository: "${{ env.RELEASE_REPO }}" - - name: "setup node" - uses: "actions/setup-node@v4" - with: - node-version: 20 - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - id: "weekly-version" - name: "Get weekly version" - run: | +"jobs": + "check": + "uses": "grafana/loki-release/.github/workflows/check.yml@main" + "with": + "build_image": "grafana/loki-build-image:0.34.5" + "golang_ci_lint_version": "v1.60.3" + "release_lib_ref": "main" + "skip_validation": false + "use_github_app_token": true + "lambda-promtail-image": + "env": + "BUILD_TIMEOUT": 60 + "GO_VERSION": "1.23.6" + "IMAGE_PREFIX": "public.ecr.aws/grafana" + "RELEASE_LIB_REF": "main" + "RELEASE_REPO": "grafana/loki" + "REPO": "loki" + "needs": + - "check" + "outputs": + "image_digest_linux_amd64": "${{ steps.digest.outputs.digest_linux_amd64 }}" + "image_digest_linux_arm64": "${{ steps.digest.outputs.digest_linux_arm64 }}" + "image_name": "${{ steps.weekly-version.outputs.image_name }}" + "image_tag": "${{ steps.weekly-version.outputs.image_version }}" + "runs-on": "${{ matrix.runs_on }}" + "steps": + - "name": "pull release library code" + "uses": "actions/checkout@v4" + "with": + "path": "lib" + "ref": "${{ env.RELEASE_LIB_REF }}" + "repository": "grafana/loki-release" + - "name": "pull code to release" + "uses": "actions/checkout@v4" + "with": + "path": "release" + "repository": "${{ env.RELEASE_REPO }}" + - "name": "setup node" + "uses": "actions/setup-node@v4" + "with": + "node-version": "20" + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "id": "get-secrets" + "name": "get-secrets" + "uses": "grafana/shared-workflows/actions/[email protected]" + "with": + "repo_secrets": | + ECR_ACCESS_KEY=aws-credentials:access_key_id + ECR_SECRET_KEY=aws-credentials:secret_access_key + - "name": "Configure AWS credentials" + "uses": "aws-actions/configure-aws-credentials@v4" + "with": + "aws-access-key-id": "${{ env.ECR_ACCESS_KEY }}" + "aws-region": "us-east-1" + "aws-secret-access-key": "${{ env.ECR_SECRET_KEY }}" + - "name": "Login to Amazon ECR Public" + "uses": "aws-actions/amazon-ecr-login@v2" + "with": + "registry-type": "public" + - "id": "weekly-version" + "name": "Get weekly version" + "run": | + version=$(./tools/image-tag) + echo "image_version=$version" >> $GITHUB_OUTPUT + echo "image_name=${{ env.IMAGE_PREFIX }}/lambda-promtail" >> $GITHUB_OUTPUT + echo "image_full_name=${{ env.IMAGE_PREFIX }}/lambda-promtail:$version" >> $GITHUB_OUTPUT + "working-directory": "release" + - "id": "prepare-tag" + "name": "Prepare tag name" + "run": | + arch=$(echo ${{ matrix.arch }} | cut -d'/' -f2) + echo "IMAGE_TAG=${{ steps.weekly-version.outputs.image_name }}:${{ steps.weekly-version.outputs.image_version }}-${arch}" >> $GITHUB_OUTPUT + - "id": "build-push" + "name": "Build and push" + "timeout-minutes": "${{ fromJSON(env.BUILD_TIMEOUT) }}" + "uses": "docker/build-push-action@v6" + "with": + "build-args": | + IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} + GO_VERSION=${{ env.GO_VERSION }} + "context": "release" + "file": "release/tools/lambda-promtail/Dockerfile" + "outputs": "type=image,push=true" + "platform": "${{ matrix.arch }}" + "provenance": false + "tags": "${{ steps.prepare-tag.outputs.IMAGE_TAG }}" + "strategy": + "fail-fast": true + "matrix": + "include": + - "arch": "linux/amd64" + "runs_on": + - "github-hosted-ubuntu-x64-small" + - "arch": "linux/arm64" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + "loki-canary-boringcrypto-image": + "env": + "BUILD_TIMEOUT": 60 + "GO_VERSION": "1.23.6" + "IMAGE_PREFIX": "grafana" + "RELEASE_LIB_REF": "main" + "RELEASE_REPO": "grafana/loki" + "needs": + - "check" + "outputs": + "image_digest_linux_amd64": "${{ steps.digest.outputs.digest_linux_amd64 }}" + "image_digest_linux_arm": "${{ steps.digest.outputs.digest_linux_arm }}" + "image_digest_linux_arm64": "${{ steps.digest.outputs.digest_linux_arm64 }}" + "image_name": "${{ steps.weekly-version.outputs.image_name }}" + "image_tag": "${{ steps.weekly-version.outputs.image_version }}" + "runs-on": "${{ matrix.runs_on }}" + "steps": + - "name": "pull release library code" + "uses": "actions/checkout@v4" + "with": + "path": "lib" + "ref": "${{ env.RELEASE_LIB_REF }}" + "repository": "grafana/loki-release" + - "name": "pull code to release" + "uses": "actions/checkout@v4" + "with": + "path": "release" + "repository": "${{ env.RELEASE_REPO }}" + - "name": "setup node" + "uses": "actions/setup-node@v4" + "with": + "node-version": 20 + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "id": "weekly-version" + "name": "Get weekly version" + "run": | + version=$(./tools/image-tag) + echo "image_version=$version" >> $GITHUB_OUTPUT + echo "image_name=${{ env.IMAGE_PREFIX }}/loki-canary-boringcrypto" >> $GITHUB_OUTPUT + echo "image_full_name=${{ env.IMAGE_PREFIX }}/loki-canary-boringcrypto:$version" >> $GITHUB_OUTPUT + "working-directory": "release" + - "id": "platform" + "name": "Parse image platform" + "run": | + platform="$(echo "${{ matrix.arch }}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" + echo "platform=${platform}" >> $GITHUB_OUTPUT + echo "platform_short=$(echo ${{ matrix.arch }} | cut -d / -f 2)" >> $GITHUB_OUTPUT + "working-directory": "release" + - "id": "build-push" + "name": "Build and push" + "timeout-minutes": "${{ fromJSON(env.BUILD_TIMEOUT) }}" + "uses": "docker/build-push-action@v6" + "with": + "build-args": | + IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} + GO_VERSION=${{ env.GO_VERSION }} + "context": "release" + "file": "release/cmd/loki-canary-boringcrypto/Dockerfile" + "outputs": "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" + "platforms": "${{ matrix.arch }}" + "provenance": true + "tags": "${{ steps.weekly-version.outputs.image_name }}" + - "id": "digest" + "name": "Process image digest" + "run": | + arch=$(echo ${{ matrix.arch }} | tr "/" "_") + echo "digest_$arch=${{ steps.build-push.outputs.digest }}" >> $GITHUB_OUTPUT + "working-directory": "release" + "strategy": + "fail-fast": true + "matrix": + "include": + - "arch": "linux/amd64" + "runs_on": + - "github-hosted-ubuntu-x64-small" + - "arch": "linux/arm64" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + - "arch": "linux/arm" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + "loki-canary-boringcrypto-manifest": + "env": + "BUILD_TIMEOUT": 60 + "needs": + - "loki-canary-boringcrypto-image" + "runs-on": "ubuntu-latest" + "steps": + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "name": "Publish multi-arch manifest" + "run": | + # Unfortunately there is no better way atm than having a separate named output for each digest + echo 'linux/arm64 ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_amd64 }}' + echo 'linux/amd64 ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm64 }}' + echo 'linux/arm ${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm }}' + IMAGE=${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}:${{ needs.loki-canary-boringcrypto-image.outputs.image_tag }} + echo "Create multi-arch manifest for $IMAGE" + docker buildx imagetools create -t $IMAGE \ + ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_amd64 }} \ + ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm64 }} \ + ${{ needs.loki-canary-boringcrypto-image.outputs.image_name }}@${{ needs.loki-canary-boringcrypto-image.outputs.image_digest_linux_arm }} + docker buildx imagetools inspect $IMAGE + "loki-canary-image": + "env": + "BUILD_TIMEOUT": 60 + "GO_VERSION": "1.23.6" + "IMAGE_PREFIX": "grafana" + "RELEASE_LIB_REF": "main" + "RELEASE_REPO": "grafana/loki" + "needs": + - "check" + "outputs": + "image_digest_linux_amd64": "${{ steps.digest.outputs.digest_linux_amd64 }}" + "image_digest_linux_arm": "${{ steps.digest.outputs.digest_linux_arm }}" + "image_digest_linux_arm64": "${{ steps.digest.outputs.digest_linux_arm64 }}" + "image_name": "${{ steps.weekly-version.outputs.image_name }}" + "image_tag": "${{ steps.weekly-version.outputs.image_version }}" + "runs-on": "${{ matrix.runs_on }}" + "steps": + - "name": "pull release library code" + "uses": "actions/checkout@v4" + "with": + "path": "lib" + "ref": "${{ env.RELEASE_LIB_REF }}" + "repository": "grafana/loki-release" + - "name": "pull code to release" + "uses": "actions/checkout@v4" + "with": + "path": "release" + "repository": "${{ env.RELEASE_REPO }}" + - "name": "setup node" + "uses": "actions/setup-node@v4" + "with": + "node-version": 20 + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "id": "weekly-version" + "name": "Get weekly version" + "run": | version=$(./tools/image-tag) echo "image_version=$version" >> $GITHUB_OUTPUT echo "image_name=${{ env.IMAGE_PREFIX }}/loki-canary" >> $GITHUB_OUTPUT echo "image_full_name=${{ env.IMAGE_PREFIX }}/loki-canary:$version" >> $GITHUB_OUTPUT - working-directory: "release" - - id: "platform" - name: "Parse image platform" - run: | + "working-directory": "release" + - "id": "platform" + "name": "Parse image platform" + "run": | platform="$(echo "${{ matrix.arch }}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT echo "platform_short=$(echo ${{ matrix.arch }} | cut -d / -f 2)" >> $GITHUB_OUTPUT - working-directory: "release" - - - id: "build-push" - name: "Build and push" - timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" - uses: "docker/build-push-action@v6" - with: - build-args: | + "working-directory": "release" + - "id": "build-push" + "name": "Build and push" + "timeout-minutes": "${{ fromJSON(env.BUILD_TIMEOUT) }}" + "uses": "docker/build-push-action@v6" + "with": + "build-args": | IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} GO_VERSION=${{ env.GO_VERSION }} - context: "release" - file: "release/cmd/loki-canary/Dockerfile" - outputs: "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" - platforms: "${{ matrix.arch }}" - provenance: true - tags: "${{ steps.weekly-version.outputs.image_name }}" - - - id: "digest" - name: "Process image digest" - run: | + "context": "release" + "file": "release/cmd/loki-canary/Dockerfile" + "outputs": "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" + "platforms": "${{ matrix.arch }}" + "provenance": true + "tags": "${{ steps.weekly-version.outputs.image_name }}" + - "id": "digest" + "name": "Process image digest" + "run": | arch=$(echo ${{ matrix.arch }} | tr "/" "_") echo "digest_$arch=${{ steps.build-push.outputs.digest }}" >> $GITHUB_OUTPUT - working-directory: "release" - strategy: - fail-fast: true - matrix: - include: - - arch: linux/amd64 - runs_on: github-hosted-ubuntu-x64-small - - arch: linux/arm64 - runs_on: github-hosted-ubuntu-arm64-small - - arch: linux/arm - runs_on: github-hosted-ubuntu-arm64-small - - loki-canary-manifest: - needs: ["loki-canary-image"] - runs-on: "ubuntu-latest" - steps: - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - - name: "Publish multi-arch manifest" - run: | - # Unfortunately there is no better way atm than having a separate named output for each digest - echo 'linux/arm64 ${{ needs.loki-canary-image.outputs.image_digest_linux_amd64 }}' - echo 'linux/amd64 ${{ needs.loki-canary-image.outputs.image_digest_linux_arm64 }}' - echo 'linux/arm ${{ needs.loki-canary-image.outputs.image_digest_linux_arm }}' - IMAGE=${{ needs.loki-canary-image.outputs.image_name }}:${{ needs.loki-canary-image.outputs.image_tag }} - echo "Create multi-arch manifest for $IMAGE" - docker buildx imagetools create -t $IMAGE \ - ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_amd64 }} \ - ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_arm64 }} \ - ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_arm }} - docker buildx imagetools inspect $IMAGE - - loki-image: - env: - BUILD_TIMEOUT: 60 - GO_VERSION: "1.23.6" - IMAGE_PREFIX: "grafana" - RELEASE_LIB_REF: "main" - RELEASE_REPO: "grafana/loki" - needs: - - check - outputs: - image_digest_linux_amd64: "${{ steps.digest.outputs.digest_linux_amd64 }}" - image_digest_linux_arm: "${{ steps.digest.outputs.digest_linux_arm }}" - image_digest_linux_arm64: "${{ steps.digest.outputs.digest_linux_arm64 }}" - image_name: "${{ steps.weekly-version.outputs.image_name }}" - image_tag: "${{ steps.weekly-version.outputs.image_version }}" - runs-on: "${{ matrix.runs_on }}" - steps: - - name: "pull release library code" - uses: "actions/checkout@v4" - with: - path: "lib" - ref: "${{ env.RELEASE_LIB_REF }}" - repository: "grafana/loki-release" - - name: "pull code to release" - uses: "actions/checkout@v4" - with: - path: "release" - repository: "${{ env.RELEASE_REPO }}" - - name: "setup node" - uses: "actions/setup-node@v4" - with: - node-version: 20 - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - id: "weekly-version" - name: "Get weekly version" - run: | + "working-directory": "release" + "strategy": + "fail-fast": true + "matrix": + "include": + - "arch": "linux/amd64" + "runs_on": + - "github-hosted-ubuntu-x64-small" + - "arch": "linux/arm64" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + - "arch": "linux/arm" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + "loki-canary-manifest": + "env": + "BUILD_TIMEOUT": 60 + "needs": + - "loki-canary-image" + "runs-on": "ubuntu-latest" + "steps": + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "name": "Publish multi-arch manifest" + "run": | + # Unfortunately there is no better way atm than having a separate named output for each digest + echo 'linux/arm64 ${{ needs.loki-canary-image.outputs.image_digest_linux_amd64 }}' + echo 'linux/amd64 ${{ needs.loki-canary-image.outputs.image_digest_linux_arm64 }}' + echo 'linux/arm ${{ needs.loki-canary-image.outputs.image_digest_linux_arm }}' + IMAGE=${{ needs.loki-canary-image.outputs.image_name }}:${{ needs.loki-canary-image.outputs.image_tag }} + echo "Create multi-arch manifest for $IMAGE" + docker buildx imagetools create -t $IMAGE \ + ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_amd64 }} \ + ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_arm64 }} \ + ${{ needs.loki-canary-image.outputs.image_name }}@${{ needs.loki-canary-image.outputs.image_digest_linux_arm }} + docker buildx imagetools inspect $IMAGE + "loki-image": + "env": + "BUILD_TIMEOUT": 60 + "GO_VERSION": "1.23.6" + "IMAGE_PREFIX": "grafana" + "RELEASE_LIB_REF": "main" + "RELEASE_REPO": "grafana/loki" + "needs": + - "check" + "outputs": + "image_digest_linux_amd64": "${{ steps.digest.outputs.digest_linux_amd64 }}" + "image_digest_linux_arm": "${{ steps.digest.outputs.digest_linux_arm }}" + "image_digest_linux_arm64": "${{ steps.digest.outputs.digest_linux_arm64 }}" + "image_name": "${{ steps.weekly-version.outputs.image_name }}" + "image_tag": "${{ steps.weekly-version.outputs.image_version }}" + "runs-on": "${{ matrix.runs_on }}" + "steps": + - "name": "pull release library code" + "uses": "actions/checkout@v4" + "with": + "path": "lib" + "ref": "${{ env.RELEASE_LIB_REF }}" + "repository": "grafana/loki-release" + - "name": "pull code to release" + "uses": "actions/checkout@v4" + "with": + "path": "release" + "repository": "${{ env.RELEASE_REPO }}" + - "name": "setup node" + "uses": "actions/setup-node@v4" + "with": + "node-version": 20 + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "id": "weekly-version" + "name": "Get weekly version" + "run": | version=$(./tools/image-tag) echo "image_version=$version" >> $GITHUB_OUTPUT echo "image_name=${{ env.IMAGE_PREFIX }}/loki" >> $GITHUB_OUTPUT echo "image_full_name=${{ env.IMAGE_PREFIX }}/loki:$version" >> $GITHUB_OUTPUT - working-directory: "release" - - id: "platform" - name: "Parse image platform" - run: | + "working-directory": "release" + - "id": "platform" + "name": "Parse image platform" + "run": | platform="$(echo "${{ matrix.arch }}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT echo "platform_short=$(echo ${{ matrix.arch }} | cut -d / -f 2)" >> $GITHUB_OUTPUT - working-directory: "release" - - id: "build-push" - name: "Build and push" - timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" - uses: "docker/build-push-action@v6" - with: - build-args: | + "working-directory": "release" + - "id": "build-push" + "name": "Build and push" + "timeout-minutes": "${{ fromJSON(env.BUILD_TIMEOUT) }}" + "uses": "docker/build-push-action@v6" + "with": + "build-args": | IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} GO_VERSION=${{ env.GO_VERSION }} - context: "release" - file: "release/cmd/loki/Dockerfile" - outputs: "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" - platforms: "${{ matrix.arch }}" - provenance: true - tags: "${{ steps.weekly-version.outputs.image_name }}" - - id: "digest" - name: "Process image digest" - run: | + "context": "release" + "file": "release/cmd/loki/Dockerfile" + "outputs": "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" + "platforms": "${{ matrix.arch }}" + "provenance": true + "tags": "${{ steps.weekly-version.outputs.image_name }}" + - "id": "digest" + "name": "Process image digest" + "run": | arch=$(echo ${{ matrix.arch }} | tr "/" "_") echo "digest_$arch=${{ steps.build-push.outputs.digest }}" >> $GITHUB_OUTPUT - working-directory: "release" - strategy: - fail-fast: true - matrix: - include: - - arch: linux/amd64 - runs_on: github-hosted-ubuntu-x64-small - - arch: linux/arm64 - runs_on: github-hosted-ubuntu-arm64-small - - arch: linux/arm - runs_on: github-hosted-ubuntu-arm64-small - - loki-manifest: - env: - BUILD_TIMEOUT: 60 - needs: - - loki-image - runs-on: ubuntu-latest - steps: - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - name: "Publish multi-arch manifest" - run: | + "working-directory": "release" + "strategy": + "fail-fast": true + "matrix": + "include": + - "arch": "linux/amd64" + "runs_on": + - "github-hosted-ubuntu-x64-small" + - "arch": "linux/arm64" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + - "arch": "linux/arm" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + "loki-manifest": + "env": + "BUILD_TIMEOUT": 60 + "needs": + - "loki-image" + "runs-on": "ubuntu-latest" + "steps": + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "name": "Publish multi-arch manifest" + "run": | # Unfortunately there is no better way atm than having a separate named output for each digest echo 'linux/arm64 ${{ needs.loki-image.outputs.image_digest_linux_amd64 }}' echo 'linux/amd64 ${{ needs.loki-image.outputs.image_digest_linux_arm64 }}' @@ -351,109 +419,122 @@ jobs: ${{ needs.loki-image.outputs.image_name }}@${{ needs.loki-image.outputs.image_digest_linux_arm64 }} \ ${{ needs.loki-image.outputs.image_name }}@${{ needs.loki-image.outputs.image_digest_linux_arm }} docker buildx imagetools inspect $IMAGE - - promtail-image: - env: - BUILD_TIMEOUT: 60 - GO_VERSION: "1.23.6" - IMAGE_PREFIX: "grafana" - RELEASE_LIB_REF: "main" - RELEASE_REPO: "grafana/loki" - needs: - - check - outputs: - image_digest_linux_amd64: "${{ steps.digest.outputs.digest_linux_amd64 }}" - image_digest_linux_arm: "${{ steps.digest.outputs.digest_linux_arm }}" - image_digest_linux_arm64: "${{ steps.digest.outputs.digest_linux_arm64 }}" - image_name: "${{ steps.weekly-version.outputs.image_name }}" - image_tag: "${{ steps.weekly-version.outputs.image_version }}" - runs-on: "${{ matrix.runs_on }}" - steps: - - name: "pull release library code" - uses: "actions/checkout@v4" - with: - path: "lib" - ref: "${{ env.RELEASE_LIB_REF }}" - repository: "grafana/loki-release" - - name: "pull code to release" - uses: "actions/checkout@v4" - with: - path: "release" - repository: "${{ env.RELEASE_REPO }}" - - name: "setup node" - uses: "actions/setup-node@v4" - with: - node-version: 20 - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - id: "weekly-version" - name: "Get weekly version" - run: | + "promtail-image": + "env": + "BUILD_TIMEOUT": 60 + "GO_VERSION": "1.23.6" + "IMAGE_PREFIX": "grafana" + "RELEASE_LIB_REF": "main" + "RELEASE_REPO": "grafana/loki" + "needs": + - "check" + "outputs": + "image_digest_linux_amd64": "${{ steps.digest.outputs.digest_linux_amd64 }}" + "image_digest_linux_arm": "${{ steps.digest.outputs.digest_linux_arm }}" + "image_digest_linux_arm64": "${{ steps.digest.outputs.digest_linux_arm64 }}" + "image_name": "${{ steps.weekly-version.outputs.image_name }}" + "image_tag": "${{ steps.weekly-version.outputs.image_version }}" + "runs-on": "${{ matrix.runs_on }}" + "steps": + - "name": "pull release library code" + "uses": "actions/checkout@v4" + "with": + "path": "lib" + "ref": "${{ env.RELEASE_LIB_REF }}" + "repository": "grafana/loki-release" + - "name": "pull code to release" + "uses": "actions/checkout@v4" + "with": + "path": "release" + "repository": "${{ env.RELEASE_REPO }}" + - "name": "setup node" + "uses": "actions/setup-node@v4" + "with": + "node-version": 20 + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "id": "weekly-version" + "name": "Get weekly version" + "run": | version=$(./tools/image-tag) echo "image_version=$version" >> $GITHUB_OUTPUT echo "image_name=${{ env.IMAGE_PREFIX }}/promtail" >> $GITHUB_OUTPUT echo "image_full_name=${{ env.IMAGE_PREFIX }}/promtail:$version" >> $GITHUB_OUTPUT - working-directory: "release" - - id: "platform" - name: "Parse image platform" - run: | + "working-directory": "release" + - "id": "platform" + "name": "Parse image platform" + "run": | platform="$(echo "${{ matrix.arch }}" | sed "s/\(.*\)\/\(.*\)/\1-\2/")" echo "platform=${platform}" >> $GITHUB_OUTPUT echo "platform_short=$(echo ${{ matrix.arch }} | cut -d / -f 2)" >> $GITHUB_OUTPUT - working-directory: "release" - - id: "build-push" - name: "Build and push" - timeout-minutes: "${{ fromJSON(env.BUILD_TIMEOUT) }}" - uses: "docker/build-push-action@v6" - with: - build-args: | + "working-directory": "release" + - "id": "build-push" + "name": "Build and push" + "timeout-minutes": "${{ fromJSON(env.BUILD_TIMEOUT) }}" + "uses": "docker/build-push-action@v6" + "with": + "build-args": | IMAGE_TAG=${{ steps.weekly-version.outputs.image_version }} GO_VERSION=${{ env.GO_VERSION }} - context: "release" - file: "release/clients/cmd/promtail/Dockerfile" - outputs: "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" - platforms: "${{ matrix.arch }}" - provenance: true - tags: "${{ steps.weekly-version.outputs.image_name }}" - - id: "digest" - name: "Process image digest" - run: | + "context": "release" + "file": "release/clients/cmd/promtail/Dockerfile" + "outputs": "push-by-digest=true,type=image,name=${{ steps.weekly-version.outputs.image_name }},push=true" + "platforms": "${{ matrix.arch }}" + "provenance": true + "tags": "${{ steps.weekly-version.outputs.image_name }}" + - "id": "digest" + "name": "Process image digest" + "run": | arch=$(echo ${{ matrix.arch }} | tr "/" "_") echo "digest_$arch=${{ steps.build-push.outputs.digest }}" >> $GITHUB_OUTPUT - working-directory: "release" - strategy: - fail-fast: true - matrix: - include: - - arch: linux/amd64 - runs_on: github-hosted-ubuntu-x64-small - - arch: linux/arm64 - runs_on: github-hosted-ubuntu-arm64-small - - arch: linux/arm - runs_on: github-hosted-ubuntu-arm64-small - - promtail-manifest: - needs: ["promtail-image"] - runs-on: "ubuntu-latest" - steps: - - name: "Set up Docker buildx" - uses: "docker/setup-buildx-action@v3" - - - name: "Login to DockerHub (from Vault)" - uses: "grafana/shared-workflows/actions/dockerhub-login@main" - - - name: "Publish multi-arch manifest" - run: | - # Unfortunately there is no better way atm than having a separate named output for each digest - echo 'linux/arm64 ${{ needs.promtail-image.outputs.image_digest_linux_amd64 }}' - echo 'linux/amd64 ${{ needs.promtail-image.outputs.image_digest_linux_arm64 }}' - echo 'linux/arm ${{ needs.promtail-image.outputs.image_digest_linux_arm }}' - IMAGE=${{ needs.promtail-image.outputs.image_name }}:${{ needs.promtail-image.outputs.image_tag }} - echo "Create multi-arch manifest for $IMAGE" - docker buildx imagetools create -t $IMAGE \ - ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_amd64 }} \ - ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_arm64 }} \ - ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_arm }} - docker buildx imagetools inspect $IMAGE + "working-directory": "release" + "strategy": + "fail-fast": true + "matrix": + "include": + - "arch": "linux/amd64" + "runs_on": + - "github-hosted-ubuntu-x64-small" + - "arch": "linux/arm64" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + - "arch": "linux/arm" + "runs_on": + - "github-hosted-ubuntu-arm64-small" + "promtail-manifest": + "env": + "BUILD_TIMEOUT": 60 + "needs": + - "promtail-image" + "runs-on": "ubuntu-latest" + "steps": + - "name": "Set up Docker buildx" + "uses": "docker/setup-buildx-action@v3" + - "name": "Login to DockerHub (from Vault)" + "uses": "grafana/shared-workflows/actions/dockerhub-login@main" + - "name": "Publish multi-arch manifest" + "run": | + # Unfortunately there is no better way atm than having a separate named output for each digest + echo 'linux/arm64 ${{ needs.promtail-image.outputs.image_digest_linux_amd64 }}' + echo 'linux/amd64 ${{ needs.promtail-image.outputs.image_digest_linux_arm64 }}' + echo 'linux/arm ${{ needs.promtail-image.outputs.image_digest_linux_arm }}' + IMAGE=${{ needs.promtail-image.outputs.image_name }}:${{ needs.promtail-image.outputs.image_tag }} + echo "Create multi-arch manifest for $IMAGE" + docker buildx imagetools create -t $IMAGE \ + ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_amd64 }} \ + ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_arm64 }} \ + ${{ needs.promtail-image.outputs.image_name }}@${{ needs.promtail-image.outputs.image_digest_linux_arm }} + docker buildx imagetools inspect $IMAGE +"name": "Publish images" +"on": + "push": + "branches": + - "k[0-9]+*" + - "main" + "workflow_dispatch": {} +"permissions": + "contents": "write" + "id-token": "write" + "pull-requests": "write" \ No newline at end of file
chore
Republish lambda promtail images (#16165)
fa188936f22d48960c362aca43413f987428d876
2019-10-15 17:54:38
Nic Roland
docs(helm): fix broken link to grafana datasource (#1152)
false
diff --git a/production/helm/README.md b/production/helm/README.md index 92499f3152787..d2a3055b0e890 100644 --- a/production/helm/README.md +++ b/production/helm/README.md @@ -85,7 +85,7 @@ $ kubectl port-forward --namespace <YOUR-NAMESPACE> service/loki-grafana 3000:80 ``` Navigate to http://localhost:3000 and login with `admin` and the password output above. -Then follow the [instructions for adding the loki datasource](/docs/querying.md#grafana), using the URL `http://loki:3100/`. +Then follow the [instructions for adding the loki datasource](/docs/getting-started/grafana.md), using the URL `http://loki:3100/`. ## Run Loki behind https ingress
docs
fix broken link to grafana datasource (#1152)
37c88220b3a7f8268c48f1bf37f4eb11cdba1b5f
2024-05-02 14:14:43
Christian Haudum
fix(blooms): Handle not found metas gracefully (#12853)
false
diff --git a/pkg/storage/stores/shipper/bloomshipper/client.go b/pkg/storage/stores/shipper/bloomshipper/client.go index c637b983cb957..1c2314691caef 100644 --- a/pkg/storage/stores/shipper/bloomshipper/client.go +++ b/pkg/storage/stores/shipper/bloomshipper/client.go @@ -12,6 +12,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/go-kit/log/level" "github.com/grafana/dskit/concurrency" "github.com/pkg/errors" "github.com/prometheus/common/model" @@ -388,7 +389,11 @@ func (b *BloomClient) GetMetas(ctx context.Context, refs []MetaRef) ([]Meta, err err := concurrency.ForEachJob(ctx, len(refs), b.concurrency, func(ctx context.Context, idx int) error { meta, err := b.GetMeta(ctx, refs[idx]) if err != nil { - return err + key := b.KeyResolver.Meta(refs[idx]).Addr() + if !b.IsObjectNotFoundErr(err) { + return fmt.Errorf("failed to get meta file %s: %w", key, err) + } + level.Error(b.logger).Log("msg", "failed to get meta file", "ref", key, "err", err) } results[idx] = meta return nil @@ -396,20 +401,22 @@ func (b *BloomClient) GetMetas(ctx context.Context, refs []MetaRef) ([]Meta, err return results, err } +// GetMeta fetches the meta file for given MetaRef from object storage and +// decodes the JSON data into a Meta. +// If the meta file is not found in storage or decoding fails, the empty Meta +// is returned along with the error. func (b *BloomClient) GetMeta(ctx context.Context, ref MetaRef) (Meta, error) { - meta := Meta{ - MetaRef: ref, - } + meta := Meta{MetaRef: ref} key := b.KeyResolver.Meta(ref).Addr() reader, _, err := b.client.GetObject(ctx, key) if err != nil { - return Meta{}, fmt.Errorf("failed to get meta file%s: %w", key, err) + return meta, err } defer reader.Close() err = json.NewDecoder(reader).Decode(&meta) if err != nil { - return Meta{}, fmt.Errorf("failed to decode meta file %s: %w", key, err) + return meta, errors.Wrap(err, "failed to decode JSON") } return meta, nil } diff --git a/pkg/storage/stores/shipper/bloomshipper/client_test.go b/pkg/storage/stores/shipper/bloomshipper/client_test.go index cd77339c0932c..ec5e7015e00b4 100644 --- a/pkg/storage/stores/shipper/bloomshipper/client_test.go +++ b/pkg/storage/stores/shipper/bloomshipper/client_test.go @@ -107,11 +107,20 @@ func TestBloomClient_GetMetas(t *testing.T) { require.Equal(t, metas, []Meta{m1, m2}) }) - t.Run("does not exist", func(t *testing.T) { - metas, err := c.GetMetas(ctx, []MetaRef{{}}) - require.Error(t, err) - require.True(t, c.client.IsObjectNotFoundErr(err)) - require.Equal(t, metas, []Meta{{}}) + t.Run("does not exist - yields empty meta", func(t *testing.T) { + ref := MetaRef{ + Ref: Ref{ + TenantID: "tenant", + TableName: "table", + Bounds: v1.FingerprintBounds{}, + StartTimestamp: 1000, + EndTimestamp: 2000, + Checksum: 1234, + }, + } + metas, err := c.GetMetas(ctx, []MetaRef{ref}) + require.NoError(t, err) + require.Equal(t, metas, []Meta{{MetaRef: ref}}) }) }
fix
Handle not found metas gracefully (#12853)
9fdb810a617e18a4dc7440d698b79eed9ec05574
2024-03-05 22:41:48
Bayan Taani
fix(operator): Fix encoding of blocked query pattern in configuration (#12097)
false
diff --git a/operator/CHANGELOG.md b/operator/CHANGELOG.md index 14f7d7e1812ea..e3f68a95ccfdf 100644 --- a/operator/CHANGELOG.md +++ b/operator/CHANGELOG.md @@ -1,5 +1,6 @@ ## Main +- [12097](https://github.com/grafana/loki/pull/12097) **btaani**: Fix encoding of blocked query pattern in configuration - [12106](https://github.com/grafana/loki/pull/12106) **xperimental**: Allow setting explicit CredentialMode in LokiStack storage spec - [11968](https://github.com/grafana/loki/pull/11968) **xperimental**: Extend status to show difference between running and ready - [12007](https://github.com/grafana/loki/pull/12007) **xperimental**: Extend Azure secret validation diff --git a/operator/internal/manifests/internal/config/build.go b/operator/internal/manifests/internal/config/build.go index f599b791a7949..277db5b95ce9a 100644 --- a/operator/internal/manifests/internal/config/build.go +++ b/operator/internal/manifests/internal/config/build.go @@ -4,8 +4,6 @@ import ( "bytes" "embed" "io" - "reflect" - "strings" "text/template" "github.com/ViaQ/logerr/v2/kverrors" @@ -29,9 +27,7 @@ var ( lokiConfigYAMLTmpl = template.Must(template.ParseFS(lokiConfigYAMLTmplFile, "loki-config.yaml")) - lokiRuntimeConfigYAMLTmpl = template.Must(template.New("loki-runtime-config.yaml").Funcs(template.FuncMap{ - "yamlBlock": yamlBlock, - }).ParseFS(lokiRuntimeConfigYAMLTmplFile, "loki-runtime-config.yaml")) + lokiRuntimeConfigYAMLTmpl = template.Must(template.New("loki-runtime-config.yaml").ParseFS(lokiRuntimeConfigYAMLTmplFile, "loki-runtime-config.yaml")) ) // Build builds a loki stack configuration files @@ -58,9 +54,3 @@ func Build(opts Options) ([]byte, []byte, error) { } return cfg, rcfg, nil } - -func yamlBlock(indent string, in reflect.Value) string { - inStr := in.String() - lines := strings.Split(strings.TrimRight(inStr, "\n"), "\n") - return strings.Join(lines, "\n"+indent) -} diff --git a/operator/internal/manifests/internal/config/build_test.go b/operator/internal/manifests/internal/config/build_test.go index 602672c813bf1..1b3683f8f2e0d 100644 --- a/operator/internal/manifests/internal/config/build_test.go +++ b/operator/internal/manifests/internal/config/build_test.go @@ -443,14 +443,16 @@ overrides: max_global_streams_per_user: 1 max_chunks_per_query: 1000000 blocked_queries: - - hash: 12345 + - pattern: "" + hash: 12345 types: metric,limited - - pattern: | - .*prod.* + - pattern: .*prod.* regex: true - - types: metric - - pattern: | - sum(rate({env="prod"}[1m])) + - pattern: "" + types: metric + - pattern: sum(rate({env="prod"}[1m])) + - pattern: '{kubernetes_namespace_name="my-app"}' + - pattern: "" ` opts := Options{ Stack: lokiv1.LokiStackSpec{ @@ -505,6 +507,12 @@ overrides: { Pattern: `sum(rate({env="prod"}[1m]))`, }, + { + Pattern: `{kubernetes_namespace_name="my-app"}`, + }, + { + Pattern: "", + }, }, }, }, @@ -538,6 +546,12 @@ overrides: { Pattern: `sum(rate({env="prod"}[1m]))`, }, + { + Pattern: `{kubernetes_namespace_name="my-app"}`, + }, + { + Pattern: "", + }, }, }, }, diff --git a/operator/internal/manifests/internal/config/loki-runtime-config.yaml b/operator/internal/manifests/internal/config/loki-runtime-config.yaml index 421426cb3911f..935c53f5692dc 100644 --- a/operator/internal/manifests/internal/config/loki-runtime-config.yaml +++ b/operator/internal/manifests/internal/config/loki-runtime-config.yaml @@ -57,10 +57,7 @@ overrides: {{- with $l.Blocked }} blocked_queries: {{- range $blockedQuery := . }} - - {{ with $blockedQuery.Pattern -}} - pattern: | - {{ . | yamlBlock " " }} - {{ end -}} + - pattern: {{ .Pattern | printf "%q" }} {{- with $blockedQuery.Regex }} regex: {{ . }} {{- end }}
fix
Fix encoding of blocked query pattern in configuration (#12097)
03a05876975d5367f9b10cf10e9506b09f01e70b
2024-12-10 02:16:44
Trevor Whitney
ci: fix nix build (#15308)
false
diff --git a/.github/workflows/nix-ci.yaml b/.github/workflows/nix-ci.yaml index ba08c719ee3dc..c76e45a199495 100644 --- a/.github/workflows/nix-ci.yaml +++ b/.github/workflows/nix-ci.yaml @@ -1,6 +1,9 @@ --- name: "Lint And Build Nix Flake" on: + push: + branches: + - main pull_request: paths: - "flake.nix" diff --git a/CODEOWNERS b/CODEOWNERS index a118c5a40c0b1..1d122e1f580c5 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -12,5 +12,9 @@ # The observability logs team is listed as co-codeowner for grammar file. This is to receive notifications about updates, so these can be implemented in https://github.com/grafana/lezer-logql /pkg/logql/syntax/expr.y @grafana/observability-logs @grafana/loki-team +# Nix +/nix/ @trevorwhitney +flake.nix @trevorwhitney + # No owners - allows sub-maintainers to merge changes. CHANGELOG.md diff --git a/flake.nix b/flake.nix index c9e52eb589af3..32642f11d110d 100644 --- a/flake.nix +++ b/flake.nix @@ -6,41 +6,21 @@ flake-utils.url = "github:numtide/flake-utils"; }; - # Nixpkgs / NixOS version to use. - outputs = { self, nixpkgs, flake-utils }: - let - nix = import ./nix { inherit self; }; - in - { - overlays = { - default = nix.overlay; - }; - } // flake-utils.lib.eachDefaultSystem (system: let - pkgs = import nixpkgs { - inherit system; - overlays = [ - nix.overlay - ]; - config = { allowUnfree = true; }; - }; + pkgs = import nixpkgs + { + inherit system; + config = { allowUnfree = true; }; + }; in - { - # The default package for 'nix build'. This makes sense if the - # flake provides only one package or there is a clear "main" - # package. + rec { defaultPackage = pkgs.loki; - packages = with pkgs; { - inherit - logcli - loki - loki-canary - loki-helm-test - loki-helm-test-docker - promtail; + packages = import ./nix { + inherit self pkgs; + inherit (pkgs) lib; }; apps = { @@ -56,18 +36,31 @@ test = { type = "app"; - program = with pkgs; "${ - (writeShellScriptBin "test.sh" '' - ${loki.overrideAttrs(old: { - buildInputs = - let - inherit (old) buildInputs; - in - if pkgs.stdenv.hostPlatform.isLinux then - buildInputs ++ (with pkgs; [ systemd ]) - else buildInputs; - doCheck = true; - })}/bin/loki --version + program = + let + loki = packages.loki.overrideAttrs (old: { + buildInputs = with pkgs; lib.optionals stdenv.hostPlatform.isLinux [ systemd.dev ]; + doCheck = true; + checkFlags = [ + "-covermode=atomic" + "-coverprofile=coverage.txt" + "-p=4" + ]; + subPackages = [ + "./..." # for tests + "cmd/loki" + "cmd/logcli" + "cmd/loki-canary" + "clients/cmd/promtail" + ]; + }); + in + "${ + (pkgs.writeShellScriptBin "test.sh" '' + ${loki}/bin/loki --version + ${loki}/bin/logcli --version + ${loki}/bin/loki-canary --version + ${loki}/bin/promtail --version '') }/bin/test.sh"; }; @@ -80,10 +73,6 @@ inherit (pkgs) buildGoModule fetchFromGitHub; }) - (pkgs.callPackage ./nix/packages/faillint.nix { - inherit (pkgs) lib buildGoModule fetchFromGitHub; - }) - chart-testing gcc go @@ -94,7 +83,7 @@ nixpkgs-fmt statix yamllint - ]; + ] // packages; }; }); } diff --git a/nix/default.nix b/nix/default.nix index d2c45ae2af383..1b00605962cb8 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -1,92 +1,91 @@ -{ self }: +{ self, pkgs, lib }: +let + # self.rev is only set on a clean git tree + gitRevision = if (self ? rev) then self.rev else "dirty"; + shortGitRevsion = with lib; + if (self ? rev) then + (strings.concatStrings + (lists.take 8 (strings.stringToCharacters gitRevision))) + else + "dirty"; + + # the image tag script is hard coded to take only 7 characters + imageTagVersion = with lib; + if (self ? rev) then + (strings.concatStrings + (lists.take 8 (strings.stringToCharacters gitRevision))) + else + "dirty"; + + imageTag = + if (self ? rev) then + "${imageTagVersion}" + else + "${imageTagVersion}-WIP"; + + meta = with lib; { + homepage = "https://grafana.com/oss/loki/"; + changelog = "https://github.com/grafana/loki/commit/${shortGitRevsion}"; + maintainers = with maintainers; [ trevorwhitney ]; + + }; + + loki-helm-test = pkgs.callPackage ../production/helm/loki/src/helm-test { + inherit pkgs; + inherit (pkgs) lib buildGoModule dockerTools; + rev = gitRevision; + }; +in { - overlay = final: prev: - let - # self.rev is only set on a clean git tree - gitRevision = if (self ? rev) then self.rev else "dirty"; - shortGitRevsion = with prev.lib; - if (self ? rev) then - (strings.concatStrings - (lists.take 8 (strings.stringToCharacters gitRevision))) - else - "dirty"; - - # the image tag script is hard coded to take only 7 characters - imageTagVersion = with prev.lib; - if (self ? rev) then - (strings.concatStrings - (lists.take 8 (strings.stringToCharacters gitRevision))) - else - "dirty"; - - imageTag = - if (self ? rev) then - "${imageTagVersion}" - else - "${imageTagVersion}-WIP"; - - loki-helm-test = prev.callPackage ../production/helm/loki/src/helm-test { - inherit (prev) pkgs lib buildGoModule dockerTools; - rev = gitRevision; - }; - in - { - inherit (loki-helm-test) loki-helm-test loki-helm-test-docker; - } // rec { - loki = prev.callPackage ./packages/loki.nix { - inherit imageTag; - version = shortGitRevsion; - pkgs = prev; - }; - - logcli = loki.overrideAttrs (oldAttrs: { - pname = "logcli"; - - buildPhase = '' - export GOCACHE=$TMPDIR/go-cache - make clean logcli - ''; - - installPhase = '' - mkdir -p $out/bin - install -m755 cmd/logcli/logcli $out/bin/logcli - ''; - }); - - loki-canary = loki.overrideAttrs (oldAttrs: { - pname = "loki-canary"; - - buildPhase = '' - export GOCACHE=$TMPDIR/go-cache - make clean loki-canary - ''; - - installPhase = '' - mkdir -p $out/bin - install -m755 cmd/loki-canary/loki-canary $out/bin/loki-canary - ''; - }); - - promtail = loki.overrideAttrs (oldAttrs: { - pname = "promtail"; - - buildInputs = - let - inherit (oldAttrs) buildInputs; - in - if prev.stdenv.hostPlatform.isLinux then - buildInputs ++ (with prev; [ systemd ]) - else buildInputs; - - buildPhase = '' - export GOCACHE=$TMPDIR/go-cache - make clean promtail - ''; - - installPhase = '' - mkdir -p $out/bin - install -m755 clients/cmd/promtail/promtail $out/bin/promtail - ''; - }); - }; + inherit (loki-helm-test) loki-helm-test loki-helm-test-docker; +} // rec { + loki = pkgs.callPackage ./packages/loki.nix { + inherit imageTag pkgs; + version = shortGitRevsion; + }; + + logcli = loki.overrideAttrs (oldAttrs: { + pname = "logcli"; + + subPackages = [ "cmd/logcli" ]; + + meta = with lib; { + description = "LogCLI is a command line tool for interacting with Loki."; + mainProgram = "logcli"; + license = with licenses; [ agpl3Only ]; + } // meta; + }); + + loki-canary = loki.overrideAttrs (oldAttrs: { + pname = "loki-canary"; + + subPackages = [ "cmd/loki-canary" ]; + + meta = with lib; { + description = "Loki Canary is a canary for the Loki project."; + mainProgram = "loki-canary"; + license = with licenses; [ agpl3Only ]; + } // meta; + }); + + promtail = loki.overrideAttrs (oldAttrs: { + pname = "promtail"; + + buildInputs = with pkgs; lib.optionals stdenv.hostPlatform.isLinux [ systemd.dev ]; + + tags = [ "promtail_journal_enabled" ]; + + subPackages = [ "clients/cmd/promtail" ]; + + preFixup = lib.optionalString pkgs.stdenv.hostPlatform.isLinux '' + wrapProgram $out/bin/promtail \ + --prefix LD_LIBRARY_PATH : "${lib.getLib pkgs.systemd}/lib" + ''; + + meta = with lib; { + description = "Client for sending logs to Loki"; + mainProgram = "promtail"; + license = with licenses; [ asl20 ]; + } // meta; + }); } diff --git a/nix/packages/faillint.nix b/nix/packages/faillint.nix deleted file mode 100644 index 0931fc08fccfa..0000000000000 --- a/nix/packages/faillint.nix +++ /dev/null @@ -1,16 +0,0 @@ -{ lib, buildGoModule, fetchFromGitHub }: - -buildGoModule rec { - pname = "faillint"; - version = "v1.14.0"; - - src = fetchFromGitHub { - owner = "fatih"; - repo = "faillint"; - rev = "${version}"; - sha256 = "NV+wbu547mtTa6dTGv7poBwWXOmu5YjqbauzolCg5qs="; - }; - - vendorHash = "sha256-vWt4HneDA7YwXYnn8TbfWCKzSv7RcgXxn/HAh6a+htQ="; - doCheck = false; -} diff --git a/nix/packages/loki.nix b/nix/packages/loki.nix index 7da43f05d3ede..28f215155b36a 100644 --- a/nix/packages/loki.nix +++ b/nix/packages/loki.nix @@ -1,78 +1,38 @@ -{ pkgs, version, imageTag }: -let - lambda-promtail-gomod = pkgs.buildGoModule { - inherit version; - pname = "lambda-promtail"; - - src = ./../../tools/lambda-promtail; - vendorHash = "sha256-yQIRFUhod91HiPS5IKm7eNeIXJzBWVcvIXf9qMncTKw="; - - doCheck = false; - - installPhase = '' - runHook preInstall - cp -r --reflink=auto vendor $out - runHook postInstall - ''; - }; -in -pkgs.stdenv.mkDerivation { +{ pkgs, version, imageTag, lib }: +pkgs.buildGo123Module { inherit version; pname = "loki"; src = ./../..; - - buildInputs = with pkgs; [ - bash - gcc - git - go_1_23 - golangci-lint - gotools - nettools - yamllint - - (import ./faillint.nix { - inherit (pkgs) lib buildGoModule fetchFromGitHub; - }) - ]; - - configurePhase = with pkgs; '' - patchShebangs tools - - substituteInPlace Makefile \ - --replace "SHELL = /usr/bin/env bash -o pipefail" "SHELL = ${bash}/bin/bash -o pipefail" \ - --replace "IMAGE_TAG ?= \$(shell ./tools/image-tag)" "IMAGE_TAG ?= ${imageTag}" \ - --replace "GIT_REVISION := \$(shell git rev-parse --short HEAD)" "GIT_REVISION := ${version}" \ - --replace "GIT_BRANCH := \$(shell git rev-parse --abbrev-ref HEAD)" "GIT_BRANCH := nix" - - substituteInPlace clients/cmd/fluentd/Makefile \ - --replace "SHELL = /usr/bin/env bash -o pipefail" "SHELL = ${bash}/bin/bash -o pipefail" - ''; - - buildPhase = '' - export GOCACHE=$TMPDIR/go-cache - export GOMODCACHE=$TMPDIR/gomodcache - export GOPROXY=off - - cp -r ${lambda-promtail-gomod} tools/lambda-promtail/vendor - make clean loki - ''; + vendorHash = null; + + ldflags = + let + prefix = "github.com/grafana/loki/v3/pkg/util/build"; + in + [ + "-s" + "-w" + "-X ${prefix}.Branch=nix" + "-X ${prefix}.Version=${imageTag}" + "-X ${prefix}.Revision=${version}" + "-X ${prefix}.BuildUser=nix@nixpkgs" + "-X ${prefix}.BuildDate=unknown" + ]; + + subPackages = [ "cmd/loki" ]; + + nativeBuildInputs = with pkgs; [ makeWrapper ]; doCheck = false; - checkPhase = '' - export GOCACHE=$TMPDIR/go-cache - export GOMODCACHE=$TMPDIR/gomodcache - export GOLANGCI_LINT_CACHE=$TMPDIR/go-cache - export GOPROXY=off - export BUILD_IN_CONTAINER=false - - make lint test - ''; - installPhase = '' - mkdir -p $out/bin - install -m755 cmd/loki/loki $out/bin/loki - ''; + meta = with lib; { + description = "Like Prometheus, but for logs"; + mainProgram = "loki"; + license = with licenses; [ agpl3Only ]; + homepage = "https://grafana.com/oss/loki/"; + changelog = "https://github.com/grafana/loki/commit/${version}"; + maintainers = with maintainers; [ trevorwhitney ]; + }; } diff --git a/pkg/loki/loki_test.go b/pkg/loki/loki_test.go index b29d2aad22065..3d5f774247754 100644 --- a/pkg/loki/loki_test.go +++ b/pkg/loki/loki_test.go @@ -188,6 +188,7 @@ server: common: compactor_address: http://localhost:%d path_prefix: /tmp/loki + instance_addr: localhost ring: kvstore: store: inmemory diff --git a/pkg/loki/modules_test.go b/pkg/loki/modules_test.go index 64241443d3439..f3b9fa9a98d51 100644 --- a/pkg/loki/modules_test.go +++ b/pkg/loki/modules_test.go @@ -406,6 +406,7 @@ func minimalWorkingConfig(t *testing.T, dir, target string, cfgTransformers ...f } cfg.Common.InstanceAddr = localhost + cfg.MemberlistKV.AdvertiseAddr = localhost cfg.Ingester.LifecyclerConfig.Addr = localhost cfg.Distributor.DistributorRing.InstanceAddr = localhost cfg.IndexGateway.Mode = indexgateway.SimpleMode
ci
fix nix build (#15308)
b8f26c55a75a90764018f9bedccd887efabe0bc5
2023-01-10 21:49:20
Erwin de Haan
helm: Fix loki helm chart podLog relabelings template nindent (#8080)
false
diff --git a/production/helm/loki/templates/monitoring/pod-logs.yaml b/production/helm/loki/templates/monitoring/pod-logs.yaml index 955f4e8ecbedf..3e597ed97af20 100644 --- a/production/helm/loki/templates/monitoring/pod-logs.yaml +++ b/production/helm/loki/templates/monitoring/pod-logs.yaml @@ -36,7 +36,7 @@ spec: - replacement: "{{ include "loki.fullname" $ }}" targetLabel: cluster {{- with .relabelings }} - {{- toYaml . | nindent 8 }} + {{- toYaml . | nindent 4 }} {{- end }} namespaceSelector: matchNames:
helm
Fix loki helm chart podLog relabelings template nindent (#8080)
43f5841d47496f35892a3c860b9bdffdae24969c
2020-09-01 20:20:45
Reinhard Nägele
promtail: Fix docker-compose.yaml (#2575)
false
diff --git a/production/docker-compose.yaml b/production/docker-compose.yaml index b045739df89fb..1773d94aacba5 100644 --- a/production/docker-compose.yaml +++ b/production/docker-compose.yaml @@ -16,7 +16,7 @@ services: image: grafana/promtail:1.6.0 volumes: - /var/log:/var/log - command: -config.file=/etc/promtail/docker-config.yaml + command: -config.file=/etc/promtail/config.yml networks: - loki
promtail
Fix docker-compose.yaml (#2575)
6d011bedbce159ee63611bf860f94e5ed030f501
2023-12-01 12:51:52
Ashwanth
config: fix index periodic config unmarshal (#11344)
false
diff --git a/pkg/storage/config/schema_config.go b/pkg/storage/config/schema_config.go index f2eaa9f3733db..d4b5902516d20 100644 --- a/pkg/storage/config/schema_config.go +++ b/pkg/storage/config/schema_config.go @@ -491,6 +491,42 @@ func (cfg *IndexPeriodicTableConfig) Validate() error { return ValidatePathPrefix(cfg.PathPrefix) } +// UnmarshalYAML implements the yaml.Unmarshaler interface. +func (cfg *IndexPeriodicTableConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + g := struct { + PathPrefix string `yaml:"path_prefix"` + Prefix string `yaml:"prefix"` + Period model.Duration `yaml:"period"` + Tags Tags `yaml:"tags"` + }{} + if err := unmarshal(&g); err != nil { + return err + } + + cfg.PathPrefix = g.PathPrefix + cfg.Prefix = g.Prefix + cfg.Period = time.Duration(g.Period) + cfg.Tags = g.Tags + + return nil +} + +// MarshalYAML implements the yaml.Marshaler interface. +func (cfg IndexPeriodicTableConfig) MarshalYAML() (interface{}, error) { + g := &struct { + PathPrefix string `yaml:"path_prefix"` + Prefix string `yaml:"prefix"` + Period model.Duration `yaml:"period"` + Tags Tags `yaml:"tags"` + }{ + PathPrefix: cfg.PathPrefix, + Prefix: cfg.Prefix, + Period: model.Duration(cfg.Period), + Tags: cfg.Tags, + } + + return g, nil +} func ValidatePathPrefix(prefix string) error { if prefix == "" { return errors.New("prefix must be set") diff --git a/pkg/storage/config/schema_config_test.go b/pkg/storage/config/schema_config_test.go index a547419987786..06fd191b7092a 100644 --- a/pkg/storage/config/schema_config_test.go +++ b/pkg/storage/config/schema_config_test.go @@ -503,6 +503,37 @@ func MustParseDayTime(s string) DayTime { return DayTime{model.TimeFromUnix(t.Unix())} } +func TestIndexPeriodicTableConfigCustomUnmarshalling(t *testing.T) { + yamlFile := `path_prefix: loki_index/ +prefix: cortex_ +period: 1w +tags: + foo: bar +` + + cfg := IndexPeriodicTableConfig{} + err := yaml.Unmarshal([]byte(yamlFile), &cfg) + require.NoError(t, err) + + expectedCfg := IndexPeriodicTableConfig{ + PathPrefix: "loki_index/", + PeriodicTableConfig: PeriodicTableConfig{ + Prefix: "cortex_", + Period: 7 * 24 * time.Hour, + Tags: map[string]string{ + "foo": "bar", + }, + }, + } + + require.Equal(t, expectedCfg, cfg) + + yamlGenerated, err := yaml.Marshal(&cfg) + require.NoError(t, err) + + require.Equal(t, yamlFile, string(yamlGenerated)) +} + func TestPeriodicTableConfigCustomUnmarshalling(t *testing.T) { yamlFile := `prefix: cortex_ period: 1w
config
fix index periodic config unmarshal (#11344)
2e5622bd3dada0529779bfa879cbc8eacef41b3a
2023-01-11 05:20:17
Cameron Attard
helm: add support for memcached client addresses (#7995)
false
diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index e371d36e820a3..d6083d6f6702c 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -103,14 +103,19 @@ loki: {{- end }} {{- with .Values.loki.memcached.chunk_cache }} - {{- if and .enabled .host }} + {{- if and .enabled (or .host .addresses) }} chunk_store_config: chunk_cache_config: memcached: batch_size: {{ .batch_size }} parallelism: {{ .parallelism }} memcached_client: + {{- if .host }} host: {{ .host }} + {{- end }} + {{- if .addresses }} + addresses: {{ .addresses }} + {{- end }} service: {{ .service }} {{- end }} {{- end }} @@ -135,13 +140,18 @@ loki: {{- with .Values.loki.memcached.results_cache }} query_range: align_queries_with_step: true - {{- if and .enabled .host }} + {{- if and .enabled (or .host .addresses) }} cache_results: {{ .enabled }} results_cache: cache: default_validity: {{ .default_validity }} memcached_client: + {{- if .host }} host: {{ .host }} + {{- end }} + {{- if .addresses }} + addresses: {{ .addresses }} + {{- end }} service: {{ .service }} timeout: {{ .timeout }} {{- end }}
helm
add support for memcached client addresses (#7995)
5652a7baf43be3a5c70983c1debd40fa4abda60d
2023-09-05 13:26:19
Christian Haudum
chore(storage): Simplify store interfaces and abstractions (pt 1) (#10435)
false
diff --git a/pkg/loki/loki.go b/pkg/loki/loki.go index d5f64c12f7d09..7c1dec7476b95 100644 --- a/pkg/loki/loki.go +++ b/pkg/loki/loki.go @@ -295,7 +295,7 @@ type Loki struct { cacheGenerationLoader queryrangebase.CacheGenNumberLoader querierAPI *querier.QuerierAPI ingesterQuerier *querier.IngesterQuerier - Store storage.Store + Store *storage.LokiStore tableManager *index.TableManager frontend Frontend ruler *base_ruler.Ruler diff --git a/pkg/querier/querier.go b/pkg/querier/querier.go index 59804aade41cc..0688b140261ee 100644 --- a/pkg/querier/querier.go +++ b/pkg/querier/querier.go @@ -622,7 +622,7 @@ func (q *SingleTenantQuerier) seriesForMatchers( // seriesForMatcher fetches series from the store for a given matcher func (q *SingleTenantQuerier) seriesForMatcher(ctx context.Context, from, through time.Time, matcher string, shards []string) ([]logproto.SeriesIdentifier, error) { - ids, err := q.store.Series(ctx, logql.SelectLogParams{ + ids, err := q.store.SelectSeries(ctx, logql.SelectLogParams{ QueryRequest: &logproto.QueryRequest{ Selector: matcher, Limit: 1, diff --git a/pkg/querier/querier_mock_test.go b/pkg/querier/querier_mock_test.go index f102831e9922a..c623e3391d0ce 100644 --- a/pkg/querier/querier_mock_test.go +++ b/pkg/querier/querier_mock_test.go @@ -350,7 +350,7 @@ func (s *storeMock) GetSchemaConfigs() []config.PeriodConfig { panic("don't call me please") } -func (s *storeMock) Series(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) { +func (s *storeMock) SelectSeries(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) { args := s.Called(ctx, req) res := args.Get(0) if res == nil { diff --git a/pkg/querier/querier_test.go b/pkg/querier/querier_test.go index 7610854e375c9..e64e9f559d077 100644 --- a/pkg/querier/querier_test.go +++ b/pkg/querier/querier_test.go @@ -243,7 +243,7 @@ func TestQuerier_SeriesAPI(t *testing.T) { func(store *storeMock, querier *queryClientMock, ingester *querierClientMock, limits validation.Limits, req *logproto.SeriesRequest) { ingester.On("Series", mock.Anything, req, mock.Anything).Return(nil, errors.New("tst-err")) - store.On("Series", mock.Anything, mock.Anything).Return(nil, nil) + store.On("SelectSeries", mock.Anything, mock.Anything).Return(nil, nil) }, func(t *testing.T, q *SingleTenantQuerier, req *logproto.SeriesRequest) { ctx := user.InjectOrgID(context.Background(), "test") @@ -259,7 +259,7 @@ func TestQuerier_SeriesAPI(t *testing.T) { {"a": "1"}, }), nil) - store.On("Series", mock.Anything, mock.Anything).Return(nil, context.DeadlineExceeded) + store.On("SelectSeries", mock.Anything, mock.Anything).Return(nil, context.DeadlineExceeded) }, func(t *testing.T, q *SingleTenantQuerier, req *logproto.SeriesRequest) { ctx := user.InjectOrgID(context.Background(), "test") @@ -272,7 +272,7 @@ func TestQuerier_SeriesAPI(t *testing.T) { mkReq([]string{`{a="1"}`}), func(store *storeMock, querier *queryClientMock, ingester *querierClientMock, limits validation.Limits, req *logproto.SeriesRequest) { ingester.On("Series", mock.Anything, req, mock.Anything).Return(mockSeriesResponse(nil), nil) - store.On("Series", mock.Anything, mock.Anything).Return(nil, nil) + store.On("SelectSeries", mock.Anything, mock.Anything).Return(nil, nil) }, func(t *testing.T, q *SingleTenantQuerier, req *logproto.SeriesRequest) { ctx := user.InjectOrgID(context.Background(), "test") @@ -290,7 +290,7 @@ func TestQuerier_SeriesAPI(t *testing.T) { {"a": "1", "b": "3"}, }), nil) - store.On("Series", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ + store.On("SelectSeries", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ {Labels: map[string]string{"a": "1", "b": "4"}}, {Labels: map[string]string{"a": "1", "b": "5"}}, }, nil) @@ -315,7 +315,7 @@ func TestQuerier_SeriesAPI(t *testing.T) { {"a": "1", "b": "2"}, }), nil) - store.On("Series", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ + store.On("SelectSeries", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ {Labels: map[string]string{"a": "1", "b": "2"}}, {Labels: map[string]string{"a": "1", "b": "3"}}, }, nil) @@ -825,7 +825,7 @@ func TestQuerier_RequestingIngesters(t *testing.T) { }, "Series": { ingesterMethod: "Series", - storeMethod: "Series", + storeMethod: "SelectSeries", }, } @@ -1100,7 +1100,7 @@ func setupIngesterQuerierMocks(conf Config, limits *validation.Overrides) (*quer store.On("SelectSamples", mock.Anything, mock.Anything).Return(mockSampleIterator(querySampleClient), nil) store.On("LabelValuesForMetricName", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]string{"1", "2", "3"}, nil) store.On("LabelNamesForMetricName", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]string{"foo"}, nil) - store.On("Series", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ + store.On("SelectSeries", mock.Anything, mock.Anything).Return([]logproto.SeriesIdentifier{ {Labels: map[string]string{"foo": "1"}}, }, nil) diff --git a/pkg/storage/batch_test.go b/pkg/storage/batch_test.go index d2ae09697669c..0e39edd86b625 100644 --- a/pkg/storage/batch_test.go +++ b/pkg/storage/batch_test.go @@ -1760,7 +1760,7 @@ func Benchmark_store_OverlappingChunks(b *testing.B) { require.NoError(b, err) b.ReportAllocs() - st := &store{ + st := &LokiStore{ chunkMetrics: NilMetrics, cfg: Config{ MaxChunkBatchSize: 50, diff --git a/pkg/storage/store.go b/pkg/storage/store.go index 6b7f749079e40..9539019c5fada 100644 --- a/pkg/storage/store.go +++ b/pkg/storage/store.go @@ -46,16 +46,20 @@ var ( errWritingChunkUnsupported = errors.New("writing chunks is not supported while running store in read-only mode") ) +type SelectStore interface { + SelectSamples(ctx context.Context, req logql.SelectSampleParams) (iter.SampleIterator, error) + SelectLogs(ctx context.Context, req logql.SelectLogParams) (iter.EntryIterator, error) + SelectSeries(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) +} + type Store interface { stores.Store - stores.ChunkReader - index.Filterable + SelectStore GetSchemaConfigs() []config.PeriodConfig } -type store struct { +type LokiStore struct { stores.Store - composite *stores.CompositeStore cfg Config storeCfg config.ChunkStoreConfig @@ -81,7 +85,7 @@ type store struct { // NewStore creates a new Loki Store using configuration supplied. func NewStore(cfg Config, storeCfg config.ChunkStoreConfig, schemaCfg config.SchemaConfig, limits StoreLimits, clientMetrics ClientMetrics, registerer prometheus.Registerer, logger log.Logger, -) (Store, error) { +) (*LokiStore, error) { if len(schemaCfg.Configs) != 0 { if index := config.ActivePeriodConfig(schemaCfg.Configs); index != -1 && index < len(schemaCfg.Configs) { indexTypeStats.Set(schemaCfg.Configs[index].IndexType) @@ -134,9 +138,8 @@ func NewStore(cfg Config, storeCfg config.ChunkStoreConfig, schemaCfg config.Sch } stores := stores.NewCompositeStore(limits) - s := &store{ + s := &LokiStore{ Store: stores, - composite: stores, cfg: cfg, storeCfg: storeCfg, schemaCfg: schemaCfg, @@ -162,7 +165,7 @@ func NewStore(cfg Config, storeCfg config.ChunkStoreConfig, schemaCfg config.Sch return s, nil } -func (s *store) init() error { +func (s *LokiStore) init() error { for i, p := range s.schemaCfg.Configs { p := p chunkClient, err := s.chunkClientForPeriod(p) @@ -183,7 +186,8 @@ func (s *store) init() error { return err } - s.composite.AddStore(p.From.Time, f, idx, w, stop) + // s.Store is always assigned the CompositeStore implementation of the Store interface + s.Store.(*stores.CompositeStore).AddStore(p.From.Time, f, idx, w, stop) } if s.cfg.EnableAsyncStore { @@ -193,7 +197,7 @@ func (s *store) init() error { return nil } -func (s *store) chunkClientForPeriod(p config.PeriodConfig) (client.Client, error) { +func (s *LokiStore) chunkClientForPeriod(p config.PeriodConfig) (client.Client, error) { objectStoreType := p.ObjectType if objectStoreType == "" { objectStoreType = p.IndexType @@ -234,7 +238,7 @@ func shouldUseIndexGatewayClient(cfg indexshipper.Config) bool { return true } -func (s *store) storeForPeriod(p config.PeriodConfig, tableRange config.TableRange, chunkClient client.Client, f *fetcher.Fetcher) (stores.ChunkWriter, index.ReaderWriter, func(), error) { +func (s *LokiStore) storeForPeriod(p config.PeriodConfig, tableRange config.TableRange, chunkClient client.Client, f *fetcher.Fetcher) (stores.ChunkWriter, index.ReaderWriter, func(), error) { indexClientReg := prometheus.WrapRegistererWith( prometheus.Labels{ "component": fmt.Sprintf( @@ -380,13 +384,13 @@ func injectShardLabel(shards []string, matchers []*labels.Matcher) ([]*labels.Ma return matchers, nil } -func (s *store) SetChunkFilterer(chunkFilterer chunk.RequestChunkFilterer) { +func (s *LokiStore) SetChunkFilterer(chunkFilterer chunk.RequestChunkFilterer) { s.chunkFilterer = chunkFilterer s.Store.SetChunkFilterer(chunkFilterer) } // lazyChunks is an internal function used to resolve a set of lazy chunks from the store without actually loading them. It's used internally by `LazyQuery` and `GetSeries` -func (s *store) lazyChunks(ctx context.Context, matchers []*labels.Matcher, from, through model.Time) ([]*LazyChunk, error) { +func (s *LokiStore) lazyChunks(ctx context.Context, matchers []*labels.Matcher, from, through model.Time) ([]*LazyChunk, error) { userID, err := tenant.TenantID(ctx) if err != nil { return nil, err @@ -424,7 +428,7 @@ func (s *store) lazyChunks(ctx context.Context, matchers []*labels.Matcher, from return lazyChunks, nil } -func (s *store) Series(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) { +func (s *LokiStore) SelectSeries(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) { userID, err := tenant.TenantID(ctx) if err != nil { return nil, err @@ -467,7 +471,7 @@ func (s *store) Series(ctx context.Context, req logql.SelectLogParams) ([]logpro // SelectLogs returns an iterator that will query the store for more chunks while iterating instead of fetching all chunks upfront // for that request. -func (s *store) SelectLogs(ctx context.Context, req logql.SelectLogParams) (iter.EntryIterator, error) { +func (s *LokiStore) SelectLogs(ctx context.Context, req logql.SelectLogParams) (iter.EntryIterator, error) { matchers, from, through, err := decodeReq(req) if err != nil { return nil, err @@ -505,7 +509,7 @@ func (s *store) SelectLogs(ctx context.Context, req logql.SelectLogParams) (iter return newLogBatchIterator(ctx, s.schemaCfg, s.chunkMetrics, lazyChunks, s.cfg.MaxChunkBatchSize, matchers, pipeline, req.Direction, req.Start, req.End, chunkFilterer) } -func (s *store) SelectSamples(ctx context.Context, req logql.SelectSampleParams) (iter.SampleIterator, error) { +func (s *LokiStore) SelectSamples(ctx context.Context, req logql.SelectSampleParams) (iter.SampleIterator, error) { matchers, from, through, err := decodeReq(req) if err != nil { return nil, err @@ -543,7 +547,7 @@ func (s *store) SelectSamples(ctx context.Context, req logql.SelectSampleParams) return newSampleBatchIterator(ctx, s.schemaCfg, s.chunkMetrics, lazyChunks, s.cfg.MaxChunkBatchSize, matchers, extractor, req.Start, req.End, chunkFilterer) } -func (s *store) GetSchemaConfigs() []config.PeriodConfig { +func (s *LokiStore) GetSchemaConfigs() []config.PeriodConfig { return s.schemaCfg.Configs } diff --git a/pkg/storage/store_test.go b/pkg/storage/store_test.go index 17a47c55d12d7..13efd8ffa538f 100644 --- a/pkg/storage/store_test.go +++ b/pkg/storage/store_test.go @@ -485,7 +485,7 @@ func Test_store_SelectLogs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s := &store{ + s := &LokiStore{ Store: storeFixture, cfg: Config{ MaxChunkBatchSize: 10, @@ -809,7 +809,7 @@ func Test_store_SelectSample(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s := &store{ + s := &LokiStore{ Store: storeFixture, cfg: Config{ MaxChunkBatchSize: 10, @@ -845,7 +845,7 @@ func (f fakeChunkFilterer) ShouldFilter(metric labels.Labels) bool { } func Test_ChunkFilterer(t *testing.T) { - s := &store{ + s := &LokiStore{ Store: storeFixture, cfg: Config{ MaxChunkBatchSize: 10, @@ -875,7 +875,7 @@ func Test_ChunkFilterer(t *testing.T) { v := mustParseLabels(it.Labels())["foo"] require.NotEqual(t, "bazz", v) } - ids, err := s.Series(ctx, logql.SelectLogParams{QueryRequest: newQuery("{foo=~\"ba.*\"}", from, from.Add(1*time.Hour), nil, nil)}) + ids, err := s.SelectSeries(ctx, logql.SelectLogParams{QueryRequest: newQuery("{foo=~\"ba.*\"}", from, from.Add(1*time.Hour), nil, nil)}) require.NoError(t, err) for _, id := range ids { v := id.Labels["foo"] @@ -935,7 +935,7 @@ func Test_store_GetSeries(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s := &store{ + s := &LokiStore{ Store: newMockChunkStore(chunkfmt, headfmt, streamsFixture), cfg: Config{ MaxChunkBatchSize: tt.batchSize, @@ -943,7 +943,7 @@ func Test_store_GetSeries(t *testing.T) { chunkMetrics: NilMetrics, } ctx = user.InjectOrgID(context.Background(), "test-user") - out, err := s.Series(ctx, logql.SelectLogParams{QueryRequest: tt.req}) + out, err := s.SelectSeries(ctx, logql.SelectLogParams{QueryRequest: tt.req}) if err != nil { t.Errorf("store.GetSeries() error = %v", err) return @@ -1365,7 +1365,7 @@ func Test_OverlappingChunks(t *testing.T) { }, }), } - s := &store{ + s := &LokiStore{ Store: &mockChunkStore{chunks: chunks, client: &mockChunkStoreClient{chunks: chunks}}, cfg: Config{ MaxChunkBatchSize: 10, @@ -1407,7 +1407,7 @@ func Test_GetSeries(t *testing.T) { require.NoError(t, err) var ( - store = &store{ + store = &LokiStore{ Store: newMockChunkStore(chunkfmt, headfmt, []*logproto.Stream{ { Labels: `{foo="bar",buzz="boo"}`, @@ -1492,7 +1492,7 @@ func Test_GetSeries(t *testing.T) { } { tt := tt t.Run(tt.name, func(t *testing.T) { - series, err := store.Series(ctx, tt.req) + series, err := store.SelectSeries(ctx, tt.req) require.NoError(t, err) require.Equal(t, tt.expectedSeries, series) }) diff --git a/pkg/storage/stores/composite_store.go b/pkg/storage/stores/composite_store.go index 419c6a719c707..81fb4eb58a4aa 100644 --- a/pkg/storage/stores/composite_store.go +++ b/pkg/storage/stores/composite_store.go @@ -9,9 +9,7 @@ import ( "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" - "github.com/grafana/loki/pkg/iter" "github.com/grafana/loki/pkg/logproto" - "github.com/grafana/loki/pkg/logql" "github.com/grafana/loki/pkg/storage/chunk" "github.com/grafana/loki/pkg/storage/chunk/fetcher" "github.com/grafana/loki/pkg/storage/stores/index" @@ -19,12 +17,6 @@ import ( "github.com/grafana/loki/pkg/util" ) -type ChunkReader interface { - SelectSamples(ctx context.Context, req logql.SelectSampleParams) (iter.SampleIterator, error) - SelectLogs(ctx context.Context, req logql.SelectLogParams) (iter.EntryIterator, error) - Series(ctx context.Context, req logql.SelectLogParams) ([]logproto.SeriesIdentifier, error) -} - type ChunkWriter interface { Put(ctx context.Context, chunks []chunk.Chunk) error PutOne(ctx context.Context, from, through model.Time, chunk chunk.Chunk) error @@ -46,21 +38,20 @@ type Store interface { // CompositeStore is a Store which delegates to various stores depending // on when they were activated. type CompositeStore struct { - compositeStore limits StoreLimits -} - -type compositeStore struct { stores []compositeStoreEntry } -// Ensure interface implementation of compositStore -var _ Store = &compositeStore{} +// Ensure interface implementation of CompositeStore +var _ Store = &CompositeStore{} // NewCompositeStore creates a new Store which delegates to different stores depending // on time. func NewCompositeStore(limits StoreLimits) *CompositeStore { - return &CompositeStore{compositeStore{}, limits} + return &CompositeStore{ + stores: make([]compositeStoreEntry, 0), + limits: limits, + } } func (c *CompositeStore) AddStore(start model.Time, fetcher *fetcher.Fetcher, index index.Reader, writer ChunkWriter, stop func()) { @@ -84,7 +75,7 @@ func (c *CompositeStore) Stores() []Store { return stores } -func (c compositeStore) Put(ctx context.Context, chunks []chunk.Chunk) error { +func (c CompositeStore) Put(ctx context.Context, chunks []chunk.Chunk) error { for _, chunk := range chunks { err := c.forStores(ctx, chunk.From, chunk.Through, func(innerCtx context.Context, from, through model.Time, store Store) error { return store.PutOne(innerCtx, from, through, chunk) @@ -96,19 +87,19 @@ func (c compositeStore) Put(ctx context.Context, chunks []chunk.Chunk) error { return nil } -func (c compositeStore) PutOne(ctx context.Context, from, through model.Time, chunk chunk.Chunk) error { +func (c CompositeStore) PutOne(ctx context.Context, from, through model.Time, chunk chunk.Chunk) error { return c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { return store.PutOne(innerCtx, from, through, chunk) }) } -func (c compositeStore) SetChunkFilterer(chunkFilter chunk.RequestChunkFilterer) { +func (c CompositeStore) SetChunkFilterer(chunkFilter chunk.RequestChunkFilterer) { for _, store := range c.stores { store.Store.SetChunkFilterer(chunkFilter) } } -func (c compositeStore) GetSeries(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) ([]labels.Labels, error) { +func (c CompositeStore) GetSeries(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) ([]labels.Labels, error) { var results []labels.Labels found := map[uint64]struct{}{} err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { @@ -131,7 +122,7 @@ func (c compositeStore) GetSeries(ctx context.Context, userID string, from, thro } // LabelValuesForMetricName retrieves all label values for a single label name and metric name. -func (c compositeStore) LabelValuesForMetricName(ctx context.Context, userID string, from, through model.Time, metricName string, labelName string, matchers ...*labels.Matcher) ([]string, error) { +func (c CompositeStore) LabelValuesForMetricName(ctx context.Context, userID string, from, through model.Time, metricName string, labelName string, matchers ...*labels.Matcher) ([]string, error) { var result util.UniqueStrings err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { labelValues, err := store.LabelValuesForMetricName(innerCtx, userID, from, through, metricName, labelName, matchers...) @@ -145,7 +136,7 @@ func (c compositeStore) LabelValuesForMetricName(ctx context.Context, userID str } // LabelNamesForMetricName retrieves all label names for a metric name. -func (c compositeStore) LabelNamesForMetricName(ctx context.Context, userID string, from, through model.Time, metricName string) ([]string, error) { +func (c CompositeStore) LabelNamesForMetricName(ctx context.Context, userID string, from, through model.Time, metricName string) ([]string, error) { var result util.UniqueStrings err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { labelNames, err := store.LabelNamesForMetricName(innerCtx, userID, from, through, metricName) @@ -158,7 +149,7 @@ func (c compositeStore) LabelNamesForMetricName(ctx context.Context, userID stri return result.Strings(), err } -func (c compositeStore) GetChunkRefs(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) ([][]chunk.Chunk, []*fetcher.Fetcher, error) { +func (c CompositeStore) GetChunkRefs(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) ([][]chunk.Chunk, []*fetcher.Fetcher, error) { chunkIDs := [][]chunk.Chunk{} fetchers := []*fetcher.Fetcher{} err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { @@ -179,7 +170,7 @@ func (c compositeStore) GetChunkRefs(ctx context.Context, userID string, from, t return chunkIDs, fetchers, err } -func (c compositeStore) Stats(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) (*stats.Stats, error) { +func (c CompositeStore) Stats(ctx context.Context, userID string, from, through model.Time, matchers ...*labels.Matcher) (*stats.Stats, error) { xs := make([]*stats.Stats, 0, len(c.stores)) err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { x, err := store.Stats(innerCtx, userID, from, through, matchers...) @@ -195,7 +186,7 @@ func (c compositeStore) Stats(ctx context.Context, userID string, from, through return &res, err } -func (c compositeStore) Volume(ctx context.Context, userID string, from, through model.Time, limit int32, targetLabels []string, aggregateBy string, matchers ...*labels.Matcher) (*logproto.VolumeResponse, error) { +func (c CompositeStore) Volume(ctx context.Context, userID string, from, through model.Time, limit int32, targetLabels []string, aggregateBy string, matchers ...*labels.Matcher) (*logproto.VolumeResponse, error) { volumes := make([]*logproto.VolumeResponse, 0, len(c.stores)) err := c.forStores(ctx, from, through, func(innerCtx context.Context, from, through model.Time, store Store) error { volume, err := store.Volume(innerCtx, userID, from, through, limit, targetLabels, aggregateBy, matchers...) @@ -211,7 +202,7 @@ func (c compositeStore) Volume(ctx context.Context, userID string, from, through return res, err } -func (c compositeStore) GetChunkFetcher(tm model.Time) *fetcher.Fetcher { +func (c CompositeStore) GetChunkFetcher(tm model.Time) *fetcher.Fetcher { // find the schema with the lowest start _after_ tm j := sort.Search(len(c.stores), func(j int) bool { return c.stores[j].start > tm @@ -227,13 +218,13 @@ func (c compositeStore) GetChunkFetcher(tm model.Time) *fetcher.Fetcher { return nil } -func (c compositeStore) Stop() { +func (c CompositeStore) Stop() { for _, store := range c.stores { store.Stop() } } -func (c compositeStore) forStores(ctx context.Context, from, through model.Time, callback func(innerCtx context.Context, from, through model.Time, store Store) error) error { +func (c CompositeStore) forStores(ctx context.Context, from, through model.Time, callback func(innerCtx context.Context, from, through model.Time, store Store) error) error { if len(c.stores) == 0 { return nil } diff --git a/pkg/storage/stores/composite_store_test.go b/pkg/storage/stores/composite_store_test.go index f1c6e72d8e0b0..3bb1c09e46b6f 100644 --- a/pkg/storage/stores/composite_store_test.go +++ b/pkg/storage/stores/composite_store_test.go @@ -73,7 +73,7 @@ func TestCompositeStore(t *testing.T) { return nil } } - cs := compositeStore{ + cs := CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, {model.TimeFromUnix(100), mockStore(2)}, @@ -82,16 +82,18 @@ func TestCompositeStore(t *testing.T) { } for i, tc := range []struct { - cs compositeStore + cs CompositeStore from, through int64 want []result }{ // Test we have sensible results when there are no schema's defined - {compositeStore{}, 0, 1, []result{}}, + { + CompositeStore{}, 0, 1, []result{}, + }, // Test we have sensible results when there is a single schema { - compositeStore{ + CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, }, @@ -104,7 +106,7 @@ func TestCompositeStore(t *testing.T) { // Test we have sensible results for negative (ie pre 1970) times { - compositeStore{ + CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, }, @@ -113,7 +115,7 @@ func TestCompositeStore(t *testing.T) { []result{}, }, { - compositeStore{ + CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, }, @@ -126,7 +128,7 @@ func TestCompositeStore(t *testing.T) { // Test we have sensible results when there is two schemas { - compositeStore{ + CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, {model.TimeFromUnix(100), mockStore(2)}, @@ -206,7 +208,7 @@ func (m mockStoreLabel) LabelNamesForMetricName(_ context.Context, _ string, _, func TestCompositeStoreLabels(t *testing.T) { t.Parallel() - cs := compositeStore{ + cs := CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(0), mockStore(1)}, {model.TimeFromUnix(20), mockStoreLabel{mockStore(1), []string{"b", "c", "e"}}}, @@ -256,7 +258,7 @@ func (m mockStoreGetChunkFetcher) GetChunkFetcher(_ model.Time) *fetcher.Fetcher } func TestCompositeStore_GetChunkFetcher(t *testing.T) { - cs := compositeStore{ + cs := CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(10), mockStoreGetChunkFetcher{mockStore(0), &fetcher.Fetcher{}}}, {model.TimeFromUnix(20), mockStoreGetChunkFetcher{mockStore(1), &fetcher.Fetcher{}}}, @@ -311,7 +313,7 @@ func (m mockStoreVolume) Volume(_ context.Context, _ string, _, _ model.Time, _ func TestVolume(t *testing.T) { t.Run("it returns volumes from all stores", func(t *testing.T) { - cs := compositeStore{ + cs := CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(10), mockStoreVolume{mockStore: mockStore(0), value: &logproto.VolumeResponse{ Volumes: []logproto.Volume{{Name: `{foo="bar"}`, Volume: 15}}, Limit: 10, @@ -328,7 +330,7 @@ func TestVolume(t *testing.T) { }) t.Run("it returns an error if any store returns an error", func(t *testing.T) { - cs := compositeStore{ + cs := CompositeStore{ stores: []compositeStoreEntry{ {model.TimeFromUnix(10), mockStoreVolume{mockStore: mockStore(0), value: &logproto.VolumeResponse{ Volumes: []logproto.Volume{{Name: `{foo="bar"}`, Volume: 15}}, Limit: 10,
chore
Simplify store interfaces and abstractions (pt 1) (#10435)
71c4421e09f30ebd8a1826c976436d3ca3ad603d
2024-08-13 19:14:54
renovate[bot]
fix(deps): update module github.com/azure/go-autorest/autorest/azure/auth to v0.5.13 (#13863)
false
diff --git a/go.mod b/go.mod index 822c126a6651e..582e6e20f9cb9 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/Azure/azure-pipeline-go v0.2.3 github.com/Azure/azure-storage-blob-go v0.14.0 github.com/Azure/go-autorest/autorest/adal v0.9.23 - github.com/Azure/go-autorest/autorest/azure/auth v0.5.12 + github.com/Azure/go-autorest/autorest/azure/auth v0.5.13 github.com/Masterminds/sprig/v3 v3.2.3 github.com/NYTimes/gziphandler v1.1.1 github.com/Shopify/sarama v1.38.1 @@ -188,7 +188,7 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.3.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect - github.com/Azure/go-autorest/autorest/azure/cli v0.4.5 // indirect + github.com/Azure/go-autorest/autorest/azure/cli v0.4.6 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect diff --git a/go.sum b/go.sum index 07561f75760ec..fc56ad065fb27 100644 --- a/go.sum +++ b/go.sum @@ -186,7 +186,7 @@ github.com/Azure/go-autorest/autorest v0.9.2/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+B github.com/Azure/go-autorest/autorest v0.9.3/go.mod h1:GsRuLYvwzLjjjRoWEIyMUaYq8GNUx2nRB378IPt/1p0= github.com/Azure/go-autorest/autorest v0.11.0/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= github.com/Azure/go-autorest/autorest v0.11.18/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= -github.com/Azure/go-autorest/autorest v0.11.24/go.mod h1:G6kyRlFnTuSbEYkQGawPfsCswgme4iYf6rfSKUDzbCc= +github.com/Azure/go-autorest/autorest v0.11.28/go.mod h1:MrkzG3Y3AH668QyF9KRk5neJnGgmhQ6krbhR8Q5eMvA= github.com/Azure/go-autorest/autorest v0.11.29 h1:I4+HL/JDvErx2LjyzaVxllw2lRDB5/BT2Bm4g20iqYw= github.com/Azure/go-autorest/autorest v0.11.29/go.mod h1:ZtEzC4Jy2JDrZLxvWs8LrBWEBycl1hbT1eknI8MtfAs= github.com/Azure/go-autorest/autorest/adal v0.1.0/go.mod h1:MeS4XhScH55IST095THyTxElntu7WqB7pNbZo8Q5G3E= @@ -204,13 +204,13 @@ github.com/Azure/go-autorest/autorest/azure/auth v0.1.0/go.mod h1:Gf7/i2FUpyb/sG github.com/Azure/go-autorest/autorest/azure/auth v0.4.1/go.mod h1:5TgH20II424SXIV9YDBsO4rBCKsh39Vbx9DvhJZZ8rU= github.com/Azure/go-autorest/autorest/azure/auth v0.4.2/go.mod h1:90gmfKdlmKgfjUpnCEpOJzsUEjrWDSLwHIG73tSXddM= github.com/Azure/go-autorest/autorest/azure/auth v0.5.0/go.mod h1:QRTvSZQpxqm8mSErhnbI+tANIBAKP7B+UIE2z4ypUO0= -github.com/Azure/go-autorest/autorest/azure/auth v0.5.12 h1:wkAZRgT/pn8HhFyzfe9UnqOjJYqlembgCTi72Bm/xKk= -github.com/Azure/go-autorest/autorest/azure/auth v0.5.12/go.mod h1:84w/uV8E37feW2NCJ08uT9VBfjfUHpgLVnG2InYD6cg= +github.com/Azure/go-autorest/autorest/azure/auth v0.5.13 h1:Ov8avRZi2vmrE2JcXw+tu5K/yB41r7xK9GZDiBF7NdM= +github.com/Azure/go-autorest/autorest/azure/auth v0.5.13/go.mod h1:5BAVfWLWXihP47vYrPuBKKf4cS0bXI+KM9Qx6ETDJYo= github.com/Azure/go-autorest/autorest/azure/cli v0.1.0/go.mod h1:Dk8CUAt/b/PzkfeRsWzVG9Yj3ps8mS8ECztu43rdU8U= github.com/Azure/go-autorest/autorest/azure/cli v0.3.1/go.mod h1:ZG5p860J94/0kI9mNJVoIoLgXcirM2gF5i2kWloofxw= github.com/Azure/go-autorest/autorest/azure/cli v0.4.0/go.mod h1:JljT387FplPzBA31vUcvsetLKF3pec5bdAxjVU4kI2s= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.5 h1:0W/yGmFdTIT77fvdlGZ0LMISoLHFJ7Tx4U0yeB+uFs4= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.5/go.mod h1:ADQAXrkgm7acgWVUNamOgh8YNrv4p27l3Wc55oVfpzg= +github.com/Azure/go-autorest/autorest/azure/cli v0.4.6 h1:w77/uPk80ZET2F+AfQExZyEWtn+0Rk/uw17m9fv5Ajc= +github.com/Azure/go-autorest/autorest/azure/cli v0.4.6/go.mod h1:piCfgPho7BiIDdEQ1+g4VmKyD5y+p/XtSNqE6Hc4QD0= github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= @@ -1982,12 +1982,12 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30= golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -2117,6 +2117,7 @@ golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -2288,6 +2289,7 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -2298,6 +2300,8 @@ golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk= golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4= @@ -2317,6 +2321,8 @@ golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/time v0.0.0-20161028155119-f51c12702a4d/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go index e97589dcdcb27..25697b3c854cc 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go @@ -21,7 +21,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "log" "os" "strings" @@ -325,7 +325,7 @@ func GetSettingsFromFile() (FileSettings, error) { return s, errors.New("environment variable AZURE_AUTH_LOCATION is not set") } - contents, err := ioutil.ReadFile(fileLocation) + contents, err := os.ReadFile(fileLocation) if err != nil { return s, err } @@ -488,7 +488,7 @@ func decode(b []byte) ([]byte, error) { } return []byte(string(utf16.Decode(u16))), nil } - return ioutil.ReadAll(reader) + return io.ReadAll(reader) } func (settings FileSettings) getResourceForToken(baseURI string) (string, error) { @@ -636,7 +636,7 @@ func (ccc ClientCertificateConfig) ServicePrincipalToken() (*adal.ServicePrincip if err != nil { return nil, err } - certData, err := ioutil.ReadFile(ccc.CertificatePath) + certData, err := os.ReadFile(ccc.CertificatePath) if err != nil { return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) } @@ -653,7 +653,7 @@ func (ccc ClientCertificateConfig) MultiTenantServicePrincipalToken() (*adal.Mul if err != nil { return nil, err } - certData, err := ioutil.ReadFile(ccc.CertificatePath) + certData, err := os.ReadFile(ccc.CertificatePath) if err != nil { return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) } diff --git a/vendor/modules.txt b/vendor/modules.txt index bc4cba78abd02..f7d6a4a7e7139 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -138,10 +138,10 @@ github.com/Azure/go-autorest/autorest/azure # github.com/Azure/go-autorest/autorest/adal v0.9.23 ## explicit; go 1.15 github.com/Azure/go-autorest/autorest/adal -# github.com/Azure/go-autorest/autorest/azure/auth v0.5.12 +# github.com/Azure/go-autorest/autorest/azure/auth v0.5.13 ## explicit; go 1.15 github.com/Azure/go-autorest/autorest/azure/auth -# github.com/Azure/go-autorest/autorest/azure/cli v0.4.5 +# github.com/Azure/go-autorest/autorest/azure/cli v0.4.6 ## explicit; go 1.15 github.com/Azure/go-autorest/autorest/azure/cli # github.com/Azure/go-autorest/autorest/date v0.3.0
fix
update module github.com/azure/go-autorest/autorest/azure/auth to v0.5.13 (#13863)
c8993168c57c405740c17b67336b6f0e30bcbf3c
2024-09-26 17:09:05
Tony Abboud
chore: Allow setting annotations for memberlist and query-scheduler-discovery services (#14211)
false
diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 21c1b00ac58a0..9add6158f3a6a 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -6485,6 +6485,15 @@ true "type": "RollingUpdate" } </pre> +</td> + </tr> + <tr> + <td>memberlist.service.annotations</td> + <td>object</td> + <td></td> + <td><pre lang="json"> +{} +</pre> </td> </tr> <tr> diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index b39023e85effc..519755dbec944 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -13,6 +13,9 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) +## 6.15.0 + +- [ENHANCEMENT] Allow setting annotations for memberlist and query-scheduler-discovery services ## 6.14.1 - [BUGFIX] Fixed Memcached persistence options. diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 24e94eb8bc508..56e48a535e070 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -3,7 +3,7 @@ name: loki description: Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. type: application appVersion: 3.1.1 -version: 6.14.1 +version: 6.15.0 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index dea0ec488b023..92008e768d6bc 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.14.1](https://img.shields.io/badge/Version-6.14.1-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.1.1](https://img.shields.io/badge/AppVersion-3.1.1-informational?style=flat-square) +![Version: 6.15.0](https://img.shields.io/badge/Version-6.15.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.1.1](https://img.shields.io/badge/AppVersion-3.1.1-informational?style=flat-square) Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. diff --git a/production/helm/loki/templates/backend/query-scheduler-discovery.yaml b/production/helm/loki/templates/backend/query-scheduler-discovery.yaml index 14bca1fa041fc..4c357e53a431f 100644 --- a/production/helm/loki/templates/backend/query-scheduler-discovery.yaml +++ b/production/helm/loki/templates/backend/query-scheduler-discovery.yaml @@ -9,6 +9,13 @@ metadata: labels: {{- include "loki.backendSelectorLabels" . | nindent 4 }} prometheus.io/service-monitor: "false" + annotations: + {{- with .Values.loki.serviceAnnotations }} + {{- toYaml . | nindent 4}} + {{- end }} + {{- with .Values.backend.service.annotations }} + {{- toYaml . | nindent 4}} + {{- end }} spec: type: ClusterIP clusterIP: None diff --git a/production/helm/loki/templates/service-memberlist.yaml b/production/helm/loki/templates/service-memberlist.yaml index cacb5b1e872bb..3d46f234d4eab 100644 --- a/production/helm/loki/templates/service-memberlist.yaml +++ b/production/helm/loki/templates/service-memberlist.yaml @@ -6,6 +6,13 @@ metadata: namespace: {{ $.Release.Namespace }} labels: {{- include "loki.labels" . | nindent 4 }} + annotations: + {{- with .Values.loki.serviceAnnotations }} + {{- toYaml . | nindent 4}} + {{- end }} + {{- with .Values.memberlist.service.annotations }} + {{- toYaml . | nindent 4}} + {{- end }} spec: type: ClusterIP clusterIP: None diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index fe7b9273ee80a..a3ee28a805338 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -794,6 +794,7 @@ networkPolicy: memberlist: service: publishNotReadyAddresses: false + annotations: {} ###################################################################################################################### # # adminAPI configuration, enterprise only.
chore
Allow setting annotations for memberlist and query-scheduler-discovery services (#14211)
347a3e18f4976d799d51a26cee229efbc27ef6c9
2019-08-03 00:51:56
Edward Welch
release: update ksonnet and helm charts to version v0.2.0
false
diff --git a/production/helm/loki-stack/Chart.yaml b/production/helm/loki-stack/Chart.yaml index e671115d92205..5077369c972f1 100644 --- a/production/helm/loki-stack/Chart.yaml +++ b/production/helm/loki-stack/Chart.yaml @@ -1,5 +1,5 @@ name: loki-stack -version: 0.13.1 +version: 0.14.0 appVersion: 0.0.1 kubeVersion: "^1.10.0-0" description: "Loki: like Prometheus, but for logs." diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 26552809fc52d..21e164747da72 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -1,5 +1,5 @@ name: loki -version: 0.12.0 +version: 0.13.0 appVersion: 0.0.1 kubeVersion: "^1.10.0-0" description: "Loki: like Prometheus, but for logs." diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index 3f25cffd0cfaa..264514140b3d8 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -66,7 +66,7 @@ config: image: repository: grafana/loki - tag: v0.1.0 + tag: v0.2.0 pullPolicy: IfNotPresent ## Additional Loki container arguments, e.g. log level (debug, info, warn, error) diff --git a/production/helm/promtail/Chart.yaml b/production/helm/promtail/Chart.yaml index fdeb252de0a24..19a6d76ee1d32 100644 --- a/production/helm/promtail/Chart.yaml +++ b/production/helm/promtail/Chart.yaml @@ -1,5 +1,5 @@ name: promtail -version: 0.9.0 +version: 0.10.0 appVersion: 0.0.1 kubeVersion: "^1.10.0-0" description: "Responsible for gathering logs and sending them to Loki" diff --git a/production/helm/promtail/values.yaml b/production/helm/promtail/values.yaml index 508f8338584bd..8c74282d30c14 100644 --- a/production/helm/promtail/values.yaml +++ b/production/helm/promtail/values.yaml @@ -8,7 +8,7 @@ deploymentStrategy: RollingUpdate image: repository: grafana/promtail - tag: v0.1.0 + tag: v0.2.0 pullPolicy: IfNotPresent livenessProbe: {} diff --git a/production/ksonnet/loki/images.libsonnet b/production/ksonnet/loki/images.libsonnet index 08e84be54de72..8f76fb152b5d2 100644 --- a/production/ksonnet/loki/images.libsonnet +++ b/production/ksonnet/loki/images.libsonnet @@ -4,7 +4,7 @@ memcached: 'memcached:1.5.6-alpine', memcachedExporter: 'prom/memcached-exporter:v0.4.1', - loki: 'grafana/loki:v0.1.0', + loki: 'grafana/loki:v0.2.0', distributor: self.loki, ingester: self.loki, diff --git a/production/ksonnet/promtail/config.libsonnet b/production/ksonnet/promtail/config.libsonnet index e3c2a293368ea..dade4569733bc 100644 --- a/production/ksonnet/promtail/config.libsonnet +++ b/production/ksonnet/promtail/config.libsonnet @@ -1,6 +1,6 @@ { _images+:: { - promtail: 'grafana/promtail:v0.1.0', + promtail: 'grafana/promtail:v0.2.0', }, _config+:: {
release
update ksonnet and helm charts to version v0.2.0
ed0b1f9edc04dc127a9ab02d6c7cf7f869ef34bb
2024-12-06 03:14:56
loki-gh-app[bot]
chore: release loki helm chart 6.23.0 (#15271)
false
diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 4975387e96dc8..0e5b534e10851 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -3062,7 +3062,7 @@ null "pullPolicy": "IfNotPresent", "registry": "docker.io", "repository": "grafana/enterprise-logs", - "tag": "3.3.0" + "tag": "3.3.1" }, "license": { "contents": "NOTAVALIDLICENSE" @@ -3235,7 +3235,7 @@ null <td>string</td> <td>Docker image tag</td> <td><pre lang="json"> -"3.3.0" +"3.3.1" </pre> </td> </tr> @@ -6090,7 +6090,7 @@ null <td>string</td> <td>Overrides the image tag whose default is the chart's appVersion</td> <td><pre lang="json"> -"3.3.0" +"3.3.1" </pre> </td> </tr> diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index 9f21593b2e403..dfc51d67d0a42 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -12,11 +12,17 @@ Entries should be ordered as follows: Entries should include a reference to the pull request that introduced the change. [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) -- [CHANGE] Changed version of Minio helm chart to 5.3.0 (#14834) +## 6.23.0 + +- [CHANGE] Changed version of Grafana Loki to 3.3.1 +- [CHANGE] Changed version of Minio helm chart to 5.3.0 (#14834) - [BUGFIX] Add default wal dir to ruler config ([#14920](https://github.com/grafana/loki/pull/14920)) + ## 6.22.0 +## 6.21.0 + ## 6.20.0 - [CHANGE] Changed version of Grafana Loki to 3.3.0 diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 7fd96976ad7ad..e1b62848c2e0b 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: loki description: Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. type: application -appVersion: 3.3.0 -version: 6.22.0 +appVersion: 3.3.1 +version: 6.23.0 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index 7396e9c3a61e6..bbc39ed7c4bef 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.22.0](https://img.shields.io/badge/Version-6.22.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.3.0](https://img.shields.io/badge/AppVersion-3.3.0-informational?style=flat-square) +![Version: 6.23.0](https://img.shields.io/badge/Version-6.23.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.3.1](https://img.shields.io/badge/AppVersion-3.3.1-informational?style=flat-square) Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index 94afe8f5a829e..855e589a097cb 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -56,7 +56,7 @@ loki: # -- Docker image repository repository: grafana/loki # -- Overrides the image tag whose default is the chart's appVersion - tag: 3.3.0 + tag: 3.3.1 # -- Overrides the image tag with an image digest digest: null # -- Docker image pull policy @@ -520,7 +520,7 @@ enterprise: # -- Docker image repository repository: grafana/enterprise-logs # -- Docker image tag - tag: 3.3.0 + tag: 3.3.1 # -- Overrides the image tag with an image digest digest: null # -- Docker image pull policy
chore
release loki helm chart 6.23.0 (#15271)
e915efc7f81350ea82d4dcbe105055075df6fc76
2024-01-11 19:06:37
Ashwanth
fix(log results cache): compose empty response based on the request (#11657)
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 357714b030b1a..612b70ab36fd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ * [11551](https://github.com/grafana/loki/pull/11551) **dannykopping** Do not reflect label names in request metrics' "route" label. * [11601](https://github.com/grafana/loki/pull/11601) **dannykopping** Ruler: Fixed a panic that can be caused by concurrent read-write access of tenant configs when there are a large amount of rules. * [11606](https://github.com/grafana/loki/pull/11606) **dannykopping** Fixed regression adding newlines to HTTP error response bodies which may break client integrations. +* [11657](https://github.com/grafana/loki/pull/11657) **ashwanthgoli** Log results cache: compose empty response based on the request being served to avoid returning incorrect limit or direction. ##### Changes diff --git a/pkg/querier/queryrange/log_result_cache.go b/pkg/querier/queryrange/log_result_cache.go index c15568d9075ac..fd26b67412a6b 100644 --- a/pkg/querier/queryrange/log_result_cache.go +++ b/pkg/querier/queryrange/log_result_cache.go @@ -106,7 +106,8 @@ func (l *logResultCache) Do(ctx context.Context, req queryrangebase.Request) (qu interval := validation.SmallestPositiveNonZeroDurationPerTenant(tenantIDs, l.limits.QuerySplitDuration) // skip caching by if interval is unset - if interval == 0 { + // skip caching when limit is 0 as it would get registerted as empty result in the cache even if that time range contains log lines. + if interval == 0 || lokiReq.Limit == 0 { return l.next.Do(ctx, req) } // The first subquery might not be aligned. @@ -181,7 +182,7 @@ func (l *logResultCache) handleMiss(ctx context.Context, cacheKey string, req *L func (l *logResultCache) handleHit(ctx context.Context, cacheKey string, cachedRequest *LokiRequest, lokiReq *LokiRequest) (queryrangebase.Response, error) { l.metrics.CacheHit.Inc() // we start with an empty response - result := emptyResponse(cachedRequest) + result := emptyResponse(lokiReq) // if the request is the same and cover the whole time range, // we can just return the cached result. if cachedRequest.StartTs.UnixNano() <= lokiReq.StartTs.UnixNano() && cachedRequest.EndTs.UnixNano() >= lokiReq.EndTs.UnixNano() { diff --git a/pkg/querier/queryrange/log_result_cache_test.go b/pkg/querier/queryrange/log_result_cache_test.go index 5d67be33b84fd..5da4aee7c4be3 100644 --- a/pkg/querier/queryrange/log_result_cache_test.go +++ b/pkg/querier/queryrange/log_result_cache_test.go @@ -580,6 +580,54 @@ func Test_LogResultNonOverlappingCache(t *testing.T) { fake.AssertExpectations(t) } +func Test_LogResultCacheDifferentLimit(t *testing.T) { + var ( + ctx = user.InjectOrgID(context.Background(), "foo") + lrc = NewLogResultCache( + log.NewNopLogger(), + fakeLimits{ + splitDuration: map[string]time.Duration{"foo": time.Minute}, + }, + cache.NewMockCache(), + nil, + nil, + nil, + ) + ) + + req1 := &LokiRequest{ + StartTs: time.Unix(0, time.Minute.Nanoseconds()), + EndTs: time.Unix(0, 2*time.Minute.Nanoseconds()), + Limit: entriesLimit, + } + + req2 := &LokiRequest{ + StartTs: time.Unix(0, time.Minute.Nanoseconds()), + EndTs: time.Unix(0, 2*time.Minute.Nanoseconds()), + Limit: 10, + } + + fake := newFakeResponse([]mockResponse{ + { + RequestResponse: queryrangebase.RequestResponse{ + Request: req1, + Response: emptyResponse(req1), + }, + }, + }) + + h := lrc.Wrap(fake) + + resp, err := h.Do(ctx, req1) + require.NoError(t, err) + require.Equal(t, emptyResponse(req1), resp) + resp, err = h.Do(ctx, req2) + require.NoError(t, err) + require.Equal(t, emptyResponse(req2), resp) + + fake.AssertExpectations(t) +} + func TestExtractLokiResponse(t *testing.T) { for _, tc := range []struct { name string @@ -677,6 +725,7 @@ func newFakeResponse(responses []mockResponse) fakeResponse { for _, r := range responses { m.On("Do", mock.Anything, r.Request).Return(r.Response, r.err).Once() } + return fakeResponse{ Mock: m, }
fix
compose empty response based on the request (#11657)
9bdd5d15bf6485f52e53d61ad1304595718fb05d
2025-03-14 13:58:40
Christian Haudum
chore: Add tree printer for physical plan (#16716)
false
diff --git a/.golangci.yml b/.golangci.yml index 0618237e0d024..393857006ffb0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -76,6 +76,7 @@ issues: - Error return value of .*log\.Logger\)\.Log\x60 is not checked - Error return value of .*.Log.* is not checked - Error return value of `` is not checked + - Error return value of `.*WriteString` is not checked exclude-rules: - path: pkg/scheduler/scheduler.go text: 'SA1019: msg.GetHttpRequest is deprecated: Do not use' diff --git a/pkg/dataobj/planner/internal/tree/printer.go b/pkg/dataobj/planner/internal/tree/printer.go new file mode 100644 index 0000000000000..c2c8c20f03e6e --- /dev/null +++ b/pkg/dataobj/planner/internal/tree/printer.go @@ -0,0 +1,202 @@ +package tree + +import ( + "fmt" + "io" +) + +const ( + symPrefix = " " + symIndent = "│ " + symConn = "├── " + symLastConn = "└── " +) + +// Property represents a property of a [Node]. It is a key-value-pair, where +// the value is either a single value or a list of values. +// When the value is a multi-value, the field IsMultiValue needs to be set to +// `true`. +// A single-value property is represented as `key=value` and a multi-value +// property as `key=(value1, value2, ...)`. +type Property struct { + // Key is the name of the property. + Key string + // Values holds the value(s) of the property. + Values []any + // IsMultiValue marks whether the property is a multi-value property. + IsMultiValue bool +} + +// NewProperty creates a new Property with the specified key, multi-value flag, and values. +// The multi parameter determines if the property should be treated as a multi-value property. +func NewProperty(key string, multi bool, values ...any) Property { + return Property{ + Key: key, + Values: values, + IsMultiValue: multi, + } +} + +// Node represents a node in a tree structure that can be traversed and printed +// by the [Printer]. +// It allows for building hierarchical representations of data where each node +// can have multiple properties and multiple children. +type Node struct { + // ID is a unique identifier for the node. + ID string + // Name is the display name of the node. + Name string + // Properties contains a list of key-value properties associated with the node. + Properties []Property + // Children are child nodes of the node. + Children []*Node + // Comments, like Children, are child nodes of the node, with the difference + // that comments are indented a level deeper than children. A common use-case + // for comments are tree-style properies of a node, such as expressions of a + // physical plan node. + Comments []*Node +} + +// NewNode creates a new node with the given name, unique identifier and +// properties. +func NewNode(name, id string, properties ...Property) *Node { + return &Node{ + ID: id, + Name: name, + Properties: properties, + } +} + +// AddChild creates a new node with the given name, unique identifier, and properties +// and adds it to the parent node. +func (n *Node) AddChild(name, id string, properties []Property) *Node { + child := NewNode(name, id, properties...) + n.Children = append(n.Children, child) + return child +} + +func (n *Node) AddComment(name, id string, properties []Property) *Node { + node := NewNode(name, id, properties...) + n.Comments = append(n.Comments, node) + return node +} + +// Printer is used for writing the hierarchical representation of a tree +// of [Node]s. +type Printer struct { + w io.StringWriter +} + +// NewPrinter creates a new [Printer] instance that writes to the specified +// [io.StringWriter]. +func NewPrinter(w io.StringWriter) *Printer { + return &Printer{w: w} +} + +// Print writes the entire tree structure starting from the given root node to +// the printer's [io.StringWriter]. +// Example output: +// +// SortMerge #sort order=ASC column=timestamp +// ├── Limit #limit1 limit=1000 +// │ └── DataObjScan #scan1 location=dataobj_1 +// └── Limit #limit2 limit=1000 +// └── DataObjScan #scan2 location=dataobj_2 +func (tp *Printer) Print(root *Node) { + tp.printNode(root) + tp.printChildren(root.Comments, root.Children, "") +} + +func (tp *Printer) printNode(node *Node) { + tp.w.WriteString(node.Name) + + if node.ID != "" { + tp.w.WriteString(" #") + tp.w.WriteString(node.ID) + } + + if len(node.Properties) == 0 { + tp.w.WriteString("\n") + return + } + + tp.w.WriteString(" ") + for i, attr := range node.Properties { + tp.w.WriteString(attr.Key) + tp.w.WriteString("=") + + if attr.IsMultiValue { + tp.w.WriteString("(") + } + for ii, val := range attr.Values { + tp.w.WriteString(fmt.Sprintf("%v", val)) + if ii < len(attr.Values)-1 { + tp.w.WriteString(", ") + } + } + + if attr.IsMultiValue { + tp.w.WriteString(")") + } + if i < len(node.Properties)-1 { + tp.w.WriteString(" ") + } + } + tp.w.WriteString("\n") +} + +// printChildren recursively prints all children with appropriate indentation +func (tp *Printer) printChildren(comments, children []*Node, prefix string) { + hasChildren := len(children) > 0 + + // Iterate over sub nodes first. + // They have extended indentation compared to regular child nodes + // and depending if there are child nodes, also have a | as prefix. + for i, node := range comments { + isLast := i == len(comments)-1 + + // Choose connector symbols based on whether this is the last item + connector := symPrefix + symConn + newPrefix := prefix + symIndent + symIndent + if hasChildren { + connector = symIndent + symConn + } + + if isLast { + connector = symPrefix + symLastConn + newPrefix = prefix + symIndent + symPrefix + if hasChildren { + connector = symIndent + symLastConn + } + } + + // Print this node + tp.w.WriteString(prefix) + tp.w.WriteString(connector) + tp.printNode(node) + + // Recursively print children + tp.printChildren(node.Comments, node.Children, newPrefix) + } + + // Iterate over child nodes last. + for i, node := range children { + isLast := i == len(children)-1 + + // Choose connector symbols based on whether this is the last item + connector := symConn + newPrefix := prefix + symIndent + if isLast { + connector = symLastConn + newPrefix = prefix + symPrefix + } + + // Print this node + tp.w.WriteString(prefix) + tp.w.WriteString(connector) + tp.printNode(node) + + // Recursively print children + tp.printChildren(node.Comments, node.Children, newPrefix) + } +} diff --git a/pkg/dataobj/planner/internal/tree/printer_test.go b/pkg/dataobj/planner/internal/tree/printer_test.go new file mode 100644 index 0000000000000..c13933c7c577f --- /dev/null +++ b/pkg/dataobj/planner/internal/tree/printer_test.go @@ -0,0 +1,51 @@ +package tree + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrinter(t *testing.T) { + root := NewNode("Root", "") + lvl1 := root.AddChild("Merge", "foo", []Property{ + {Key: "key_a", Values: []any{"value_a"}, IsMultiValue: true}, + {Key: "key_b", Values: []any{"value_b", "value_c"}, IsMultiValue: true}, + }) + lvl2 := lvl1.AddChild("Product", "foobar", []Property{ + {Key: "relations", Values: []any{"foo", "bar"}, IsMultiValue: true}, + }) + rel := lvl2.AddComment("Relation", "foo", nil) + rel.AddChild("Shard", "0", nil) + rel.AddChild("Shard", "1", nil) + rel.AddChild("Shard", "2", nil) + lvl2.AddComment("Relation", "bar", nil) + lvl2.AddChild("Scan", "foo", []Property{ + {Key: "selector", Values: []any{`{env="prod", region=".+"}`}}, + }) + lvl2.AddChild("Scan", "bar", []Property{ + {Key: "selector", Values: []any{`{env="dev", region=".+"}`}}, + }) + _ = lvl1.AddChild("Scan", "baz", []Property{}) + + b := &strings.Builder{} + p := NewPrinter(b) + p.Print(root) + + t.Log("\n" + b.String()) + expected := ` +Root +└── Merge #foo key_a=(value_a) key_b=(value_b, value_c) + ├── Product #foobar relations=(foo, bar) + │ │ ├── Relation #foo + │ │ │ ├── Shard #0 + │ │ │ ├── Shard #1 + │ │ │ └── Shard #2 + │ │ └── Relation #bar + │ ├── Scan #foo selector={env="prod", region=".+"} + │ └── Scan #bar selector={env="dev", region=".+"} + └── Scan #baz +` + require.Equal(t, expected, "\n"+b.String()) +} diff --git a/pkg/dataobj/planner/physical/printer.go b/pkg/dataobj/planner/physical/printer.go new file mode 100644 index 0000000000000..7a0162d6eab51 --- /dev/null +++ b/pkg/dataobj/planner/physical/printer.go @@ -0,0 +1,82 @@ +package physical + +import ( + "strings" + + "github.com/grafana/loki/v3/pkg/dataobj/planner/internal/tree" +) + +// BuildTree converts a physical plan node and its children into a tree structure +// that can be used for visualization and debugging purposes. +func BuildTree(p *Plan, n Node) *tree.Node { + return toTree(p, n) +} + +func toTree(p *Plan, n Node) *tree.Node { + root := toTreeNode(n) + for _, child := range p.Children(n) { + if ch := toTree(p, child); ch != nil { + root.Children = append(root.Children, ch) + } + } + return root +} + +func toTreeNode(n Node) *tree.Node { + treeNode := tree.NewNode(n.Type().String(), n.ID()) + switch node := n.(type) { + case *DataObjScan: + treeNode.Properties = []tree.Property{ + tree.NewProperty("location", false, node.Location), + tree.NewProperty("stream_ids", true, toAnySlice(node.StreamIDs)...), + tree.NewProperty("projections", true, toAnySlice(node.Projections)...), + tree.NewProperty("predicates", true, toAnySlice(node.Predicates)...), + tree.NewProperty("direction", false, node.Direction), + tree.NewProperty("limit", false, node.Limit), + } + case *SortMerge: + treeNode.Properties = []tree.Property{ + tree.NewProperty("column", false, node.Column), + tree.NewProperty("order", false, node.Order), + } + case *Projection: + treeNode.Properties = []tree.Property{ + tree.NewProperty("columns", true, toAnySlice(node.Columns)...), + } + case *Filter: + treeNode.Properties = []tree.Property{ + tree.NewProperty("predicates", true, toAnySlice(node.Predicates)...), + } + case *Limit: + treeNode.Properties = []tree.Property{ + tree.NewProperty("offset", false, node.Offset), + tree.NewProperty("limit", false, node.Limit), + } + } + return treeNode +} + +func toAnySlice[T any](s []T) []any { + ret := make([]any, len(s)) + for i := range s { + ret[i] = s[i] + } + return ret +} + +// PrintAsTree converts a physical [Plan] into a human-readable tree representation. +// It processes each root node in the plan graph, and returns the combined +// string output of all trees joined by newlines. +func PrintAsTree(p *Plan) string { + results := make([]string, 0, len(p.Roots())) + + for _, root := range p.Roots() { + sb := &strings.Builder{} + printer := tree.NewPrinter(sb) + node := BuildTree(p, root) + printer.Print(node) + results = append(results, sb.String()) + } + + return strings.Join(results, "\n") +} diff --git a/pkg/dataobj/planner/physical/printer_test.go b/pkg/dataobj/planner/physical/printer_test.go new file mode 100644 index 0000000000000..3d5ebebbe863c --- /dev/null +++ b/pkg/dataobj/planner/physical/printer_test.go @@ -0,0 +1,52 @@ +package physical + +import "testing" + +func TestPrinter(t *testing.T) { + t.Run("simple tree", func(t *testing.T) { + p := &Plan{} + + limit := p.addNode(&Limit{id: "limit"}) + filter := p.addNode(&Filter{id: "filter"}) + merge := p.addNode(&SortMerge{id: "merge"}) + scan1 := p.addNode(&DataObjScan{id: "scan1"}) + scan2 := p.addNode(&DataObjScan{id: "scan2"}) + _ = p.addEdge(Edge{Parent: limit, Child: filter}) + _ = p.addEdge(Edge{Parent: filter, Child: merge}) + _ = p.addEdge(Edge{Parent: merge, Child: scan1}) + _ = p.addEdge(Edge{Parent: merge, Child: scan2}) + + repr := PrintAsTree(p) + t.Log("\n" + repr) + }) + + t.Run("multiple root nodes", func(t *testing.T) { + p := &Plan{} + + limit1 := p.addNode(&Limit{id: "limit1"}) + scan1 := p.addNode(&DataObjScan{id: "scan1"}) + _ = p.addEdge(Edge{Parent: limit1, Child: scan1}) + + limit2 := p.addNode(&Limit{id: "limit2"}) + scan2 := p.addNode(&DataObjScan{id: "scan2"}) + _ = p.addEdge(Edge{Parent: limit2, Child: scan2}) + + repr := PrintAsTree(p) + t.Log("\n" + repr) + }) + + t.Run("multiple parents sharing the same child node", func(t *testing.T) { + p := &Plan{} + limit := p.addNode(&Limit{id: "limit"}) + filter1 := p.addNode(&Limit{id: "filter1"}) + filter2 := p.addNode(&Limit{id: "filter2"}) + scan := p.addNode(&DataObjScan{id: "scan"}) + _ = p.addEdge(Edge{Parent: limit, Child: filter1}) + _ = p.addEdge(Edge{Parent: limit, Child: filter2}) + _ = p.addEdge(Edge{Parent: filter1, Child: scan}) + _ = p.addEdge(Edge{Parent: filter2, Child: scan}) + + repr := PrintAsTree(p) + t.Log("\n" + repr) + }) +}
chore
Add tree printer for physical plan (#16716)
44523e085dc2576b8929659250f8ae421a084443
2024-11-25 15:24:22
Bayan Taani
feat: Add objstore support for Swift using thanos.io/objstore (#11672)
false
diff --git a/docs/sources/shared/configuration.md b/docs/sources/shared/configuration.md index 40ee8f681fc1d..f8a1b518facba 100644 --- a/docs/sources/shared/configuration.md +++ b/docs/sources/shared/configuration.md @@ -5976,6 +5976,12 @@ The `swift_storage_config` block configures the connection to OpenStack Object S # is received on a request. # CLI flag: -<prefix>.swift.request-timeout [request_timeout: <duration> | default = 5s] + +http: + # Path to the CA certificates to validate server certificate against. If not + # set, the host's root CA certificates are used. + # CLI flag: -<prefix>.swift.http.tls-ca-path + [tls_ca_path: <string> | default = ""] ``` ### table_manager diff --git a/pkg/logqlmodel/stats/context.go b/pkg/logqlmodel/stats/context.go index 36235d8d9f09a..cacd509a11686 100644 --- a/pkg/logqlmodel/stats/context.go +++ b/pkg/logqlmodel/stats/context.go @@ -108,7 +108,7 @@ func (c *Context) Index() Index { return c.index } -// Merge index stats from multiple respones in a concurrency-safe manner +// Merge index stats from multiple response in a concurrency-safe manner func (c *Context) MergeIndex(i Index) { c.mtx.Lock() defer c.mtx.Unlock() diff --git a/pkg/loki/config_wrapper_test.go b/pkg/loki/config_wrapper_test.go index 203baecf4aec0..952804d607de4 100644 --- a/pkg/loki/config_wrapper_test.go +++ b/pkg/loki/config_wrapper_test.go @@ -547,9 +547,9 @@ memberlist: assert.Equal(t, "swift", config.Ruler.StoreConfig.Type) - for _, actual := range []swift.Config{ - config.Ruler.StoreConfig.Swift.Config, - config.StorageConfig.Swift.Config, + for _, actual := range []openstack.SwiftConfig{ + config.Ruler.StoreConfig.Swift, + config.StorageConfig.Swift, } { assert.Equal(t, 3, actual.AuthVersion) assert.Equal(t, "http://example.com", actual.AuthURL) @@ -557,7 +557,7 @@ memberlist: assert.Equal(t, "example.com", actual.UserDomainName) assert.Equal(t, "1", actual.UserDomainID) assert.Equal(t, "27", actual.UserID) - assert.Equal(t, "supersecret", actual.Password) + assert.Equal(t, flagext.SecretWithValue("supersecret"), actual.Password) assert.Equal(t, "2", actual.DomainID) assert.Equal(t, "test.com", actual.DomainName) assert.Equal(t, "13", actual.ProjectID) diff --git a/pkg/storage/bucket/client.go b/pkg/storage/bucket/client.go index 327f6f3f9cab1..6372aea2a9b1c 100644 --- a/pkg/storage/bucket/client.go +++ b/pkg/storage/bucket/client.go @@ -176,7 +176,7 @@ func (cfg *Config) configureTransport(backend string, rt http.RoundTripper) erro case Azure: cfg.Azure.Transport = rt case Swift: - cfg.Swift.Transport = rt + cfg.Swift.HTTP.Transport = rt case Filesystem, Alibaba, BOS: // do nothing default: diff --git a/pkg/storage/bucket/http/config.go b/pkg/storage/bucket/http/config.go index 509de0bf301f1..0527051bafd28 100644 --- a/pkg/storage/bucket/http/config.go +++ b/pkg/storage/bucket/http/config.go @@ -2,6 +2,7 @@ package http import ( "flag" + "net/http" "time" ) @@ -15,7 +16,19 @@ type Config struct { MaxIdleConns int `yaml:"max_idle_connections"` MaxIdleConnsPerHost int `yaml:"max_idle_connections_per_host"` MaxConnsPerHost int `yaml:"max_connections_per_host"` - CAFile string `yaml:"ca_file"` + + // Allow upstream callers to inject a round tripper + Transport http.RoundTripper `yaml:"-"` + + TLSConfig TLSConfig `yaml:",inline"` +} + +// TLSConfig configures the options for TLS connections. +type TLSConfig struct { + CAPath string `yaml:"tls_ca_path" category:"advanced"` + CertPath string `yaml:"tls_cert_path" category:"advanced"` + KeyPath string `yaml:"tls_key_path" category:"advanced"` + ServerName string `yaml:"tls_server_name" category:"advanced"` } // RegisterFlags registers the flags for the storage HTTP client. @@ -25,13 +38,21 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) { // RegisterFlagsWithPrefix registers the flags for the storage HTTP client with the provided prefix. func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { - f.DurationVar(&cfg.IdleConnTimeout, prefix+"idle-conn-timeout", 90*time.Second, "The time an idle connection will remain idle before closing.") - f.DurationVar(&cfg.ResponseHeaderTimeout, prefix+"response-header-timeout", 2*time.Minute, "The amount of time the client will wait for a servers response headers.") - f.BoolVar(&cfg.InsecureSkipVerify, prefix+"insecure-skip-verify", false, "If the client connects via HTTPS and this option is enabled, the client will accept any certificate and hostname.") + f.DurationVar(&cfg.IdleConnTimeout, prefix+"http.idle-conn-timeout", 90*time.Second, "The time an idle connection will remain idle before closing.") + f.DurationVar(&cfg.ResponseHeaderTimeout, prefix+"http.response-header-timeout", 2*time.Minute, "The amount of time the client will wait for a servers response headers.") + f.BoolVar(&cfg.InsecureSkipVerify, prefix+"http.insecure-skip-verify", false, "If the client connects via HTTPS and this option is enabled, the client will accept any certificate and hostname.") f.DurationVar(&cfg.TLSHandshakeTimeout, prefix+"tls-handshake-timeout", 10*time.Second, "Maximum time to wait for a TLS handshake. 0 means no limit.") f.DurationVar(&cfg.ExpectContinueTimeout, prefix+"expect-continue-timeout", 1*time.Second, "The time to wait for a server's first response headers after fully writing the request headers if the request has an Expect header. 0 to send the request body immediately.") f.IntVar(&cfg.MaxIdleConns, prefix+"max-idle-connections", 100, "Maximum number of idle (keep-alive) connections across all hosts. 0 means no limit.") f.IntVar(&cfg.MaxIdleConnsPerHost, prefix+"max-idle-connections-per-host", 100, "Maximum number of idle (keep-alive) connections to keep per-host. If 0, a built-in default value is used.") f.IntVar(&cfg.MaxConnsPerHost, prefix+"max-connections-per-host", 0, "Maximum number of connections per host. 0 means no limit.") - f.StringVar(&cfg.CAFile, prefix+"ca-file", "", "Path to the trusted CA file that signed the SSL certificate of the object storage endpoint.") + cfg.TLSConfig.RegisterFlagsWithPrefix(prefix, f) +} + +// RegisterFlagsWithPrefix registers the flags for s3 storage with the provided prefix. +func (cfg *TLSConfig) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { + f.StringVar(&cfg.CAPath, prefix+"http.tls-ca-path", "", "Path to the CA certificates to validate server certificate against. If not set, the host's root CA certificates are used.") + f.StringVar(&cfg.CertPath, prefix+"http.tls-cert-path", "", "Path to the client certificate, which will be used for authenticating with the server. Also requires the key path to be configured.") + f.StringVar(&cfg.KeyPath, prefix+"http.tls-key-path", "", "Path to the key for the client certificate. Also requires the client certificate to be configured.") + f.StringVar(&cfg.ServerName, prefix+"http.tls-server-name", "", "Override the expected name on the server certificate.") } diff --git a/pkg/storage/bucket/s3/config.go b/pkg/storage/bucket/s3/config.go index 67c412de6d606..053e35209d118 100644 --- a/pkg/storage/bucket/s3/config.go +++ b/pkg/storage/bucket/s3/config.go @@ -4,10 +4,8 @@ import ( "encoding/json" "flag" "fmt" - "net/http" "slices" "strings" - "time" s3_service "github.com/aws/aws-sdk-go/service/s3" "github.com/grafana/dskit/flagext" @@ -15,6 +13,7 @@ import ( "github.com/pkg/errors" "github.com/thanos-io/objstore/providers/s3" + "github.com/grafana/loki/v3/pkg/storage/bucket/http" "github.com/grafana/loki/v3/pkg/util" ) @@ -55,52 +54,6 @@ func thanosS3BucketLookupTypesValues() (list []string) { return list } -// HTTPConfig stores the http.Transport configuration for the s3 minio client. -type HTTPConfig struct { - IdleConnTimeout time.Duration `yaml:"idle_conn_timeout" category:"advanced"` - ResponseHeaderTimeout time.Duration `yaml:"response_header_timeout" category:"advanced"` - InsecureSkipVerify bool `yaml:"insecure_skip_verify" category:"advanced"` - TLSHandshakeTimeout time.Duration `yaml:"tls_handshake_timeout" category:"advanced"` - ExpectContinueTimeout time.Duration `yaml:"expect_continue_timeout" category:"advanced"` - MaxIdleConns int `yaml:"max_idle_connections" category:"advanced"` - MaxIdleConnsPerHost int `yaml:"max_idle_connections_per_host" category:"advanced"` - MaxConnsPerHost int `yaml:"max_connections_per_host" category:"advanced"` - - // Allow upstream callers to inject a round tripper - Transport http.RoundTripper `yaml:"-"` - - TLSConfig TLSConfig `yaml:",inline"` -} - -// TLSConfig configures the options for TLS connections. -type TLSConfig struct { - CAPath string `yaml:"tls_ca_path" category:"advanced"` - CertPath string `yaml:"tls_cert_path" category:"advanced"` - KeyPath string `yaml:"tls_key_path" category:"advanced"` - ServerName string `yaml:"tls_server_name" category:"advanced"` -} - -// RegisterFlagsWithPrefix registers the flags for s3 storage with the provided prefix -func (cfg *HTTPConfig) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { - f.DurationVar(&cfg.IdleConnTimeout, prefix+"s3.http.idle-conn-timeout", 90*time.Second, "The time an idle connection will remain idle before closing.") - f.DurationVar(&cfg.ResponseHeaderTimeout, prefix+"s3.http.response-header-timeout", 2*time.Minute, "The amount of time the client will wait for a servers response headers.") - f.BoolVar(&cfg.InsecureSkipVerify, prefix+"s3.http.insecure-skip-verify", false, "If the client connects to S3 via HTTPS and this option is enabled, the client will accept any certificate and hostname.") - f.DurationVar(&cfg.TLSHandshakeTimeout, prefix+"s3.tls-handshake-timeout", 10*time.Second, "Maximum time to wait for a TLS handshake. 0 means no limit.") - f.DurationVar(&cfg.ExpectContinueTimeout, prefix+"s3.expect-continue-timeout", 1*time.Second, "The time to wait for a server's first response headers after fully writing the request headers if the request has an Expect header. 0 to send the request body immediately.") - f.IntVar(&cfg.MaxIdleConns, prefix+"s3.max-idle-connections", 100, "Maximum number of idle (keep-alive) connections across all hosts. 0 means no limit.") - f.IntVar(&cfg.MaxIdleConnsPerHost, prefix+"s3.max-idle-connections-per-host", 100, "Maximum number of idle (keep-alive) connections to keep per-host. If 0, a built-in default value is used.") - f.IntVar(&cfg.MaxConnsPerHost, prefix+"s3.max-connections-per-host", 0, "Maximum number of connections per host. 0 means no limit.") - cfg.TLSConfig.RegisterFlagsWithPrefix(prefix, f) -} - -// RegisterFlagsWithPrefix registers the flags for s3 storage with the provided prefix. -func (cfg *TLSConfig) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { - f.StringVar(&cfg.CAPath, prefix+"s3.http.tls-ca-path", "", "Path to the CA certificates to validate server certificate against. If not set, the host's root CA certificates are used.") - f.StringVar(&cfg.CertPath, prefix+"s3.http.tls-cert-path", "", "Path to the client certificate, which will be used for authenticating with the server. Also requires the key path to be configured.") - f.StringVar(&cfg.KeyPath, prefix+"s3.http.tls-key-path", "", "Path to the key for the client certificate. Also requires the client certificate to be configured.") - f.StringVar(&cfg.ServerName, prefix+"s3.http.tls-server-name", "", "Override the expected name on the server certificate.") -} - // Config holds the config options for an S3 backend type Config struct { Endpoint string `yaml:"endpoint"` @@ -121,7 +74,7 @@ type Config struct { MaxRetries int `yaml:"max_retries"` SSE SSEConfig `yaml:"sse"` - HTTP HTTPConfig `yaml:"http"` + HTTP http.Config `yaml:"http"` TraceConfig TraceConfig `yaml:"trace"` } @@ -149,7 +102,7 @@ func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { f.StringVar(&cfg.STSEndpoint, prefix+"s3.sts-endpoint", "", "Accessing S3 resources using temporary, secure credentials provided by AWS Security Token Service.") f.IntVar(&cfg.MaxRetries, prefix+"s3.max-retries", 10, "The maximum number of retries for S3 requests that are retryable. Default is 10, set this to 1 to disable retries.") cfg.SSE.RegisterFlagsWithPrefix(prefix+"s3.sse.", f) - cfg.HTTP.RegisterFlagsWithPrefix(prefix, f) + cfg.HTTP.RegisterFlagsWithPrefix(prefix+"s3.", f) cfg.TraceConfig.RegisterFlagsWithPrefix(prefix+"s3.trace.", f) } diff --git a/pkg/storage/bucket/swift/bucket_client.go b/pkg/storage/bucket/swift/bucket_client.go index 93ecdee9da7f7..5f502f2fd1e52 100644 --- a/pkg/storage/bucket/swift/bucket_client.go +++ b/pkg/storage/bucket/swift/bucket_client.go @@ -13,31 +13,49 @@ import ( // NewBucketClient creates a new Swift bucket client func NewBucketClient(cfg Config, _ string, logger log.Logger, wrapper func(http.RoundTripper) http.RoundTripper) (objstore.Bucket, error) { bucketConfig := swift.Config{ - AuthVersion: cfg.AuthVersion, - AuthUrl: cfg.AuthURL, - Username: cfg.Username, - UserDomainName: cfg.UserDomainName, - UserDomainID: cfg.UserDomainID, - UserId: cfg.UserID, - Password: cfg.Password, - DomainId: cfg.DomainID, - DomainName: cfg.DomainName, - ProjectID: cfg.ProjectID, - ProjectName: cfg.ProjectName, - ProjectDomainID: cfg.ProjectDomainID, - ProjectDomainName: cfg.ProjectDomainName, - RegionName: cfg.RegionName, - ContainerName: cfg.ContainerName, - Retries: cfg.MaxRetries, - ConnectTimeout: model.Duration(cfg.ConnectTimeout), - Timeout: model.Duration(cfg.RequestTimeout), + ApplicationCredentialID: cfg.ApplicationCredentialID, + ApplicationCredentialName: cfg.ApplicationCredentialName, + ApplicationCredentialSecret: cfg.ApplicationCredentialSecret.String(), + AuthVersion: cfg.AuthVersion, + AuthUrl: cfg.AuthURL, + Username: cfg.Username, + UserDomainName: cfg.UserDomainName, + UserDomainID: cfg.UserDomainID, + UserId: cfg.UserID, + Password: cfg.Password.String(), + DomainId: cfg.DomainID, + DomainName: cfg.DomainName, + ProjectID: cfg.ProjectID, + ProjectName: cfg.ProjectName, + ProjectDomainID: cfg.ProjectDomainID, + ProjectDomainName: cfg.ProjectDomainName, + RegionName: cfg.RegionName, + ContainerName: cfg.ContainerName, + Retries: cfg.MaxRetries, + ConnectTimeout: model.Duration(cfg.ConnectTimeout), + Timeout: model.Duration(cfg.RequestTimeout), + HTTPConfig: exthttp.HTTPConfig{ + IdleConnTimeout: model.Duration(cfg.HTTP.IdleConnTimeout), + ResponseHeaderTimeout: model.Duration(cfg.HTTP.ResponseHeaderTimeout), + InsecureSkipVerify: cfg.HTTP.InsecureSkipVerify, + TLSHandshakeTimeout: model.Duration(cfg.HTTP.TLSHandshakeTimeout), + ExpectContinueTimeout: model.Duration(cfg.HTTP.ExpectContinueTimeout), + MaxIdleConns: cfg.HTTP.MaxIdleConns, + MaxIdleConnsPerHost: cfg.HTTP.MaxIdleConnsPerHost, + MaxConnsPerHost: cfg.HTTP.MaxConnsPerHost, + Transport: cfg.HTTP.Transport, + TLSConfig: exthttp.TLSConfig{ + CAFile: cfg.HTTP.TLSConfig.CAPath, + CertFile: cfg.HTTP.TLSConfig.CertPath, + KeyFile: cfg.HTTP.TLSConfig.KeyPath, + ServerName: cfg.HTTP.TLSConfig.ServerName, + }, + }, // Hard-coded defaults. ChunkSize: swift.DefaultConfig.ChunkSize, UseDynamicLargeObjects: false, - HTTPConfig: exthttp.DefaultHTTPConfig, } - bucketConfig.HTTPConfig.Transport = cfg.Transport return swift.NewContainerFromConfig(logger, &bucketConfig, false, wrapper) } diff --git a/pkg/storage/bucket/swift/config.go b/pkg/storage/bucket/swift/config.go index 22717efcc8e59..521938739069b 100644 --- a/pkg/storage/bucket/swift/config.go +++ b/pkg/storage/bucket/swift/config.go @@ -2,34 +2,37 @@ package swift import ( "flag" - "net/http" "time" + + "github.com/grafana/dskit/flagext" + + "github.com/grafana/loki/v3/pkg/storage/bucket/http" ) // Config holds the config options for Swift backend type Config struct { - AuthVersion int `yaml:"auth_version"` - AuthURL string `yaml:"auth_url"` - Internal bool `yaml:"internal"` - Username string `yaml:"username"` - UserDomainName string `yaml:"user_domain_name"` - UserDomainID string `yaml:"user_domain_id"` - UserID string `yaml:"user_id"` - Password string `yaml:"password"` - DomainID string `yaml:"domain_id"` - DomainName string `yaml:"domain_name"` - ProjectID string `yaml:"project_id"` - ProjectName string `yaml:"project_name"` - ProjectDomainID string `yaml:"project_domain_id"` - ProjectDomainName string `yaml:"project_domain_name"` - RegionName string `yaml:"region_name"` - ContainerName string `yaml:"container_name"` - MaxRetries int `yaml:"max_retries"` - ConnectTimeout time.Duration `yaml:"connect_timeout"` - RequestTimeout time.Duration `yaml:"request_timeout"` - - // Allow upstream callers to inject a round tripper - Transport http.RoundTripper `yaml:"-"` + ApplicationCredentialID string `yaml:"application_credential_id"` + ApplicationCredentialName string `yaml:"application_credential_name"` + ApplicationCredentialSecret flagext.Secret `yaml:"application_credential_secret"` + AuthVersion int `yaml:"auth_version"` + AuthURL string `yaml:"auth_url"` + Username string `yaml:"username"` + UserDomainName string `yaml:"user_domain_name"` + UserDomainID string `yaml:"user_domain_id"` + UserID string `yaml:"user_id"` + Password flagext.Secret `yaml:"password"` + DomainID string `yaml:"domain_id"` + DomainName string `yaml:"domain_name"` + ProjectID string `yaml:"project_id"` + ProjectName string `yaml:"project_name"` + ProjectDomainID string `yaml:"project_domain_id"` + ProjectDomainName string `yaml:"project_domain_name"` + RegionName string `yaml:"region_name"` + ContainerName string `yaml:"container_name"` + MaxRetries int `yaml:"max_retries" category:"advanced"` + ConnectTimeout time.Duration `yaml:"connect_timeout" category:"advanced"` + RequestTimeout time.Duration `yaml:"request_timeout" category:"advanced"` + HTTP http.Config `yaml:"http"` } // RegisterFlags registers the flags for Swift storage @@ -39,14 +42,16 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) { // RegisterFlagsWithPrefix registers the flags for Swift storage with the provided prefix func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { + f.StringVar(&cfg.ApplicationCredentialID, prefix+"swift.application-credential-id", "", "OpenStack Swift application credential id") + f.StringVar(&cfg.ApplicationCredentialName, prefix+"swift.application-credential-name", "", "OpenStack Swift application credential name") + f.Var(&cfg.ApplicationCredentialSecret, prefix+"swift.application-credential-secret", "OpenStack Swift application credential secret") f.IntVar(&cfg.AuthVersion, prefix+"swift.auth-version", 0, "OpenStack Swift authentication API version. 0 to autodetect.") f.StringVar(&cfg.AuthURL, prefix+"swift.auth-url", "", "OpenStack Swift authentication URL") - f.BoolVar(&cfg.Internal, prefix+"swift.internal", false, "Set this to true to use the internal OpenStack Swift endpoint URL") f.StringVar(&cfg.Username, prefix+"swift.username", "", "OpenStack Swift username.") f.StringVar(&cfg.UserDomainName, prefix+"swift.user-domain-name", "", "OpenStack Swift user's domain name.") f.StringVar(&cfg.UserDomainID, prefix+"swift.user-domain-id", "", "OpenStack Swift user's domain ID.") f.StringVar(&cfg.UserID, prefix+"swift.user-id", "", "OpenStack Swift user ID.") - f.StringVar(&cfg.Password, prefix+"swift.password", "", "OpenStack Swift API key.") + f.Var(&cfg.Password, prefix+"swift.password", "OpenStack Swift API key.") f.StringVar(&cfg.DomainID, prefix+"swift.domain-id", "", "OpenStack Swift user's domain ID.") f.StringVar(&cfg.DomainName, prefix+"swift.domain-name", "", "OpenStack Swift user's domain name.") f.StringVar(&cfg.ProjectID, prefix+"swift.project-id", "", "OpenStack Swift project ID (v2,v3 auth only).") @@ -58,8 +63,5 @@ func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { f.IntVar(&cfg.MaxRetries, prefix+"swift.max-retries", 3, "Max retries on requests error.") f.DurationVar(&cfg.ConnectTimeout, prefix+"swift.connect-timeout", 10*time.Second, "Time after which a connection attempt is aborted.") f.DurationVar(&cfg.RequestTimeout, prefix+"swift.request-timeout", 5*time.Second, "Time after which an idle request is aborted. The timeout watchdog is reset each time some data is received, so the timeout triggers after X time no data is received on a request.") -} - -func (cfg *Config) Validate() error { - return nil + cfg.HTTP.RegisterFlagsWithPrefix(prefix+"swift.", f) } diff --git a/pkg/storage/chunk/client/openstack/swift_object_client.go b/pkg/storage/chunk/client/openstack/swift_object_client.go index 03721d3e16407..63de9458e77c1 100644 --- a/pkg/storage/chunk/client/openstack/swift_object_client.go +++ b/pkg/storage/chunk/client/openstack/swift_object_client.go @@ -3,27 +3,62 @@ package openstack import ( "bytes" "context" + "crypto/tls" + "crypto/x509" "flag" "fmt" "io" "net/http" + "os" "time" + "github.com/grafana/dskit/flagext" swift "github.com/ncw/swift/v2" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" - bucket_swift "github.com/grafana/loki/v3/pkg/storage/bucket/swift" "github.com/grafana/loki/v3/pkg/storage/chunk/client" "github.com/grafana/loki/v3/pkg/storage/chunk/client/hedging" "github.com/grafana/loki/v3/pkg/util/log" ) -var defaultTransport http.RoundTripper = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConnsPerHost: 200, - MaxIdleConns: 200, - ExpectContinueTimeout: 5 * time.Second, +// Config stores the http.Client configuration for the storage clients. +type HTTPConfig struct { + Transport http.RoundTripper `yaml:"-"` + TLSConfig TLSConfig `yaml:",inline"` +} + +// TLSConfig configures the options for TLS connections. +type TLSConfig struct { + CAPath string `yaml:"tls_ca_path" category:"advanced"` +} + +func defaultTransport(config HTTPConfig) (http.RoundTripper, error) { + if config.Transport != nil { + return config.Transport, nil + } + + tlsConfig := &tls.Config{} + if len(config.TLSConfig.CAPath) > 0 { + caPath := config.TLSConfig.CAPath + data, err := os.ReadFile(caPath) + if err != nil { + return nil, fmt.Errorf("unable to load specified CA cert %s: %s", caPath, err) + } + caCertPool := x509.NewCertPool() + if !caCertPool.AppendCertsFromPEM(data) { + return nil, fmt.Errorf("unable to use specified CA cert %s", caPath) + } + tlsConfig.RootCAs = caCertPool + } + + return &http.Transport{ + Proxy: http.ProxyFromEnvironment, + MaxIdleConns: 200, + MaxIdleConnsPerHost: 200, + ExpectContinueTimeout: 5 * time.Second, + TLSClientConfig: tlsConfig, + }, nil } type SwiftObjectClient struct { @@ -34,7 +69,26 @@ type SwiftObjectClient struct { // SwiftConfig is config for the Swift Chunk Client. type SwiftConfig struct { - bucket_swift.Config `yaml:",inline"` + AuthVersion int `yaml:"auth_version"` + AuthURL string `yaml:"auth_url"` + Internal bool `yaml:"internal"` + Username string `yaml:"username"` + UserDomainName string `yaml:"user_domain_name"` + UserDomainID string `yaml:"user_domain_id"` + UserID string `yaml:"user_id"` + Password flagext.Secret `yaml:"password"` + DomainID string `yaml:"domain_id"` + DomainName string `yaml:"domain_name"` + ProjectID string `yaml:"project_id"` + ProjectName string `yaml:"project_name"` + ProjectDomainID string `yaml:"project_domain_id"` + ProjectDomainName string `yaml:"project_domain_name"` + RegionName string `yaml:"region_name"` + ContainerName string `yaml:"container_name"` + MaxRetries int `yaml:"max_retries" category:"advanced"` + ConnectTimeout time.Duration `yaml:"connect_timeout" category:"advanced"` + RequestTimeout time.Duration `yaml:"request_timeout" category:"advanced"` + HTTP HTTPConfig `yaml:"http"` } // RegisterFlags registers flags. @@ -49,7 +103,26 @@ func (cfg *SwiftConfig) Validate() error { // RegisterFlagsWithPrefix registers flags with prefix. func (cfg *SwiftConfig) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { - cfg.Config.RegisterFlagsWithPrefix(prefix, f) + f.IntVar(&cfg.AuthVersion, prefix+"swift.auth-version", 0, "OpenStack Swift authentication API version. 0 to autodetect.") + f.StringVar(&cfg.AuthURL, prefix+"swift.auth-url", "", "OpenStack Swift authentication URL") + f.BoolVar(&cfg.Internal, prefix+"swift.internal", false, "Set this to true to use the internal OpenStack Swift endpoint URL") + f.StringVar(&cfg.Username, prefix+"swift.username", "", "OpenStack Swift username.") + f.StringVar(&cfg.UserDomainName, prefix+"swift.user-domain-name", "", "OpenStack Swift user's domain name.") + f.StringVar(&cfg.UserDomainID, prefix+"swift.user-domain-id", "", "OpenStack Swift user's domain ID.") + f.StringVar(&cfg.UserID, prefix+"swift.user-id", "", "OpenStack Swift user ID.") + f.Var(&cfg.Password, prefix+"swift.password", "OpenStack Swift API key.") + f.StringVar(&cfg.DomainID, prefix+"swift.domain-id", "", "OpenStack Swift user's domain ID.") + f.StringVar(&cfg.DomainName, prefix+"swift.domain-name", "", "OpenStack Swift user's domain name.") + f.StringVar(&cfg.ProjectID, prefix+"swift.project-id", "", "OpenStack Swift project ID (v2,v3 auth only).") + f.StringVar(&cfg.ProjectName, prefix+"swift.project-name", "", "OpenStack Swift project name (v2,v3 auth only).") + f.StringVar(&cfg.ProjectDomainID, prefix+"swift.project-domain-id", "", "ID of the OpenStack Swift project's domain (v3 auth only), only needed if it differs the from user domain.") + f.StringVar(&cfg.ProjectDomainName, prefix+"swift.project-domain-name", "", "Name of the OpenStack Swift project's domain (v3 auth only), only needed if it differs from the user domain.") + f.StringVar(&cfg.RegionName, prefix+"swift.region-name", "", "OpenStack Swift Region to use (v2,v3 auth only).") + f.StringVar(&cfg.ContainerName, prefix+"swift.container-name", "", "Name of the OpenStack Swift container to put chunks in.") + f.IntVar(&cfg.MaxRetries, prefix+"swift.max-retries", 3, "Max retries on requests error.") + f.DurationVar(&cfg.ConnectTimeout, prefix+"swift.connect-timeout", 10*time.Second, "Time after which a connection attempt is aborted.") + f.DurationVar(&cfg.RequestTimeout, prefix+"swift.request-timeout", 5*time.Second, "Time after which an idle request is aborted. The timeout watchdog is reset each time some data is received, so the timeout triggers after X time no data is received on a request.") + f.StringVar(&cfg.HTTP.TLSConfig.CAPath, prefix+"swift.http.tls-ca-path", "", "Path to the CA certificates to validate server certificate against. If not set, the host's root CA certificates are used.") } // NewSwiftObjectClient makes a new chunk.Client that writes chunks to OpenStack Swift. @@ -61,7 +134,7 @@ func NewSwiftObjectClient(cfg SwiftConfig, hedgingCfg hedging.Config) (*SwiftObj return nil, err } // Ensure the container is created, no error is returned if it already exists. - if err := c.ContainerCreate(context.Background(), cfg.Config.ContainerName, nil); err != nil { + if err := c.ContainerCreate(context.Background(), cfg.ContainerName, nil); err != nil { return nil, err } hedging, err := createConnection(cfg, hedgingCfg, true) @@ -76,32 +149,36 @@ func NewSwiftObjectClient(cfg SwiftConfig, hedgingCfg hedging.Config) (*SwiftObj } func createConnection(cfg SwiftConfig, hedgingCfg hedging.Config, hedging bool) (*swift.Connection, error) { - // Create a connection + defaultTransport, err := defaultTransport(cfg.HTTP) + if err != nil { + return nil, err + } + c := &swift.Connection{ - AuthVersion: cfg.Config.AuthVersion, - AuthUrl: cfg.Config.AuthURL, - Internal: cfg.Config.Internal, - ApiKey: cfg.Config.Password, - UserName: cfg.Config.Username, - UserId: cfg.Config.UserID, - Retries: cfg.Config.MaxRetries, - ConnectTimeout: cfg.Config.ConnectTimeout, - Timeout: cfg.Config.RequestTimeout, - TenantId: cfg.Config.ProjectID, - Tenant: cfg.Config.ProjectName, - TenantDomain: cfg.Config.ProjectDomainName, - TenantDomainId: cfg.Config.ProjectDomainID, - Domain: cfg.Config.DomainName, - DomainId: cfg.Config.DomainID, - Region: cfg.Config.RegionName, + AuthVersion: cfg.AuthVersion, + AuthUrl: cfg.AuthURL, + Internal: cfg.Internal, + ApiKey: cfg.Password.String(), + UserName: cfg.Username, + UserId: cfg.UserID, + Retries: cfg.MaxRetries, + ConnectTimeout: cfg.ConnectTimeout, + Timeout: cfg.RequestTimeout, + TenantId: cfg.ProjectID, + Tenant: cfg.ProjectName, + TenantDomain: cfg.ProjectDomainName, + TenantDomainId: cfg.ProjectDomainID, + Domain: cfg.DomainName, + DomainId: cfg.DomainID, + Region: cfg.RegionName, Transport: defaultTransport, } switch { - case cfg.Config.UserDomainName != "": - c.Domain = cfg.Config.UserDomainName - case cfg.Config.UserDomainID != "": - c.DomainId = cfg.Config.UserDomainID + case cfg.UserDomainName != "": + c.Domain = cfg.UserDomainName + case cfg.UserDomainID != "": + c.DomainId = cfg.UserDomainID } if hedging { var err error @@ -111,7 +188,8 @@ func createConnection(cfg SwiftConfig, hedgingCfg hedging.Config, hedging bool) } } - err := c.Authenticate(context.TODO()) + // Create a connection + err = c.Authenticate(context.TODO()) if err != nil { return nil, err } @@ -135,7 +213,7 @@ func (s *SwiftObjectClient) ObjectExists(ctx context.Context, objectKey string) } func (s *SwiftObjectClient) GetAttributes(ctx context.Context, objectKey string) (client.ObjectAttributes, error) { - info, _, err := s.hedgingConn.Object(ctx, s.cfg.Config.ContainerName, objectKey) + info, _, err := s.hedgingConn.Object(ctx, s.cfg.ContainerName, objectKey) if err != nil { return client.ObjectAttributes{}, nil } @@ -146,7 +224,7 @@ func (s *SwiftObjectClient) GetAttributes(ctx context.Context, objectKey string) // GetObject returns a reader and the size for the specified object key from the configured swift container. func (s *SwiftObjectClient) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, int64, error) { var buf bytes.Buffer - _, err := s.hedgingConn.ObjectGet(ctx, s.cfg.Config.ContainerName, objectKey, &buf, false, nil) + _, err := s.hedgingConn.ObjectGet(ctx, s.cfg.ContainerName, objectKey, &buf, false, nil) if err != nil { return nil, 0, err } @@ -160,7 +238,7 @@ func (s *SwiftObjectClient) GetObjectRange(ctx context.Context, objectKey string h := swift.Headers{ "Range": fmt.Sprintf("bytes=%d-%d", offset, offset+length-1), } - _, err := s.hedgingConn.ObjectGet(ctx, s.cfg.Config.ContainerName, objectKey, &buf, false, h) + _, err := s.hedgingConn.ObjectGet(ctx, s.cfg.ContainerName, objectKey, &buf, false, h) if err != nil { return nil, err } @@ -170,7 +248,7 @@ func (s *SwiftObjectClient) GetObjectRange(ctx context.Context, objectKey string // PutObject puts the specified bytes into the configured Swift container at the provided key func (s *SwiftObjectClient) PutObject(ctx context.Context, objectKey string, object io.Reader) error { - _, err := s.conn.ObjectPut(ctx, s.cfg.Config.ContainerName, objectKey, object, false, "", "", nil) + _, err := s.conn.ObjectPut(ctx, s.cfg.ContainerName, objectKey, object, false, "", "", nil) return err } @@ -187,7 +265,7 @@ func (s *SwiftObjectClient) List(ctx context.Context, prefix, delimiter string) opts.Delimiter = []rune(delimiter)[0] } - objs, err := s.conn.ObjectsAll(ctx, s.cfg.Config.ContainerName, opts) + objs, err := s.conn.ObjectsAll(ctx, s.cfg.ContainerName, opts) if err != nil { return nil, nil, err } @@ -214,7 +292,7 @@ func (s *SwiftObjectClient) List(ctx context.Context, prefix, delimiter string) // DeleteObject deletes the specified object key from the configured Swift container. func (s *SwiftObjectClient) DeleteObject(ctx context.Context, objectKey string) error { - return s.conn.ObjectDelete(ctx, s.cfg.Config.ContainerName, objectKey) + return s.conn.ObjectDelete(ctx, s.cfg.ContainerName, objectKey) } // IsObjectNotFoundErr returns true if error means that object is not found. Relevant to GetObject and DeleteObject operations. @@ -223,4 +301,8 @@ func (s *SwiftObjectClient) IsObjectNotFoundErr(err error) bool { } // TODO(dannyk): implement for client -func (s *SwiftObjectClient) IsRetryableErr(error) bool { return false } +func IsRetryableErr(error) bool { return false } + +func (s *SwiftObjectClient) IsRetryableErr(err error) bool { + return IsRetryableErr(err) +} diff --git a/pkg/storage/chunk/client/openstack/swift_object_client_test.go b/pkg/storage/chunk/client/openstack/swift_object_client_test.go index efcd2807fdc90..6f970102c1f56 100644 --- a/pkg/storage/chunk/client/openstack/swift_object_client_test.go +++ b/pkg/storage/chunk/client/openstack/swift_object_client_test.go @@ -10,7 +10,8 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/atomic" - "github.com/grafana/loki/v3/pkg/storage/bucket/swift" + "github.com/grafana/dskit/flagext" + "github.com/grafana/loki/v3/pkg/storage/chunk/client/hedging" ) @@ -61,7 +62,7 @@ func Test_Hedging(t *testing.T) { t.Run(tc.name, func(t *testing.T) { count := atomic.NewInt32(0) // hijack the transport to count the number of calls - defaultTransport = RoundTripperFunc(func(req *http.Request) (*http.Response, error) { + transportCounter := RoundTripperFunc(func(req *http.Request) (*http.Response, error) { // fake auth if req.Header.Get("X-Auth-Key") == "passwd" { return &http.Response{ @@ -89,13 +90,14 @@ func Test_Hedging(t *testing.T) { }) c, err := NewSwiftObjectClient(SwiftConfig{ - Config: swift.Config{ - MaxRetries: 1, - ContainerName: "foo", - AuthVersion: 1, - Password: "passwd", - ConnectTimeout: 10 * time.Second, - RequestTimeout: 10 * time.Second, + MaxRetries: 1, + ContainerName: "foo", + AuthVersion: 1, + Password: flagext.SecretWithValue("passwd"), + ConnectTimeout: 10 * time.Second, + RequestTimeout: 10 * time.Second, + HTTP: HTTPConfig{ + Transport: transportCounter, }, }, hedging.Config{ At: tc.hedgeAt,
feat
Add objstore support for Swift using thanos.io/objstore (#11672)
60231c67a5a30ae5c7c23d5a651c09ac15cfcb69
2025-03-04 15:52:49
renovate[bot]
chore(deps): update fluent/fluent-bit docker tag to v3.2.8 (main) (#16535)
false
diff --git a/clients/cmd/fluent-bit/Dockerfile b/clients/cmd/fluent-bit/Dockerfile index 4e7692b9f585f..dbd22d59ca37e 100644 --- a/clients/cmd/fluent-bit/Dockerfile +++ b/clients/cmd/fluent-bit/Dockerfile @@ -14,7 +14,7 @@ RUN go build \ -o clients/cmd/fluent-bit/out_grafana_loki.so \ /src/clients/cmd/fluent-bit -FROM fluent/fluent-bit:3.2.7@sha256:bfce64b4b2027dfb3819dce82da776ff439e2e4197359e7aa18ec5b3c478c651 +FROM fluent/fluent-bit:3.2.8@sha256:961c6b687c45c7fd0282b96de1ec1e6e68a44aa99242fbf07b0a592bccf98ae7 COPY --from=builder /src/clients/cmd/fluent-bit/out_grafana_loki.so /fluent-bit/bin COPY clients/cmd/fluent-bit/fluent-bit.conf /fluent-bit/etc/fluent-bit.conf
chore
update fluent/fluent-bit docker tag to v3.2.8 (main) (#16535)
4d18a5b006b9fc494c559855891c6483b84ac0f4
2023-07-19 20:06:12
Kaviraj Kanagaraj
loki: Add `CODEOWNERS` file (#9961)
false
diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000000..0baa10ac5ad92 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,8 @@ +# Default owners for everything in the repo, unless a later match takes precedence. +* @grafana/loki-team + +# Documentation. +/docs/ @grafana/docs-logs @grafana/loki-team + +# No owners - allows sub-maintainers to merge changes. +CHANGELOG.md
loki
Add `CODEOWNERS` file (#9961)
a1efafdad22f18c960f6a3bc273072f24f988121
2024-07-03 16:03:55
benclive
perf: Limit tokens per pattern to 128 (#13376)
false
diff --git a/pkg/pattern/drain/drain_test.go b/pkg/pattern/drain/drain_test.go index 0f9313391c1eb..16e2841e794ea 100644 --- a/pkg/pattern/drain/drain_test.go +++ b/pkg/pattern/drain/drain_test.go @@ -44,7 +44,7 @@ func TestDrain_TrainExtractsPatterns(t *testing.T) { `ts=2024-04-16T15:10:<_>.<_> caller=filetargetmanager.go:181 level=info component=logs logs_config=default msg="received file watcher event" name=/var/log/pods/<_><_><_>/<_><_><_>.<_> op=CREATE`, `ts=2024-04-16T15:10:<_>.<_> caller=filetargetmanager.go:181 level=info component=logs logs_config=default msg="received file watcher event" name=/var/log/pods/<_><_><_>/<_><_><_>.<_>.<_> op=CREATE`, `ts=2024-04-16T15:10:<_>.<_> caller=filetargetmanager.go:181 level=info component=logs logs_config=default msg="received file watcher event" name=/var/log/pods/hosted-grafana_.<_>/<_>/0.log.<_>.<_> op=CREATE`, - `ts=2024-04-16T15:10:<_>.<_> caller=filetargetmanager.go:<_> level=info component=logs logs_config=default msg="<_> target" key="/var/log/pods/*<_>/<_>/*.log:{app=\"grafana\", conprof=\"true\", container=\"<_>\", instanceId=\"<_>\", job=\"hosted-grafana/grafana\", name=\"grafana\", namespace=\"hosted-grafana\", org=\"<_>\", plan=\"free\", pod=\"<_>\", pod_template_hash=\"<_>\", resource_version=\"<_>\", slug=\"<_>\", stackId=\"<_>\"}"`, + `ts=2024-04-16T15:10:<_>.<_> caller=filetargetmanager.go:<_> level=info component=logs logs_config=default msg="<_> target" key="/var/log/pods/*<_>/<_>/*.log:{app=\"grafana\", conprof=\"true\", container=\"<_>\", instanceId=\"<_>\", job=\"hosted-grafana/grafana\", name=\"grafana\", namespace=\"hosted-grafana\", org=\"<_>\", plan=\"free\", pod=<_>`, `ts=2024-04-16T15:10:<_>.<_> caller=log.go:168 component=logs logs_config=default level=info msg="Re-opening moved/deleted file /var/log/pods/<_>/<_>/<_>.log ..."`, `ts=2024-04-16T15:10:<_>.<_> caller=log.go:168 component=logs logs_config=default level=info msg="Re-opening moved/deleted file /var/log/pods/hosted-grafana_.<_>/<_>/0.log ..."`, `ts=2024-04-16T15:10:<_>.<_> caller=log.go:168 component=logs logs_config=default level=info msg="Seeked /var/log/pods/<_>/<_>/0.log - &{Offset:0 Whence:0}"`, @@ -118,12 +118,12 @@ func TestDrain_TrainExtractsPatterns(t *testing.T) { `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"<_>\" with CreateContainerConfigError: \"secret \\\"<_>\\\" not found\"" pod="<_>/<_>" podUID="<_>"`, `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"<_>\" with ImagePullBackOff: \"Back-off pulling image \\\"us.gcr.io/hosted-grafana/<_>:<_>.<_>.<_>\\\"\"" pod="<_>/<_>" podUID="<_>"`, `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"<_>\" with ImagePullBackOff: \"Back-off pulling image \\\"us.gcr.io/kubernetes-dev/<_>:<_>\\\"\"" pod="<_>/<_>" podUID="<_>"`, - `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"grafana\" with ErrImagePull: \"[rpc error: code = NotFound desc = failed to pull and unpack image \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": failed to resolve reference \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>: not found, failed to pull and unpack image \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": failed to resolve reference \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": unexpected status from HEAD request to https://us.gcr.io/v2/hosted-grafana/hosted-grafana-pro/manifests/<_>.1.<_>: 403 Forbidden]\"" pod="hosted-grafana/<_>" podUID="<_>"`, + `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"grafana\" with ErrImagePull: \"[rpc error: code = NotFound desc = failed to pull and unpack image \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": failed to resolve reference \\\"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\\\": us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>: not <_>`, `E0507 11:59:<_>.<_> <_> pod_workers.go:1300] "Error syncing pod, skipping" err="failed to \"StartContainer\" for \"pdc\" with ErrImageNeverPull: \"Container image \\\"us.gcr.io/hosted-grafana/pdc:0.1.415\\\" is not present with pull policy of Never\"" pod="pdc/<_>" podUID="<_>"`, `E0507 11:59:<_>.<_> <_> prober.go:104] "Probe errored" err="rpc error: code = NotFound desc = failed to exec in container: failed to load task: no running task found: task <_> not found: not found" probeType="Readiness" pod="hosted-grafana/<_>" podUID="<_>" containerName="grafana"`, `E0507 11:59:<_>.<_> <_> prober.go:239] "Unable to write all bytes from execInContainer" err="short write" expectedBytes=<_> actualBytes=10240`, `E0507 11:59:<_>.<_> <_> remote_image.go:180] "PullImage from image service failed" err="rpc error: code = NotFound desc = failed to pull and unpack image \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": failed to resolve reference \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>: not found" image="us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>"`, - `E0507 11:59:<_>.<_> <_> remote_image.go:180] "PullImage from image service failed" err="rpc error: code = Unknown desc = failed to pull and unpack image \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": failed to resolve reference \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": unexpected status from HEAD request to https://us.gcr.io/v2/hosted-grafana/hosted-grafana-pro/manifests/<_>.1.<_>: 403 Forbidden" image="us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>"`, + `E0507 11:59:<_>.<_> <_> remote_image.go:180] "PullImage from image service failed" err="rpc error: code = Unknown desc = failed to pull and unpack image \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": failed to resolve reference \"us.gcr.io/hosted-grafana/hosted-grafana-pro:<_>.1.<_>\": unexpected status from HEAD request to https://us.gcr.io/v2/hosted-grafana/hosted-grafana-pro/manifests/<_>.1.<_>: 403 Forbidden" image="us.gcr.io/hosted-grafana/<_>`, `E0507 11:59:<_>.<_> <_> remote_runtime.go:432] "ContainerStatus from runtime service failed" err="rpc error: code = NotFound desc = an error occurred when try to find container \"<_>\": not found" containerID="<_>"`, `E0507 11:59:<_>.<_> <_> remote_runtime.go:496] "ExecSync cmd from runtime service failed" err="rpc error: code = NotFound desc = failed to exec in container: failed to load task: no running task found: task <_> not found: not found" containerID="<_>" cmd=["/bin/hgrun","check"]`, `I0507 11:59:31.815514 2791 azure_credentials.go:220] image(us.gcr.io/hosted-grafana/hosted-grafana-pro) is not from ACR, return empty authentication`, @@ -311,10 +311,9 @@ func TestDrain_TrainExtractsPatterns(t *testing.T) { `2024-05-08 15:23:56.<_> [DEBUG][76] felix/route_table.go 686: Reconcile against kernel programming ifaceName="<_>" ifaceRegex="^azv.*" ipVersion=0x4 tableIndex=0`, `2024-05-08 15:23:56.<_> [DEBUG][76] felix/route_table.go 880: Processing route: 254 <_> 10.68.10.<_>/32 ifaceName="<_>" ifaceRegex="^azv.*" ipVersion=0x4 tableIndex=0`, `2024-05-08 15:23:56.<_> [DEBUG][76] felix/route_table.go 915: Route is correct dest=10.68.10.<_>/32 ifaceName="<_>" ifaceRegex="^azv.*" ipVersion=0x4 tableIndex=0`, - `2024-05-08 15:23:57.942 [WARNING][56] felix/table.go 654: Detected out-of-sync inserts, marking for resync actualRuleIDs=[]string{"", "", "", "", "", "", "", "", "", "", "", "", "tVnHkvAo15HuiPy0", "", ""} chainName="OUTPUT" expectedRuleIDs=[]string{"tVnHkvAo15HuiPy0", "", "", "", "", "", "", "", "", "", "", "", "", "", ""} ipVersion=0x4 table="raw"`, `2024-05-08 15:23:57.942 [WARNING][56] felix/table.go 654: Detected out-of-sync inserts, marking for resync actualRuleIDs=[]string{"", "", "", "", "6gwbT8clXdHdC1b1"} chainName="PREROUTING" expectedRuleIDs=[]string{"6gwbT8clXdHdC1b1", "", "", "", ""} ipVersion=0x4 table="raw"`, - `2024-05-08 15:23:57.969 [WARNING][56] felix/table.go 654: Detected out-of-sync inserts, marking for resync actualRuleIDs=[]string{"", "", "", "", "Cz_u1IQiXIMmKD4c", "", "", "", "", "", "", "", "", "", "", "", ""} chainName="INPUT" expectedRuleIDs=[]string{"Cz_u1IQiXIMmKD4c", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""} ipVersion=0x4 table="filter"`, `2024-05-08 15:23:57.969 [WARNING][56] felix/table.go 654: Detected out-of-sync inserts, marking for resync actualRuleIDs=[]string{"", "", "", "", "tVnHkvAo15HuiPy0", "", "", "", "", ""} chainName="OUTPUT" expectedRuleIDs=[]string{"tVnHkvAo15HuiPy0", "", "", "", "", "", "", "", "", ""} ipVersion=0x4 table="filter"`, + `2024-05-08 15:23:57.<_> [WARNING][56] felix/table.go 654: Detected out-of-sync inserts, marking for resync actualRuleIDs=[]string{"", "", "", "", "<_><_><_> "<_><_> "<_><_> "<_><_> "<_><_> "<_><_> "<_><_> "<_><_> <_>", "", ""<_> <_><_><_> <_>"<_> <_><_><_><_><_> <_><_><_><_><_><_><_><_>", "", "", "", "", "", "", "", "", ""<_>`, `2024-05-08 15:23:58.169 [INFO][2333] felix/summary.go 100: Summarising 35 dataplane reconciliation loops over 1m2s: avg=12ms longest=46ms (resync-filter-v4,resync-filter-v6,resync-mangle-v4,resync-mangle-v6,update-filter-v4,update-filter-v6)`, `2024-05-08 15:23:58.566 [DEBUG][3576126] felix/int_dataplane.go 957: Examining link for MTU calculation mtu=1500 name="eth0"`, `2024-05-08 15:23:58.680 [DEBUG][216945] felix/int_dataplane.go 1785: Reschedule kick received`, diff --git a/pkg/pattern/drain/line_tokenizer.go b/pkg/pattern/drain/line_tokenizer.go index 89bf34a5569b5..9a366edc6fe89 100644 --- a/pkg/pattern/drain/line_tokenizer.go +++ b/pkg/pattern/drain/line_tokenizer.go @@ -38,39 +38,36 @@ func newPunctuationTokenizer() *punctuationTokenizer { } func (p *punctuationTokenizer) Tokenize(line string) ([]string, interface{}) { - tokens := make([]string, len(line)) // Maximum size is every character is punctuation - spacesAfter := make([]int, strings.Count(line, " ")) // Could be a bitmap, but it's not worth it for a few bytes. + tokens := make([]string, 0, 128) + spacesAfter := make([]int, 0, 64) start := 0 - nextTokenIdx := 0 - nextSpaceIdx := 0 for i, char := range line { + if len(tokens) >= cap(tokens)-1 { + break + } if unicode.IsLetter(char) || unicode.IsNumber(char) || char < 128 && p.excludeDelimiters[char] != 0 { continue } included := char < 128 && p.includeDelimiters[char] != 0 if char == ' ' || included || unicode.IsPunct(char) { if i > start { - tokens[nextTokenIdx] = line[start:i] - nextTokenIdx++ + tokens = append(tokens, line[start:i]) } if char == ' ' { - spacesAfter[nextSpaceIdx] = nextTokenIdx - 1 - nextSpaceIdx++ + spacesAfter = append(spacesAfter, len(tokens)-1) } else { - tokens[nextTokenIdx] = line[i : i+1] - nextTokenIdx++ + tokens = append(tokens, line[i:i+1]) } start = i + 1 } } if start < len(line) { - tokens[nextTokenIdx] = line[start:] - nextTokenIdx++ + tokens = append(tokens, line[start:]) } - return tokens[:nextTokenIdx], spacesAfter[:nextSpaceIdx] + return tokens, spacesAfter } func (p *punctuationTokenizer) Join(tokens []string, state interface{}) string { diff --git a/pkg/pattern/drain/line_tokenizer_test.go b/pkg/pattern/drain/line_tokenizer_test.go index 1eda1b51068a3..7aac061d28f38 100644 --- a/pkg/pattern/drain/line_tokenizer_test.go +++ b/pkg/pattern/drain/line_tokenizer_test.go @@ -1,6 +1,7 @@ package drain import ( + "strings" "testing" "github.com/stretchr/testify/require" @@ -88,6 +89,22 @@ var testCases = []TestCase{ typeSplitting: {"ts=", "2024-05-30T12:50:36.648377186Z", "caller=", "scheduler_processor.go:143", "level=", "warn", "msg=", "\"error", "contacting", "scheduler\"", "err=", "\"rpc", "error:", "code", "=", ``, "Unavailable", "desc", "=", ``, "connection", "error:", "desc", "=", ``, `\"error`, "reading", "server", "preface:", `EOF\""`, "addr=", "10.0.151.101:9095"}, }, }, + { + name: "Exactly 128 tokens are not combined", + line: strings.Repeat(`A `, 126) + "127 128", + want: map[string][]string{ + typePunctuation: append(strings.Split(strings.Repeat(`A `, 126), " ")[:126], "127", "128"), + typeSplitting: append(strings.Split(strings.Repeat(`A `, 126), " ")[:126], "127", "128"), + }, + }, + { + name: "More than 128 tokens combined suffix into one token", + line: strings.Repeat(`A `, 126) + "127 128 129", + want: map[string][]string{ + typePunctuation: append(strings.Split(strings.Repeat(`A `, 126), " ")[:126], "127", "128 129"), + typeSplitting: append(strings.Split(strings.Repeat(`A `, 126), " ")[:126], "127", "128", "129"), + }, + }, { name: "Only punctation", line: `!@£$%^&*()`,
perf
Limit tokens per pattern to 128 (#13376)
17bf32bc50598aaf620fda269511c6db64359dbd
2024-12-13 13:30:41
Ravishankar
fix: Return error 422 (Unprocessable Content) when push request does not contain any streams (#13706)
false
diff --git a/pkg/distributor/distributor.go b/pkg/distributor/distributor.go index f871336e26e9d..ac0dc19476208 100644 --- a/pkg/distributor/distributor.go +++ b/pkg/distributor/distributor.go @@ -446,7 +446,7 @@ func (d *Distributor) Push(ctx context.Context, req *logproto.PushRequest) (*log // Return early if request does not contain any streams if len(req.Streams) == 0 { - return &logproto.PushResponse{}, nil + return &logproto.PushResponse{}, httpgrpc.Errorf(http.StatusUnprocessableEntity, validation.MissingStreamsErrorMsg) } // First we flatten out the request into a list of samples. diff --git a/pkg/distributor/distributor_test.go b/pkg/distributor/distributor_test.go index 3f735b42371ac..b438780547ca0 100644 --- a/pkg/distributor/distributor_test.go +++ b/pkg/distributor/distributor_test.go @@ -643,6 +643,16 @@ func Test_DiscardEmptyStreamsAfterValidation(t *testing.T) { topVal := ingester.Peek() require.Nil(t, topVal) }) + + t.Run("it returns unprocessable entity error if the streams is empty", func(t *testing.T) { + limits, ingester := setup() + distributors, _ := prepare(t, 1, 5, limits, func(_ string) (ring_client.PoolClient, error) { return ingester, nil }) + + _, err := distributors[0].Push(ctx, makeWriteRequestWithLabels(1, 1, []string{})) + require.Equal(t, err, httpgrpc.Errorf(http.StatusUnprocessableEntity, validation.MissingStreamsErrorMsg)) + topVal := ingester.Peek() + require.Nil(t, topVal) + }) } func TestStreamShard(t *testing.T) { diff --git a/pkg/validation/validate.go b/pkg/validation/validate.go index f4731c439fe63..82a3343d442ad 100644 --- a/pkg/validation/validate.go +++ b/pkg/validation/validate.go @@ -11,7 +11,9 @@ import ( ) const ( - ReasonLabel = "reason" + ReasonLabel = "reason" + MissingStreamsErrorMsg = "error at least one valid stream is required for ingestion" + // InvalidLabels is a reason for discarding log lines which have labels that cannot be parsed. InvalidLabels = "invalid_labels" MissingLabels = "missing_labels"
fix
Return error 422 (Unprocessable Content) when push request does not contain any streams (#13706)
60dcee1b34e895f0b552b9302b9ad234a610e553
2024-03-15 16:26:41
Poyzan
fix: data race in seriesIterator, use atomic int (#12223)
false
diff --git a/pkg/iter/sample_iterator.go b/pkg/iter/sample_iterator.go index 632ed9106df15..ce943a8328c75 100644 --- a/pkg/iter/sample_iterator.go +++ b/pkg/iter/sample_iterator.go @@ -3,6 +3,7 @@ package iter import ( "container/heap" "context" + "go.uber.org/atomic" "io" "sync" @@ -521,7 +522,7 @@ func NewSampleQueryResponseIterator(resp *logproto.SampleQueryResponse) SampleIt } type seriesIterator struct { - i int + i *atomic.Int32 series logproto.Series } @@ -567,14 +568,14 @@ func NewMultiSeriesIterator(series []logproto.Series) SampleIterator { // NewSeriesIterator iterates over sample in a series. func NewSeriesIterator(series logproto.Series) SampleIterator { return &seriesIterator{ - i: -1, + i: atomic.NewInt32(-1), series: series, } } func (i *seriesIterator) Next() bool { - i.i++ - return i.i < len(i.series.Samples) + i.i.Inc() + return int(i.i.Load()) < len(i.series.Samples) } func (i *seriesIterator) Error() error { @@ -590,7 +591,7 @@ func (i *seriesIterator) StreamHash() uint64 { } func (i *seriesIterator) Sample() logproto.Sample { - return i.series.Samples[i.i] + return i.series.Samples[i.i.Load()] } func (i *seriesIterator) Close() error {
fix
data race in seriesIterator, use atomic int (#12223)
7ed63ea7f493dab6c81200ddb7a0e6f26dc41bec
2024-07-24 16:42:54
George Robinson
feat: remove mutexes from wal.SegmentWriter (#13641)
false
diff --git a/pkg/storage/wal/segment.go b/pkg/storage/wal/segment.go index 945d8ff17c7d6..57ad096fac309 100644 --- a/pkg/storage/wal/segment.go +++ b/pkg/storage/wal/segment.go @@ -30,7 +30,6 @@ var ( streamSegmentPool = sync.Pool{ New: func() interface{} { return &streamSegment{ - lock: &sync.Mutex{}, entries: make([]*logproto.Entry, 0, 4096), } }, @@ -47,18 +46,16 @@ type streamID struct { } type SegmentWriter struct { - metrics *SegmentMetrics - streams map[streamID]*streamSegment - buf1 encoding.Encbuf - outputSize atomic.Int64 - inputSize atomic.Int64 - idxWriter *index.Writer - consistencyMtx *sync.RWMutex - indexRef metastorepb.DataRef + metrics *SegmentMetrics + streams map[streamID]*streamSegment + buf1 encoding.Encbuf + outputSize atomic.Int64 + inputSize atomic.Int64 + idxWriter *index.Writer + indexRef metastorepb.DataRef } type streamSegment struct { - lock *sync.Mutex lbls labels.Labels entries []*logproto.Entry tenantID string @@ -86,24 +83,19 @@ func NewWalSegmentWriter(m *SegmentMetrics) (*SegmentWriter, error) { return nil, err } return &SegmentWriter{ - metrics: m, - streams: make(map[streamID]*streamSegment, 64), - buf1: encoding.EncWith(make([]byte, 0, 4)), - idxWriter: idxWriter, - inputSize: atomic.Int64{}, - consistencyMtx: &sync.RWMutex{}, + metrics: m, + streams: make(map[streamID]*streamSegment, 64), + buf1: encoding.EncWith(make([]byte, 0, 4)), + idxWriter: idxWriter, + inputSize: atomic.Int64{}, }, nil } func (b *SegmentWriter) getOrCreateStream(id streamID, lbls labels.Labels) *streamSegment { - b.consistencyMtx.RLock() s, ok := b.streams[id] - b.consistencyMtx.RUnlock() if ok { return s } - b.consistencyMtx.Lock() - defer b.consistencyMtx.Unlock() // Check another thread has not created it s, ok = b.streams[id] if ok { @@ -130,8 +122,6 @@ func (b *SegmentWriter) Append(tenantID, labelsString string, lbls labels.Labels id := streamID{labels: labelsString, tenant: tenantID} s := b.getOrCreateStream(id, lbls) - s.lock.Lock() - defer s.lock.Unlock() for i, e := range entries { if e.Timestamp.UnixNano() >= s.maxt { s.entries = append(s.entries, entries[i]) @@ -152,9 +142,6 @@ func (b *SegmentWriter) Append(tenantID, labelsString string, lbls labels.Labels // ReportMetrics for the writer. If called before WriteTo then the output size // histogram will observe 0. func (b *SegmentWriter) ReportMetrics() { - b.consistencyMtx.Lock() - defer b.consistencyMtx.Unlock() - b.metrics.streams.Observe(float64(len(b.streams))) tenants := make(map[string]struct{}, 64) for _, s := range b.streams { @@ -166,9 +153,6 @@ func (b *SegmentWriter) ReportMetrics() { } func (b *SegmentWriter) Meta(id string) *metastorepb.BlockMeta { - b.consistencyMtx.Lock() - defer b.consistencyMtx.Unlock() - var globalMinT, globalMaxT int64 tenants := make(map[string]*metastorepb.TenantStreams, 64) diff --git a/pkg/storage/wal/segment_test.go b/pkg/storage/wal/segment_test.go index 5852294329f91..34b8d78b2d586 100644 --- a/pkg/storage/wal/segment_test.go +++ b/pkg/storage/wal/segment_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "sort" - "sync" "testing" "time" @@ -132,163 +131,6 @@ func TestWalSegmentWriter_Append(t *testing.T) { } } -func BenchmarkConcurrentAppends(t *testing.B) { - type appendArgs struct { - tenant string - labels labels.Labels - entries []*push.Entry - } - - lbls := []labels.Labels{ - labels.FromStrings("container", "foo", "namespace", "dev"), - labels.FromStrings("container", "bar", "namespace", "staging"), - labels.FromStrings("container", "bar", "namespace", "prod"), - } - characters := "abcdefghijklmnopqrstuvwxyz" - tenants := []string{} - // 676 unique tenants (26^2) - for i := 0; i < len(characters); i++ { - for j := 0; j < len(characters); j++ { - tenants = append(tenants, string(characters[i])+string(characters[j])) - } - } - - workChan := make(chan *appendArgs) - var wg sync.WaitGroup - var w *SegmentWriter - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - for args := range workChan { - w.Append(args.tenant, args.labels.String(), args.labels, args.entries) - } - wg.Done() - }(i) - } - - t.ResetTimer() - for i := 0; i < t.N; i++ { - var err error - w, err = NewWalSegmentWriter(NewSegmentMetrics(nil)) - require.NoError(t, err) - - for _, lbl := range lbls { - for _, r := range tenants { - for i := 0; i < 10; i++ { - workChan <- &appendArgs{ - tenant: r, - labels: lbl, - entries: []*push.Entry{ - {Timestamp: time.Unix(0, int64(i)), Line: fmt.Sprintf("log line %d", i)}, - }, - } - } - } - } - } - close(workChan) - wg.Wait() -} - -func TestConcurrentAppends(t *testing.T) { - type appendArgs struct { - tenant string - labels labels.Labels - entries []*push.Entry - } - dst := bytes.NewBuffer(nil) - - w, err := NewWalSegmentWriter(NewSegmentMetrics(nil)) - require.NoError(t, err) - var wg sync.WaitGroup - workChan := make(chan *appendArgs, 100) - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - for args := range workChan { - w.Append(args.tenant, args.labels.String(), args.labels, args.entries) - } - wg.Done() - }(i) - } - - lbls := []labels.Labels{ - labels.FromStrings("container", "foo", "namespace", "dev"), - labels.FromStrings("container", "bar", "namespace", "staging"), - labels.FromStrings("container", "bar", "namespace", "prod"), - } - characters := "abcdefghijklmnopqrstuvwxyz" - tenants := []string{} - // 676 unique tenants (26^2) - for i := 0; i < len(characters); i++ { - for j := 0; j < len(characters); j++ { - for k := 0; k < len(characters); k++ { - tenants = append(tenants, string(characters[i])+string(characters[j])+string(characters[k])) - } - } - } - - msgsPerSeries := 10 - msgsGenerated := 0 - for _, r := range tenants { - for _, lbl := range lbls { - for i := 0; i < msgsPerSeries; i++ { - msgsGenerated++ - workChan <- &appendArgs{ - tenant: r, - labels: lbl, - entries: []*push.Entry{ - {Timestamp: time.Unix(0, int64(i)), Line: fmt.Sprintf("log line %d", i)}, - }, - } - } - } - } - close(workChan) - wg.Wait() - - n, err := w.WriteTo(dst) - require.NoError(t, err) - require.True(t, n > 0) - - r, err := NewReader(dst.Bytes()) - require.NoError(t, err) - - iter, err := r.Series(context.Background()) - require.NoError(t, err) - - var expectedSeries, actualSeries []string - - for _, tenant := range tenants { - for _, lbl := range lbls { - expectedSeries = append(expectedSeries, labels.NewBuilder(lbl).Set(tenantLabel, tenant).Labels().String()) - } - } - - msgsRead := 0 - for iter.Next() { - actualSeries = append(actualSeries, iter.At().String()) - chk, err := iter.ChunkReader(nil) - require.NoError(t, err) - // verify all lines - var i int - for chk.Next() { - ts, line := chk.At() - require.Equal(t, int64(i), ts) - require.Equal(t, fmt.Sprintf("log line %d", i), string(line)) - msgsRead++ - i++ - } - require.NoError(t, chk.Err()) - require.NoError(t, chk.Close()) - require.Equal(t, msgsPerSeries, i) - } - require.NoError(t, iter.Err()) - require.ElementsMatch(t, expectedSeries, actualSeries) - require.Equal(t, msgsGenerated, msgsRead) - t.Logf("Generated %d messages between %d tenants", msgsGenerated, len(tenants)) -} - func TestMultiTenantWrite(t *testing.T) { w, err := NewWalSegmentWriter(NewSegmentMetrics(nil)) require.NoError(t, err)
feat
remove mutexes from wal.SegmentWriter (#13641)
498f29a66b2dbfeff85454f22d0596d20066a635
2024-07-24 20:49:14
Michael Strucken
fix: remove trailing backtick in verify-config for Loki 3.0 (#13640)
false
diff --git a/docs/sources/setup/upgrade/_index.md b/docs/sources/setup/upgrade/_index.md index b98063ff30f4b..812544ce43a9c 100644 --- a/docs/sources/setup/upgrade/_index.md +++ b/docs/sources/setup/upgrade/_index.md @@ -69,7 +69,7 @@ If you would like to see if your existing configuration will work with Loki 3.0: 1. In an empty directory on your computer, copy you configuration into a file named `loki-config.yaml`. 1. Run this command from that directory: ```bash -docker run --rm -t -v "${PWD}":/config grafana/loki:3.0.0 -config.file=/config/loki-config.yaml -verify-config=true` +docker run --rm -t -v "${PWD}":/config grafana/loki:3.0.0 -config.file=/config/loki-config.yaml -verify-config=true ``` {{< admonition type="note" >}}
fix
remove trailing backtick in verify-config for Loki 3.0 (#13640)
9fe8b5709913ab763e15239cd77f002e2579ef79
2025-02-26 17:53:27
renovate[bot]
fix(deps): update module github.com/prometheus/prometheus to v0.302.1 (main) (#16475)
false
diff --git a/go.mod b/go.mod index 0e50b727a7d45..847ba6b6f058e 100644 --- a/go.mod +++ b/go.mod @@ -86,7 +86,7 @@ require ( github.com/prometheus/client_golang v1.21.0 github.com/prometheus/client_model v0.6.1 github.com/prometheus/common v0.62.0 - github.com/prometheus/prometheus v0.302.0 + github.com/prometheus/prometheus v0.302.1 github.com/redis/go-redis/v9 v9.7.1 github.com/segmentio/fasthash v1.0.3 github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c diff --git a/go.sum b/go.sum index 542711506f192..935f2db99db61 100644 --- a/go.sum +++ b/go.sum @@ -1057,8 +1057,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/prometheus/prometheus v0.302.0 h1:47EsaoBRroS2ekSyMSOPIjXwYnY/mxoFk0xt2dkFvfI= -github.com/prometheus/prometheus v0.302.0/go.mod h1:YcyCoTbUR/TM8rY3Aoeqr0AWTu/pu1Ehh+trpX3eRzg= +github.com/prometheus/prometheus v0.302.1 h1:xqVdrwrB4WNpdgJqxsz5loqFWNUZitsK8myqLuSZ6Ag= +github.com/prometheus/prometheus v0.302.1/go.mod h1:YcyCoTbUR/TM8rY3Aoeqr0AWTu/pu1Ehh+trpX3eRzg= github.com/prometheus/sigv4 v0.1.2 h1:R7570f8AoM5YnTUPFm3mjZH5q2k4D+I/phCWvZ4PXG8= github.com/prometheus/sigv4 v0.1.2/go.mod h1:GF9fwrvLgkQwDdQ5BXeV9XUSCH/IPNqzvAoaohfjqMU= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= diff --git a/tools/lambda-promtail/go.mod b/tools/lambda-promtail/go.mod index 607cdf09aa9ce..bad3ac33a82f8 100644 --- a/tools/lambda-promtail/go.mod +++ b/tools/lambda-promtail/go.mod @@ -151,4 +151,4 @@ require ( //replace k8s.io/client-go => k8s.io/client-go v0.21.0 // Using a fork of Prometheus with Mimir-specific changes. -replace github.com/prometheus/prometheus => github.com/prometheus/prometheus v0.302.0 +replace github.com/prometheus/prometheus => github.com/prometheus/prometheus v0.302.1 diff --git a/tools/lambda-promtail/go.sum b/tools/lambda-promtail/go.sum index 9432c41887568..e60b2e194465d 100644 --- a/tools/lambda-promtail/go.sum +++ b/tools/lambda-promtail/go.sum @@ -432,8 +432,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/prometheus/prometheus v0.302.0 h1:47EsaoBRroS2ekSyMSOPIjXwYnY/mxoFk0xt2dkFvfI= -github.com/prometheus/prometheus v0.302.0/go.mod h1:YcyCoTbUR/TM8rY3Aoeqr0AWTu/pu1Ehh+trpX3eRzg= +github.com/prometheus/prometheus v0.302.1 h1:xqVdrwrB4WNpdgJqxsz5loqFWNUZitsK8myqLuSZ6Ag= +github.com/prometheus/prometheus v0.302.1/go.mod h1:YcyCoTbUR/TM8rY3Aoeqr0AWTu/pu1Ehh+trpX3eRzg= github.com/prometheus/sigv4 v0.1.1 h1:UJxjOqVcXctZlwDjpUpZ2OiMWJdFijgSofwLzO1Xk0Q= github.com/prometheus/sigv4 v0.1.1/go.mod h1:RAmWVKqx0bwi0Qm4lrKMXFM0nhpesBcenfCtz9qRyH8= github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= diff --git a/vendor/github.com/prometheus/prometheus/config/config.go b/vendor/github.com/prometheus/prometheus/config/config.go index 73282ac429530..465affe082335 100644 --- a/vendor/github.com/prometheus/prometheus/config/config.go +++ b/vendor/github.com/prometheus/prometheus/config/config.go @@ -523,7 +523,7 @@ var ( ScrapeProtocolsHeaders = map[ScrapeProtocol]string{ PrometheusProto: "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", PrometheusText0_0_4: "text/plain;version=0.0.4", - PrometheusText1_0_0: "text/plain;version=1.0.0;escaping=allow-utf-8", + PrometheusText1_0_0: "text/plain;version=1.0.0", OpenMetricsText0_0_1: "application/openmetrics-text;version=0.0.1", OpenMetricsText1_0_0: "application/openmetrics-text;version=1.0.0", } diff --git a/vendor/modules.txt b/vendor/modules.txt index 8f0f18ad5fd81..cd6425f4e6b14 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1516,7 +1516,7 @@ github.com/prometheus/exporter-toolkit/web github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/prometheus/prometheus v0.302.0 +# github.com/prometheus/prometheus v0.302.1 ## explicit; go 1.22.7 github.com/prometheus/prometheus/config github.com/prometheus/prometheus/discovery
fix
update module github.com/prometheus/prometheus to v0.302.1 (main) (#16475)
74a97899dd97c95674a1fdb380c96daa64b680dc
2021-02-25 22:40:40
Ed Welch
loki: Fix parser hint for extracted labels which collide with stream labels (#3380)
false
diff --git a/pkg/logql/log/parser_hints.go b/pkg/logql/log/parser_hints.go index eb3264bbd31fd..55e85994106f0 100644 --- a/pkg/logql/log/parser_hints.go +++ b/pkg/logql/log/parser_hints.go @@ -63,6 +63,22 @@ func (p *parserHint) NoLabels() bool { // newParserHint creates a new parser hint using the list of labels that are seen and required in a query. func newParserHint(requiredLabelNames, groups []string, without, noLabels bool, metricLabelName string) *parserHint { + // If a parsed label collides with a stream label we add the `_extracted` suffix to it, however hints + // are used by the parsers before we know they will collide with a stream label and hence before the + // _extracted suffix is added. Therefore we must strip the _extracted suffix from any required labels + // that were parsed from somewhere in the query, say in a filter or an aggregation clause. + // Because it's possible for a valid json or logfmt key to already end with _extracted, we'll just + // leave the existing entry ending with _extracted but also add a version with the suffix removed. + extractedLabels := []string{} + for _, l := range requiredLabelNames { + if strings.HasSuffix(l, "_extracted") { + extractedLabels = append(extractedLabels, strings.TrimSuffix(l, "_extracted")) + } + } + if len(extractedLabels) > 0 { + requiredLabelNames = append(requiredLabelNames, extractedLabels...) + } + if len(groups) > 0 { requiredLabelNames = append(requiredLabelNames, groups...) } diff --git a/pkg/logql/log/parser_hints_test.go b/pkg/logql/log/parser_hints_test.go index 9cb9b928e27b7..11f3e97832783 100644 --- a/pkg/logql/log/parser_hints_test.go +++ b/pkg/logql/log/parser_hints_test.go @@ -15,6 +15,7 @@ var ( "remote_user": "foo", "upstream_addr": "10.0.0.1:80", "protocol": "HTTP/2.0", + "cluster": "us-east-west", "request": { "time": "30.001", "method": "POST", @@ -32,7 +33,7 @@ var ( ) func Test_ParserHints(t *testing.T) { - lbs := labels.Labels{{Name: "app", Value: "nginx"}} + lbs := labels.Labels{{Name: "app", Value: "nginx"}, {Name: "cluster", Value: "us-central-west"}} t.Parallel() for _, tt := range []struct { @@ -47,14 +48,14 @@ func Test_ParserHints(t *testing.T) { jsonLine, true, 1.0, - `{app="nginx", protocol="HTTP/2.0", remote_user="foo", request_host="foo.grafana.net", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_latency_seconds="30.001", response_status="204", upstream_addr="10.0.0.1:80"}`, + `{app="nginx", cluster="us-central-west", cluster_extracted="us-east-west", protocol="HTTP/2.0", remote_user="foo", request_host="foo.grafana.net", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_latency_seconds="30.001", response_status="204", upstream_addr="10.0.0.1:80"}`, }, { - `sum without (request_host,app) (rate({app="nginx"} | json | __error__="" | response_status = 204 [1m]))`, + `sum without (request_host,app,cluster) (rate({app="nginx"} | json | __error__="" | response_status = 204 [1m]))`, jsonLine, true, 1.0, - `{protocol="HTTP/2.0", remote_user="foo", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_latency_seconds="30.001", response_status="204", upstream_addr="10.0.0.1:80"}`, + `{cluster_extracted="us-east-west", protocol="HTTP/2.0", remote_user="foo", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_latency_seconds="30.001", response_status="204", upstream_addr="10.0.0.1:80"}`, }, { `sum by (request_host,app) (rate({app="nginx"} | json | __error__="" | response_status = 204 [1m]))`, @@ -103,14 +104,14 @@ func Test_ParserHints(t *testing.T) { jsonLine, true, 30.001, - `{app="nginx", protocol="HTTP/2.0", remote_user="foo", request_host="foo.grafana.net", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_status="204", upstream_addr="10.0.0.1:80"}`, + `{app="nginx", cluster="us-central-west", cluster_extracted="us-east-west", protocol="HTTP/2.0", remote_user="foo", request_host="foo.grafana.net", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_status="204", upstream_addr="10.0.0.1:80"}`, }, { - `sum without (request_host,app)(rate({app="nginx"} | json | response_status = 204 | unwrap response_latency_seconds [1m]))`, + `sum without (request_host,app,cluster)(rate({app="nginx"} | json | response_status = 204 | unwrap response_latency_seconds [1m]))`, jsonLine, true, 30.001, - `{protocol="HTTP/2.0", remote_user="foo", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_status="204", upstream_addr="10.0.0.1:80"}`, + `{cluster_extracted="us-east-west", protocol="HTTP/2.0", remote_user="foo", request_method="POST", request_size="101", request_time="30.001", request_uri="/rpc/v2/stage", response_status="204", upstream_addr="10.0.0.1:80"}`, }, { `sum(rate({app="nginx"} | logfmt | org_id=3677 | unwrap Ingester_TotalReached[1m]))`, @@ -131,10 +132,10 @@ func Test_ParserHints(t *testing.T) { logfmtLine, true, 15.0, - `{Ingester_TotalBatches="0", Ingester_TotalChunksMatched="0", app="nginx", caller="spanlogger.go:79", org_id="3677", traceID="2e5c7234b8640997", ts="2021-02-02T14:35:05.983992774Z"}`, + `{Ingester_TotalBatches="0", Ingester_TotalChunksMatched="0", app="nginx", caller="spanlogger.go:79", cluster="us-central-west", org_id="3677", traceID="2e5c7234b8640997", ts="2021-02-02T14:35:05.983992774Z"}`, }, { - `sum without (org_id,app)(rate({app="nginx"} | logfmt | org_id=3677 | unwrap Ingester_TotalReached[1m]))`, + `sum without (org_id,app,cluster)(rate({app="nginx"} | logfmt | org_id=3677 | unwrap Ingester_TotalReached[1m]))`, logfmtLine, true, 15.0, @@ -175,6 +176,13 @@ func Test_ParserHints(t *testing.T) { 1.0, `{}`, }, + { + `sum by (cluster_extracted)(count_over_time({app="nginx"} | json | cluster_extracted="us-east-west" [1m]))`, + jsonLine, + true, + 1.0, + `{cluster_extracted="us-east-west"}`, + }, } { tt := tt t.Run(tt.expr, func(t *testing.T) {
loki
Fix parser hint for extracted labels which collide with stream labels (#3380)
9981e9e40d4eda1a88d1aee0483cec1c098b92c7
2024-06-07 16:18:18
Sven Grossmann
fix(orFilters): fix multiple or filters would get wrong filtertype (#13169)
false
diff --git a/pkg/logql/syntax/ast.go b/pkg/logql/syntax/ast.go index 6e3f18b7cc8e6..e5e80b4d0c172 100644 --- a/pkg/logql/syntax/ast.go +++ b/pkg/logql/syntax/ast.go @@ -366,14 +366,6 @@ func newLineFilterExpr(ty log.LineMatchType, op, match string) *LineFilterExpr { func newOrLineFilter(left, right *LineFilterExpr) *LineFilterExpr { right.Ty = left.Ty - if left.Ty == log.LineMatchEqual || left.Ty == log.LineMatchRegexp || left.Ty == log.LineMatchPattern { - left.Or = right - right.IsOrChild = true - return left - } - - // !(left or right) == (!left and !right). - // NOTE: Consider, we have chain of "or", != "foo" or "bar" or "baz" // we parse from right to left, so first time left="bar", right="baz", and we don't know the actual `Ty` (equal: |=, notequal: !=, regex: |~, etc). So // it will have default (0, LineMatchEqual). @@ -385,6 +377,13 @@ func newOrLineFilter(left, right *LineFilterExpr) *LineFilterExpr { tmp = tmp.Or } + if left.Ty == log.LineMatchEqual || left.Ty == log.LineMatchRegexp || left.Ty == log.LineMatchPattern { + left.Or = right + right.IsOrChild = true + return left + } + + // !(left or right) == (!left and !right). return newNestedLineFilterExpr(left, right) } diff --git a/pkg/logql/syntax/ast_test.go b/pkg/logql/syntax/ast_test.go index 9090fc98b7558..d75ff2d0261b6 100644 --- a/pkg/logql/syntax/ast_test.go +++ b/pkg/logql/syntax/ast_test.go @@ -545,11 +545,18 @@ func Test_FilterMatcher(t *testing.T) { []linecheck{{"foo", false}, {"bar", true}, {"127.0.0.2", true}, {"127.0.0.1", false}}, }, { - `{app="foo"} |> "foo" or "bar"`, + `{app="foo"} |> "<_>foo<_>" or "<_>bar<_>"`, []*labels.Matcher{ mustNewMatcher(labels.MatchEqual, "app", "foo"), }, - []linecheck{{"foo", true}, {"bar", true}, {"none", false}}, + []linecheck{{"test foo test", true}, {"test bar test", true}, {"none", false}}, + }, + { + `{app="foo"} |> "<_>foo<_>" or "<_>bar<_>" or "<_>baz<_>"`, + []*labels.Matcher{ + mustNewMatcher(labels.MatchEqual, "app", "foo"), + }, + []linecheck{{"test foo test", true}, {"test bar test", true}, {"test baz test", true}, {"none", false}}, }, { `{app="foo"} !> "foo" or "bar"`, @@ -618,6 +625,18 @@ func TestOrLineFilterTypes(t *testing.T) { _ = newOrLineFilter(left, right) require.Equal(t, tt.ty, right.Ty) + require.Equal(t, tt.ty, left.Ty) + }) + + t.Run("right inherits left's type with multiple or filters", func(t *testing.T) { + f1 := &LineFilterExpr{LineFilter: LineFilter{Ty: tt.ty, Match: "something"}} + f2 := &LineFilterExpr{LineFilter: LineFilter{Ty: log.LineMatchEqual, Match: "something"}} + f3 := &LineFilterExpr{LineFilter: LineFilter{Ty: log.LineMatchEqual, Match: "something"}} + + _ = newOrLineFilter(f1, newOrLineFilter(f2, f3)) + require.Equal(t, tt.ty, f1.Ty) + require.Equal(t, tt.ty, f2.Ty) + require.Equal(t, tt.ty, f3.Ty) }) } } diff --git a/pkg/logql/syntax/parser_test.go b/pkg/logql/syntax/parser_test.go index f12309f2b24a5..4c2a85203938b 100644 --- a/pkg/logql/syntax/parser_test.go +++ b/pkg/logql/syntax/parser_test.go @@ -3173,6 +3173,66 @@ var ParseTestCases = []struct { }, }, }, + { + in: `{app="foo"} |= "foo" or "bar" or "baz"`, + exp: &PipelineExpr{ + Left: newMatcherExpr([]*labels.Matcher{mustNewMatcher(labels.MatchEqual, "app", "foo")}), + MultiStages: MultiStageExpr{ + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchEqual, + Match: "foo", + }, + Or: newOrLineFilter( + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchEqual, + Match: "bar", + }, + IsOrChild: true, + }, + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchEqual, + Match: "baz", + }, + IsOrChild: true, + }), + IsOrChild: false, + }, + }, + }, + }, + { + in: `{app="foo"} |> "foo" or "bar" or "baz"`, + exp: &PipelineExpr{ + Left: newMatcherExpr([]*labels.Matcher{mustNewMatcher(labels.MatchEqual, "app", "foo")}), + MultiStages: MultiStageExpr{ + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchPattern, + Match: "foo", + }, + Or: newOrLineFilter( + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchPattern, + Match: "bar", + }, + IsOrChild: true, + }, + &LineFilterExpr{ + LineFilter: LineFilter{ + Ty: log.LineMatchPattern, + Match: "baz", + }, + IsOrChild: true, + }), + IsOrChild: false, + }, + }, + }, + }, } func TestParse(t *testing.T) {
fix
fix multiple or filters would get wrong filtertype (#13169)
4bd5e617c3af2b60310e35795b5ac9f88b6a3a8e
2023-08-24 20:30:10
Kaviraj Kanagaraj
chore(schema-v13): Fix `periodConfig.Validate` for `v13` schema (#10336)
false
diff --git a/pkg/storage/config/schema_config.go b/pkg/storage/config/schema_config.go index 370a26f28d170..f035e79f06132 100644 --- a/pkg/storage/config/schema_config.go +++ b/pkg/storage/config/schema_config.go @@ -430,7 +430,7 @@ func (cfg PeriodConfig) validate() error { } switch v { - case 10, 11, 12: + case 10, 11, 12, 13: if cfg.RowShards == 0 { return fmt.Errorf("must have row_shards > 0 (current: %d) for schema (%s)", cfg.RowShards, cfg.Schema) } diff --git a/pkg/storage/config/schema_config_test.go b/pkg/storage/config/schema_config_test.go index 9412c5b5f073e..6d6cb78798a54 100644 --- a/pkg/storage/config/schema_config_test.go +++ b/pkg/storage/config/schema_config_test.go @@ -427,6 +427,15 @@ func TestPeriodConfig_Validate(t *testing.T) { ChunkTables: PeriodicTableConfig{Period: 0}, }, }, + { + desc: "v13", + in: PeriodConfig{ + Schema: "v13", + RowShards: 16, + IndexTables: PeriodicTableConfig{Period: 0}, + ChunkTables: PeriodicTableConfig{Period: 0}, + }, + }, } { t.Run(tc.desc, func(t *testing.T) { if tc.err == "" { @@ -555,6 +564,19 @@ func TestVersionAsInt(t *testing.T) { }, expected: int(12), }, + { + name: "v13", + schemaCfg: SchemaConfig{ + Configs: []PeriodConfig{ + { + From: DayTime{Time: 0}, + Schema: "v13", + RowShards: 16, + }, + }, + }, + expected: int(13), + }, } { t.Run(tc.name, func(t *testing.T) { version, err := tc.schemaCfg.Configs[0].VersionAsInt()
chore
Fix `periodConfig.Validate` for `v13` schema (#10336)
30d2b7640ff9d55901ba26208a37fa75220f165c
2023-08-11 15:34:30
Kaviraj Kanagaraj
codeowners: Add codeowners for loki operator (#10222)
false
diff --git a/CODEOWNERS b/CODEOWNERS index 0baa10ac5ad92..61f5c60b8a9ec 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -4,5 +4,8 @@ # Documentation. /docs/ @grafana/docs-logs @grafana/loki-team +# Loki operator +/operator/ @grafana/loki-team @periklis @xperimental + # No owners - allows sub-maintainers to merge changes. CHANGELOG.md
codeowners
Add codeowners for loki operator (#10222)
ff08d2fcc2b707a209dabc647933d826fc834543
2024-04-05 14:55:38
Christian Haudum
chore(blooms): Remove bloom gateway ring (#12484)
false
diff --git a/docs/sources/configure/_index.md b/docs/sources/configure/_index.md index 2837647cff97f..830aff30e9f5f 100644 --- a/docs/sources/configure/_index.md +++ b/docs/sources/configure/_index.md @@ -1986,102 +1986,6 @@ ring: The `bloom_gateway` block configures the Loki bloom gateway server, responsible for serving queries for filtering chunks based on filter expressions. ```yaml -# Defines the ring to be used by the bloom gateway servers and clients. In case -# this isn't configured, this block supports inheriting configuration from the -# common ring section. -ring: - kvstore: - # Backend storage to use for the ring. Supported values are: consul, etcd, - # inmemory, memberlist, multi. - # CLI flag: -bloom-gateway.ring.store - [store: <string> | default = "consul"] - - # The prefix for the keys in the store. Should end with a /. - # CLI flag: -bloom-gateway.ring.prefix - [prefix: <string> | default = "collectors/"] - - # Configuration for a Consul client. Only applies if the selected kvstore is - # consul. - # The CLI flags prefix for this block configuration is: bloom-gateway.ring - [consul: <consul>] - - # Configuration for an ETCD v3 client. Only applies if the selected kvstore - # is etcd. - # The CLI flags prefix for this block configuration is: bloom-gateway.ring - [etcd: <etcd>] - - multi: - # Primary backend storage used by multi-client. - # CLI flag: -bloom-gateway.ring.multi.primary - [primary: <string> | default = ""] - - # Secondary backend storage used by multi-client. - # CLI flag: -bloom-gateway.ring.multi.secondary - [secondary: <string> | default = ""] - - # Mirror writes to secondary store. - # CLI flag: -bloom-gateway.ring.multi.mirror-enabled - [mirror_enabled: <boolean> | default = false] - - # Timeout for storing value to secondary store. - # CLI flag: -bloom-gateway.ring.multi.mirror-timeout - [mirror_timeout: <duration> | default = 2s] - - # Period at which to heartbeat to the ring. 0 = disabled. - # CLI flag: -bloom-gateway.ring.heartbeat-period - [heartbeat_period: <duration> | default = 15s] - - # The heartbeat timeout after which compactors are considered unhealthy within - # the ring. 0 = never (timeout disabled). - # CLI flag: -bloom-gateway.ring.heartbeat-timeout - [heartbeat_timeout: <duration> | default = 1m] - - # File path where tokens are stored. If empty, tokens are not stored at - # shutdown and restored at startup. - # CLI flag: -bloom-gateway.ring.tokens-file-path - [tokens_file_path: <string> | default = ""] - - # True to enable zone-awareness and replicate blocks across different - # availability zones. - # CLI flag: -bloom-gateway.ring.zone-awareness-enabled - [zone_awareness_enabled: <boolean> | default = false] - - # Number of tokens to use in the ring. The bigger the number of tokens, the - # more fingerprint ranges the compactor will own, but the smaller these ranges - # will be. Bigger number of tokens means that more but smaller requests will - # be handled by each gateway. - # CLI flag: -bloom-gateway.ring.tokens - [num_tokens: <int> | default = 16] - - # Factor for data replication. - # CLI flag: -bloom-gateway.ring.replication-factor - [replication_factor: <int> | default = 3] - - # Instance ID to register in the ring. - # CLI flag: -bloom-gateway.ring.instance-id - [instance_id: <string> | default = "<hostname>"] - - # Name of network interface to read address from. - # CLI flag: -bloom-gateway.ring.instance-interface-names - [instance_interface_names: <list of strings> | default = [<private network interfaces>]] - - # Port to advertise in the ring (defaults to server.grpc-listen-port). - # CLI flag: -bloom-gateway.ring.instance-port - [instance_port: <int> | default = 0] - - # IP address to advertise in the ring. - # CLI flag: -bloom-gateway.ring.instance-addr - [instance_addr: <string> | default = ""] - - # The availability zone where this instance is running. Required if - # zone-awareness is enabled. - # CLI flag: -bloom-gateway.ring.instance-availability-zone - [instance_availability_zone: <string> | default = ""] - - # Enable using a IPv6 instance address. - # CLI flag: -bloom-gateway.ring.instance-enable-ipv6 - [instance_enable_ipv6: <boolean> | default = false] - # Flag to enable or disable the bloom gateway component globally. # CLI flag: -bloom-gateway.enabled [enabled: <boolean> | default = false] @@ -4149,7 +4053,6 @@ ring: Configuration for a Consul client. Only applies if the selected kvstore is `consul`. The supported CLI flags `<prefix>` used to reference this configuration block are: - `bloom-compactor.ring` -- `bloom-gateway.ring` - `common.storage.ring` - `compactor.ring` - `distributor.ring` @@ -4196,7 +4099,6 @@ Configuration for a Consul client. Only applies if the selected kvstore is `cons Configuration for an ETCD v3 client. Only applies if the selected kvstore is `etcd`. The supported CLI flags `<prefix>` used to reference this configuration block are: - `bloom-compactor.ring` -- `bloom-gateway.ring` - `common.storage.ring` - `compactor.ring` - `distributor.ring` diff --git a/pkg/bloomgateway/bloomgateway_test.go b/pkg/bloomgateway/bloomgateway_test.go index edaa2ea7f0c82..547652473ab90 100644 --- a/pkg/bloomgateway/bloomgateway_test.go +++ b/pkg/bloomgateway/bloomgateway_test.go @@ -10,9 +10,6 @@ import ( "github.com/go-kit/log" "github.com/grafana/dskit/flagext" - "github.com/grafana/dskit/kv" - "github.com/grafana/dskit/kv/consul" - "github.com/grafana/dskit/ring" "github.com/grafana/dskit/services" "github.com/grafana/dskit/user" "github.com/pkg/errors" @@ -29,7 +26,6 @@ import ( "github.com/grafana/loki/v3/pkg/storage/config" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" bloomshipperconfig "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper/config" - lokiring "github.com/grafana/loki/v3/pkg/util/ring" "github.com/grafana/loki/v3/pkg/validation" ) @@ -99,20 +95,8 @@ func TestBloomGateway_StartStopService(t *testing.T) { reg := prometheus.NewRegistry() t.Run("start and stop bloom gateway", func(t *testing.T) { - kvStore, closer := consul.NewInMemoryClient(ring.GetCodec(), logger, reg) - t.Cleanup(func() { - closer.Close() - }) - cfg := Config{ - Enabled: true, - Ring: lokiring.RingConfig{ - KVStore: kv.Config{ - Mock: kvStore, - }, - ReplicationFactor: 1, - NumTokens: 16, - }, + Enabled: true, WorkerConcurrency: 4, MaxOutstandingPerTenant: 1024, } @@ -137,22 +121,8 @@ func TestBloomGateway_FilterChunkRefs(t *testing.T) { tenantID := "test" logger := log.NewNopLogger() - reg := prometheus.NewRegistry() - - kvStore, closer := consul.NewInMemoryClient(ring.GetCodec(), logger, reg) - t.Cleanup(func() { - closer.Close() - }) - cfg := Config{ - Enabled: true, - Ring: lokiring.RingConfig{ - KVStore: kv.Config{ - Mock: kvStore, - }, - ReplicationFactor: 1, - NumTokens: 16, - }, + Enabled: true, WorkerConcurrency: 2, BlockQueryConcurrency: 2, MaxOutstandingPerTenant: 1024, diff --git a/pkg/bloomgateway/config.go b/pkg/bloomgateway/config.go index 9eaa6771e674f..397d8681ae49a 100644 --- a/pkg/bloomgateway/config.go +++ b/pkg/bloomgateway/config.go @@ -2,16 +2,10 @@ package bloomgateway import ( "flag" - - "github.com/grafana/loki/v3/pkg/util/ring" ) // Config configures the Bloom Gateway component. type Config struct { - // Ring configures the ring store used to save and retrieve the different Bloom Gateway instances. - // In case it isn't explicitly set, it follows the same behavior of the other rings (ex: using the common configuration - // section and the ingester configuration by default). - Ring ring.RingConfig `yaml:"ring,omitempty" doc:"description=Defines the ring to be used by the bloom gateway servers and clients. In case this isn't configured, this block supports inheriting configuration from the common ring section."` // Enabled is the global switch to configures whether Bloom Gateways should be used to filter chunks. Enabled bool `yaml:"enabled"` // Client configures the Bloom Gateway client @@ -38,13 +32,6 @@ func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) { // TODO(chaudum): Figure out what the better place is for registering flags // -bloom-gateway.client.* or -bloom-gateway-client.* cfg.Client.RegisterFlags(f) - - // Ring - skipFlags := []string{ - prefix + "ring.tokens", - } - cfg.Ring.RegisterFlagsWithPrefix(prefix, "collectors/", f, skipFlags...) - f.IntVar(&cfg.Ring.NumTokens, prefix+"ring.tokens", 16, "Number of tokens to use in the ring. The bigger the number of tokens, the more fingerprint ranges the compactor will own, but the smaller these ranges will be. Bigger number of tokens means that more but smaller requests will be handled by each gateway.") } type Limits interface { diff --git a/pkg/loki/config_wrapper.go b/pkg/loki/config_wrapper.go index 7353f797bdd1f..e74d055e5e406 100644 --- a/pkg/loki/config_wrapper.go +++ b/pkg/loki/config_wrapper.go @@ -182,7 +182,6 @@ func applyInstanceConfigs(r, defaults *ConfigWrapper) { func applyCommonReplicationFactor(r, defaults *ConfigWrapper) { if !reflect.DeepEqual(r.Common.ReplicationFactor, defaults.Common.ReplicationFactor) { r.IndexGateway.Ring.ReplicationFactor = r.Common.ReplicationFactor - r.BloomGateway.Ring.ReplicationFactor = r.Common.ReplicationFactor } } @@ -332,20 +331,6 @@ func applyConfigToRings(r, defaults *ConfigWrapper, rc lokiring.RingConfig, merg r.BloomCompactor.Ring.KVStore = rc.KVStore r.BloomCompactor.Ring.NumTokens = rc.NumTokens } - - // BloomGateway - if mergeWithExisting || reflect.DeepEqual(r.BloomGateway.Ring, defaults.BloomGateway.Ring) { - r.BloomGateway.Ring.HeartbeatTimeout = rc.HeartbeatTimeout - r.BloomGateway.Ring.HeartbeatPeriod = rc.HeartbeatPeriod - r.BloomGateway.Ring.InstancePort = rc.InstancePort - r.BloomGateway.Ring.InstanceAddr = rc.InstanceAddr - r.BloomGateway.Ring.InstanceID = rc.InstanceID - r.BloomGateway.Ring.InstanceInterfaceNames = rc.InstanceInterfaceNames - r.BloomGateway.Ring.InstanceZone = rc.InstanceZone - r.BloomGateway.Ring.ZoneAwarenessEnabled = rc.ZoneAwarenessEnabled - r.BloomGateway.Ring.KVStore = rc.KVStore - r.BloomGateway.Ring.NumTokens = rc.NumTokens - } } func applyTokensFilePath(cfg *ConfigWrapper) error { @@ -384,13 +369,6 @@ func applyTokensFilePath(cfg *ConfigWrapper) error { } cfg.BloomCompactor.Ring.TokensFilePath = f - // Bloom-Gateway - f, err = tokensFile(cfg, "bloomgateway.tokens") - if err != nil { - return err - } - cfg.BloomGateway.Ring.TokensFilePath = f - // Pattern f, err = tokensFile(cfg, "pattern.tokens") if err != nil { @@ -487,10 +465,6 @@ func appendLoopbackInterface(cfg, defaults *ConfigWrapper) { if reflect.DeepEqual(cfg.BloomCompactor.Ring.InstanceInterfaceNames, defaults.BloomCompactor.Ring.InstanceInterfaceNames) { cfg.BloomCompactor.Ring.InstanceInterfaceNames = append(cfg.BloomCompactor.Ring.InstanceInterfaceNames, loopbackIface) } - - if reflect.DeepEqual(cfg.BloomGateway.Ring.InstanceInterfaceNames, defaults.BloomGateway.Ring.InstanceInterfaceNames) { - cfg.BloomGateway.Ring.InstanceInterfaceNames = append(cfg.BloomGateway.Ring.InstanceInterfaceNames, loopbackIface) - } } // applyMemberlistConfig will change the default ingester, distributor, ruler, and query scheduler ring configurations to use memberlist. @@ -506,7 +480,6 @@ func applyMemberlistConfig(r *ConfigWrapper) { r.CompactorConfig.CompactorRing.KVStore.Store = memberlistStr r.IndexGateway.Ring.KVStore.Store = memberlistStr r.BloomCompactor.Ring.KVStore.Store = memberlistStr - r.BloomGateway.Ring.KVStore.Store = memberlistStr } var ErrTooManyStorageConfigs = errors.New("too many storage configs provided in the common config, please only define one storage backend") diff --git a/pkg/loki/loki.go b/pkg/loki/loki.go index c3ee72a7fc574..5e759b6470126 100644 --- a/pkg/loki/loki.go +++ b/pkg/loki/loki.go @@ -681,7 +681,6 @@ func (t *Loki) setupModuleManager() error { mm.RegisterModule(IndexGatewayRing, t.initIndexGatewayRing, modules.UserInvisibleModule) mm.RegisterModule(IndexGatewayInterceptors, t.initIndexGatewayInterceptors, modules.UserInvisibleModule) mm.RegisterModule(BloomGateway, t.initBloomGateway) - mm.RegisterModule(BloomGatewayRing, t.initBloomGatewayRing, modules.UserInvisibleModule) mm.RegisterModule(QueryScheduler, t.initQueryScheduler) mm.RegisterModule(QuerySchedulerRing, t.initQuerySchedulerRing, modules.UserInvisibleModule) mm.RegisterModule(Analytics, t.initAnalytics) @@ -713,14 +712,13 @@ func (t *Loki) setupModuleManager() error { TableManager: {Server, Analytics}, Compactor: {Server, Overrides, MemberlistKV, Analytics}, IndexGateway: {Server, Store, IndexGatewayRing, IndexGatewayInterceptors, Analytics}, - BloomGateway: {Server, BloomStore, BloomGatewayRing, Analytics}, + BloomGateway: {Server, BloomStore, Analytics}, BloomCompactor: {Server, BloomStore, BloomCompactorRing, Analytics, Store}, PatternIngester: {Server, MemberlistKV, Analytics}, PatternRingClient: {Server, MemberlistKV, Analytics}, IngesterQuerier: {Ring}, QuerySchedulerRing: {Overrides, MemberlistKV}, IndexGatewayRing: {Overrides, MemberlistKV}, - BloomGatewayRing: {Overrides, MemberlistKV}, BloomCompactorRing: {Overrides, MemberlistKV}, MemberlistKV: {Server}, @@ -777,11 +775,6 @@ func (t *Loki) setupModuleManager() error { deps[Server] = append(deps[Server], IngesterGRPCInterceptors) } - // Add bloom gateway ring in client mode to IndexGateway service dependencies if bloom filtering is enabled. - if t.Cfg.BloomGateway.Enabled { - deps[IndexGateway] = append(deps[IndexGateway], BloomGatewayRing) - } - if t.Cfg.LegacyReadTarget { deps[Read] = append(deps[Read], deps[Backend]...) } diff --git a/pkg/loki/modules.go b/pkg/loki/modules.go index 5d64b947437c3..0efa6b430bfb6 100644 --- a/pkg/loki/modules.go +++ b/pkg/loki/modules.go @@ -114,7 +114,6 @@ const ( MemberlistKV string = "memberlist-kv" Compactor string = "compactor" BloomGateway string = "bloom-gateway" - BloomGatewayRing string = "bloom-gateway-ring" IndexGateway string = "index-gateway" IndexGatewayRing string = "index-gateway-ring" IndexGatewayInterceptors string = "index-gateway-interceptors" @@ -278,7 +277,6 @@ func (t *Loki) initRuntimeConfig() (services.Service, error) { t.Cfg.BloomCompactor.Ring.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.Cfg.Distributor.DistributorRing.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.Cfg.IndexGateway.Ring.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) - t.Cfg.BloomGateway.Ring.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.Cfg.Ingester.LifecyclerConfig.RingConfig.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.Cfg.QueryScheduler.SchedulerRing.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) t.Cfg.Ruler.Ring.KVStore.Multi.ConfigProvider = multiClientRuntimeConfigChannel(t.runtimeConfig) @@ -1293,7 +1291,6 @@ func (t *Loki) initMemberlistKV() (services.Service, error) { t.Cfg.Ingester.LifecyclerConfig.RingConfig.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV t.Cfg.QueryScheduler.SchedulerRing.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV t.Cfg.Ruler.Ring.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV - t.Cfg.BloomGateway.Ring.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV t.Cfg.BloomCompactor.Ring.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV t.Cfg.Pattern.LifecyclerConfig.RingConfig.KVStore.MemberlistKV = t.MemberlistKV.GetMemberlistKV t.Server.HTTP.Handle("/memberlist", t.MemberlistKV) @@ -1386,35 +1383,6 @@ func (t *Loki) initBloomGateway() (services.Service, error) { return gateway, nil } -func (t *Loki) initBloomGatewayRing() (services.Service, error) { - if !t.Cfg.BloomGateway.Enabled { - return nil, nil - } - // Inherit ring listen port from gRPC config - t.Cfg.BloomGateway.Ring.ListenPort = t.Cfg.Server.GRPCListenPort - - // TODO(chaudum): Do we want to integration the bloom gateway component into the backend target? - mode := lokiring.ClientMode - legacyReadMode := t.Cfg.LegacyReadTarget && t.isModuleActive(Read) - if t.Cfg.isModuleEnabled(BloomGateway) || t.Cfg.isModuleEnabled(Backend) || legacyReadMode { - mode = lokiring.ServerMode - } - manager, err := lokiring.NewRingManager(bloomGatewayRingKey, mode, t.Cfg.BloomGateway.Ring, t.Cfg.BloomGateway.Ring.ReplicationFactor, t.Cfg.BloomGateway.Ring.NumTokens, util_log.Logger, prometheus.DefaultRegisterer) - if err != nil { - return nil, gerrors.Wrap(err, "error initializing bloom gateway ring manager") - } - - t.bloomGatewayRingManager = manager - - t.Server.HTTP.Path("/bloomgateway/ring").Methods("GET", "POST").Handler(t.bloomGatewayRingManager) - - if t.Cfg.InternalServer.Enable { - t.InternalServer.HTTP.Path("/bloomgateway/ring").Methods("GET", "POST").Handler(t.bloomGatewayRingManager) - } - - return t.bloomGatewayRingManager, nil -} - func (t *Loki) initIndexGateway() (services.Service, error) { shardingStrategy := indexgateway.GetShardingStrategy(t.Cfg.IndexGateway, t.indexGatewayRingManager, t.Overrides) diff --git a/pkg/loki/modules_test.go b/pkg/loki/modules_test.go index 90c0b887dd02e..eb196896ee15d 100644 --- a/pkg/loki/modules_test.go +++ b/pkg/loki/modules_test.go @@ -410,7 +410,6 @@ func minimalWorkingConfig(t *testing.T, dir, target string, cfgTransformers ...f cfg.IndexGateway.Mode = indexgateway.SimpleMode cfg.IndexGateway.Ring.InstanceAddr = localhost cfg.BloomCompactor.Ring.InstanceAddr = localhost - cfg.BloomGateway.Ring.InstanceAddr = localhost cfg.CompactorConfig.CompactorRing.InstanceAddr = localhost cfg.CompactorConfig.WorkingDirectory = filepath.Join(dir, "compactor")
chore
Remove bloom gateway ring (#12484)
d8cc1cea83a0060168bc1477adb16e2125786a95
2024-07-03 13:38:50
Christian Haudum
chore: Make dedicated iterator package (#13273)
false
diff --git a/pkg/bloombuild/builder/batch.go b/pkg/bloombuild/builder/batch.go index 4b5fcdb00ad2e..af47f5531df7e 100644 --- a/pkg/bloombuild/builder/batch.go +++ b/pkg/bloombuild/builder/batch.go @@ -10,6 +10,7 @@ import ( "golang.org/x/exp/slices" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" logql_log "github.com/grafana/loki/v3/pkg/logql/log" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -168,9 +169,9 @@ func newBatchedBlockLoader( } // compiler checks -var _ v1.Iterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} -var _ v1.CloseableIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} -var _ v1.ResettableIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.Iterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.CloseIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.ResetIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} // TODO(chaudum): testware func newBlockLoadingIter(ctx context.Context, blocks []bloomshipper.BlockRef, fetcher FetchFunc[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier], batchSize int) *blockLoadingIter { @@ -189,14 +190,14 @@ type blockLoadingIter struct { ctx context.Context fetcher Fetcher[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier] inputs []bloomshipper.BlockRef - overlapping v1.Iterator[[]bloomshipper.BlockRef] + overlapping iter.Iterator[[]bloomshipper.BlockRef] batchSize int // optional arguments filter func(*bloomshipper.CloseableBlockQuerier) bool // internals initialized bool err error - iter v1.Iterator[*v1.SeriesWithBlooms] + iter iter.Iterator[*v1.SeriesWithBlooms] loader *batchedLoader[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier, *bloomshipper.CloseableBlockQuerier] loaded map[io.Closer]struct{} } @@ -229,7 +230,7 @@ func (i *blockLoadingIter) init() { i.overlapping = overlappingBlocksIter(i.inputs) // set initial iter - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() // set "match all" filter function if not present if i.filter == nil { @@ -247,24 +248,24 @@ func (i *blockLoadingIter) loadNext() bool { blockRefs := i.overlapping.At() loader := newBatchedBlockLoader(i.ctx, i.fetcher, blockRefs, i.batchSize) - filtered := v1.NewFilterIter[*bloomshipper.CloseableBlockQuerier](loader, i.filter) + filtered := iter.NewFilterIter[*bloomshipper.CloseableBlockQuerier](loader, i.filter) - iters := make([]v1.PeekingIterator[*v1.SeriesWithBlooms], 0, len(blockRefs)) + iters := make([]iter.PeekIterator[*v1.SeriesWithBlooms], 0, len(blockRefs)) for filtered.Next() { bq := filtered.At() i.loaded[bq] = struct{}{} - iter, err := bq.SeriesIter() + itr, err := bq.SeriesIter() if err != nil { i.err = err - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() return false } - iters = append(iters, iter) + iters = append(iters, itr) } if err := filtered.Err(); err != nil { i.err = err - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() return false } @@ -278,23 +279,23 @@ func (i *blockLoadingIter) loadNext() bool { // two overlapping blocks can conceivably have the same series, so we need to dedupe, // preferring the one with the most chunks already indexed since we'll have // to add fewer chunks to the bloom - i.iter = v1.NewDedupingIter[*v1.SeriesWithBlooms, *v1.SeriesWithBlooms]( + i.iter = iter.NewDedupingIter[*v1.SeriesWithBlooms, *v1.SeriesWithBlooms]( func(a, b *v1.SeriesWithBlooms) bool { return a.Series.Fingerprint == b.Series.Fingerprint }, - v1.Identity[*v1.SeriesWithBlooms], + iter.Identity[*v1.SeriesWithBlooms], func(a, b *v1.SeriesWithBlooms) *v1.SeriesWithBlooms { if len(a.Series.Chunks) > len(b.Series.Chunks) { return a } return b }, - v1.NewPeekingIter(mergedBlocks), + iter.NewPeekIter(mergedBlocks), ) return i.iter.Next() } - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() i.err = i.overlapping.Err() return false } @@ -335,11 +336,11 @@ func (i *blockLoadingIter) Filter(filter func(*bloomshipper.CloseableBlockQuerie i.filter = filter } -func overlappingBlocksIter(inputs []bloomshipper.BlockRef) v1.Iterator[[]bloomshipper.BlockRef] { +func overlappingBlocksIter(inputs []bloomshipper.BlockRef) iter.Iterator[[]bloomshipper.BlockRef] { // can we assume sorted blocks? - peekIter := v1.NewPeekingIter(v1.NewSliceIter(inputs)) + peekIter := iter.NewPeekIter(iter.NewSliceIter(inputs)) - return v1.NewDedupingIter[bloomshipper.BlockRef, []bloomshipper.BlockRef]( + return iter.NewDedupingIter[bloomshipper.BlockRef, []bloomshipper.BlockRef]( func(a bloomshipper.BlockRef, b []bloomshipper.BlockRef) bool { minFp := b[0].Bounds.Min maxFp := slices.MaxFunc(b, func(a, b bloomshipper.BlockRef) int { return int(a.Bounds.Max - b.Bounds.Max) }).Bounds.Max diff --git a/pkg/bloombuild/builder/batch_test.go b/pkg/bloombuild/builder/batch_test.go index 19de5354fb14b..37109d0196af6 100644 --- a/pkg/bloombuild/builder/batch_test.go +++ b/pkg/bloombuild/builder/batch_test.go @@ -8,6 +8,7 @@ import ( "github.com/prometheus/common/model" "github.com/stretchr/testify/require" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" ) @@ -128,7 +129,7 @@ func TestBatchedLoader(t *testing.T) { tc.batchSize, ) - got, err := v1.Collect[int](loader) + got, err := v2.Collect[int](loader) if tc.err { require.Error(t, err) return diff --git a/pkg/bloombuild/builder/builder.go b/pkg/bloombuild/builder/builder.go index 0ee9afbc71fd5..2282a377f783f 100644 --- a/pkg/bloombuild/builder/builder.go +++ b/pkg/bloombuild/builder/builder.go @@ -22,6 +22,7 @@ import ( "github.com/grafana/loki/v3/pkg/bloombuild/common" "github.com/grafana/loki/v3/pkg/bloombuild/protos" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" @@ -334,7 +335,7 @@ func (b *Builder) processTask( // Blocks are built consuming the series iterator. For observability, we wrap the series iterator // with a counter iterator to count the number of times Next() is called on it. // This is used to observe the number of series that are being processed. - seriesItrWithCounter := v1.NewCounterIter[*v1.Series](seriesItr) + seriesItrWithCounter := iter.NewCounterIter[*v1.Series](seriesItr) gen := NewSimpleBloomGenerator( tenant, @@ -429,7 +430,7 @@ func (b *Builder) loadWorkForGap( tenant string, id tsdb.Identifier, gap protos.GapWithBlocks, -) (v1.Iterator[*v1.Series], v1.CloseableResettableIterator[*v1.SeriesWithBlooms], error) { +) (iter.Iterator[*v1.Series], iter.CloseResetIterator[*v1.SeriesWithBlooms], error) { // load a series iterator for the gap seriesItr, err := b.tsdbStore.LoadTSDB(ctx, table, tenant, id, gap.Bounds) if err != nil { diff --git a/pkg/bloombuild/builder/spec.go b/pkg/bloombuild/builder/spec.go index a031a69c9812b..3feca8f49a3b0 100644 --- a/pkg/bloombuild/builder/spec.go +++ b/pkg/bloombuild/builder/spec.go @@ -10,6 +10,7 @@ import ( "github.com/pkg/errors" "github.com/prometheus/common/model" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/chunk" @@ -36,15 +37,15 @@ func (k Keyspace) Cmp(other Keyspace) v1.BoundsCheck { // Store is likely bound within. This allows specifying impls like ShardedStore<Store> // to only request the shard-range needed from the existing store. type BloomGenerator interface { - Generate(ctx context.Context) (skippedBlocks []v1.BlockMetadata, toClose []io.Closer, results v1.Iterator[*v1.Block], err error) + Generate(ctx context.Context) (skippedBlocks []v1.BlockMetadata, toClose []io.Closer, results iter.Iterator[*v1.Block], err error) } // Simple implementation of a BloomGenerator. type SimpleBloomGenerator struct { userID string - store v1.Iterator[*v1.Series] + store iter.Iterator[*v1.Series] chunkLoader ChunkLoader - blocksIter v1.ResettableIterator[*v1.SeriesWithBlooms] + blocksIter iter.ResetIterator[*v1.SeriesWithBlooms] // options to build blocks with opts v1.BlockOptions @@ -65,9 +66,9 @@ type SimpleBloomGenerator struct { func NewSimpleBloomGenerator( userID string, opts v1.BlockOptions, - store v1.Iterator[*v1.Series], + store iter.Iterator[*v1.Series], chunkLoader ChunkLoader, - blocksIter v1.ResettableIterator[*v1.SeriesWithBlooms], + blocksIter iter.ResetIterator[*v1.SeriesWithBlooms], readWriterFn func() (v1.BlockWriter, v1.BlockReader), reporter func(model.Fingerprint), metrics *v1.Metrics, @@ -100,7 +101,7 @@ func NewSimpleBloomGenerator( func (s *SimpleBloomGenerator) populator(ctx context.Context) v1.BloomPopulatorFunc { return func( series *v1.Series, - srcBlooms v1.SizedIterator[*v1.Bloom], + srcBlooms iter.SizedIterator[*v1.Bloom], toAdd v1.ChunkRefs, ch chan *v1.BloomCreation, ) { @@ -126,7 +127,7 @@ func (s *SimpleBloomGenerator) populator(ctx context.Context) v1.BloomPopulatorF func (s *SimpleBloomGenerator) Generate(ctx context.Context) *LazyBlockBuilderIterator { level.Debug(s.logger).Log("msg", "generating bloom filters for blocks", "schema", fmt.Sprintf("%+v", s.opts.Schema)) - series := v1.NewPeekingIter(s.store) + series := iter.NewPeekIter(s.store) // TODO: Use interface impl, ok := s.blocksIter.(*blockLoadingIter) @@ -166,8 +167,8 @@ type LazyBlockBuilderIterator struct { metrics *v1.Metrics populate v1.BloomPopulatorFunc readWriterFn func() (v1.BlockWriter, v1.BlockReader) - series v1.PeekingIterator[*v1.Series] - blocks v1.ResettableIterator[*v1.SeriesWithBlooms] + series iter.PeekIterator[*v1.Series] + blocks iter.ResetIterator[*v1.SeriesWithBlooms] bytesAdded int curr *v1.Block @@ -180,8 +181,8 @@ func NewLazyBlockBuilderIterator( metrics *v1.Metrics, populate v1.BloomPopulatorFunc, readWriterFn func() (v1.BlockWriter, v1.BlockReader), - series v1.PeekingIterator[*v1.Series], - blocks v1.ResettableIterator[*v1.SeriesWithBlooms], + series iter.PeekIterator[*v1.Series], + blocks iter.ResetIterator[*v1.SeriesWithBlooms], ) *LazyBlockBuilderIterator { return &LazyBlockBuilderIterator{ ctx: ctx, @@ -250,7 +251,7 @@ type indexLoader interface { // ChunkItersByFingerprint models the chunks belonging to a fingerprint type ChunkItersByFingerprint struct { fp model.Fingerprint - itr v1.Iterator[v1.ChunkRefWithIter] + itr iter.Iterator[v1.ChunkRefWithIter] } // ChunkLoader loads chunks from a store diff --git a/pkg/bloombuild/builder/spec_test.go b/pkg/bloombuild/builder/spec_test.go index 0e3f98c907799..5be2a0e1c61be 100644 --- a/pkg/bloombuild/builder/spec_test.go +++ b/pkg/bloombuild/builder/spec_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" "github.com/grafana/loki/v3/pkg/util/mempool" @@ -47,7 +48,7 @@ func blocksFromSchemaWithRange(t *testing.T, n int, options v1.BlockOptions, fro minIdx, maxIdx := i*seriesPerBlock, (i+1)*seriesPerBlock - itr := v1.NewSliceIter[v1.SeriesWithBlooms](data[minIdx:maxIdx]) + itr := v2.NewSliceIter[v1.SeriesWithBlooms](data[minIdx:maxIdx]) _, err = builder.BuildFrom(itr) require.Nil(t, err) @@ -66,11 +67,11 @@ type dummyChunkLoader struct{} func (dummyChunkLoader) Load(_ context.Context, _ string, series *v1.Series) *ChunkItersByFingerprint { return &ChunkItersByFingerprint{ fp: series.Fingerprint, - itr: v1.NewEmptyIter[v1.ChunkRefWithIter](), + itr: v2.NewEmptyIter[v1.ChunkRefWithIter](), } } -func dummyBloomGen(t *testing.T, opts v1.BlockOptions, store v1.Iterator[*v1.Series], blocks []*v1.Block, refs []bloomshipper.BlockRef) *SimpleBloomGenerator { +func dummyBloomGen(t *testing.T, opts v1.BlockOptions, store v2.Iterator[*v1.Series], blocks []*v1.Block, refs []bloomshipper.BlockRef) *SimpleBloomGenerator { bqs := make([]*bloomshipper.CloseableBlockQuerier, 0, len(blocks)) for i, b := range blocks { bqs = append(bqs, &bloomshipper.CloseableBlockQuerier{ @@ -133,8 +134,8 @@ func TestSimpleBloomGenerator(t *testing.T) { } { t.Run(fmt.Sprintf("%s/%s", tc.desc, enc), func(t *testing.T) { sourceBlocks, data, refs := blocksFromSchemaWithRange(t, 2, tc.fromSchema, 0x00000, 0x6ffff) - storeItr := v1.NewMapIter[v1.SeriesWithBlooms, *v1.Series]( - v1.NewSliceIter[v1.SeriesWithBlooms](data), + storeItr := v2.NewMapIter[v1.SeriesWithBlooms, *v1.Series]( + v2.NewSliceIter[v1.SeriesWithBlooms](data), func(swb v1.SeriesWithBlooms) *v1.Series { return swb.Series }, diff --git a/pkg/bloombuild/common/tsdb.go b/pkg/bloombuild/common/tsdb.go index a24efcd1eecf1..8082a8b319a47 100644 --- a/pkg/bloombuild/common/tsdb.go +++ b/pkg/bloombuild/common/tsdb.go @@ -15,6 +15,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" baseStore "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" @@ -38,7 +39,7 @@ type TSDBStore interface { tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, - ) (v1.Iterator[*v1.Series], error) + ) (iter.Iterator[*v1.Series], error) } // BloomTSDBStore is a wrapper around the storage.Client interface which @@ -90,7 +91,7 @@ func (b *BloomTSDBStore) LoadTSDB( tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, -) (v1.Iterator[*v1.Series], error) { +) (iter.Iterator[*v1.Series], error) { withCompression := id.Name() + gzipExtension data, err := b.storage.GetUserFile(ctx, table.Addr(), tenant, withCompression) @@ -126,7 +127,7 @@ func (b *BloomTSDBStore) LoadTSDB( return NewTSDBSeriesIter(ctx, tenant, idx, bounds) } -func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, bounds v1.FingerprintBounds) (v1.Iterator[*v1.Series], error) { +func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, bounds v1.FingerprintBounds) (iter.Iterator[*v1.Series], error) { // TODO(salvacorts): Create a pool series := make([]*v1.Series, 0, 100) @@ -163,9 +164,9 @@ func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, b select { case <-ctx.Done(): - return v1.NewEmptyIter[*v1.Series](), ctx.Err() + return iter.NewEmptyIter[*v1.Series](), ctx.Err() default: - return v1.NewCancelableIter[*v1.Series](ctx, v1.NewSliceIter[*v1.Series](series)), nil + return iter.NewCancelableIter[*v1.Series](ctx, iter.NewSliceIter[*v1.Series](series)), nil } } @@ -251,7 +252,7 @@ func (s *TSDBStores) LoadTSDB( tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, -) (v1.Iterator[*v1.Series], error) { +) (iter.Iterator[*v1.Series], error) { store, err := s.storeForPeriod(table.DayTime) if err != nil { return nil, err diff --git a/pkg/bloombuild/common/tsdb_test.go b/pkg/bloombuild/common/tsdb_test.go index 481399102fce1..70ee440551e42 100644 --- a/pkg/bloombuild/common/tsdb_test.go +++ b/pkg/bloombuild/common/tsdb_test.go @@ -9,6 +9,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/stretchr/testify/require" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" ) @@ -61,7 +62,7 @@ func TestTSDBSeriesIter(t *testing.T) { }, }, } - srcItr := v1.NewSliceIter(input) + srcItr := v2.NewSliceIter(input) itr, err := NewTSDBSeriesIter(context.Background(), "", forSeriesTestImpl(input), v1.NewBounds(0, math.MaxUint64)) require.NoError(t, err) diff --git a/pkg/bloombuild/planner/planner.go b/pkg/bloombuild/planner/planner.go index ccbd462aaabe0..995a4f9f35d01 100644 --- a/pkg/bloombuild/planner/planner.go +++ b/pkg/bloombuild/planner/planner.go @@ -18,6 +18,7 @@ import ( "github.com/grafana/loki/v3/pkg/bloombuild/common" "github.com/grafana/loki/v3/pkg/bloombuild/protos" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/queue" "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -575,13 +576,13 @@ func (p *Planner) loadTenantWork( return tenantTableWork, ctx.Err() } -func (p *Planner) tenants(ctx context.Context, table config.DayTable) (*v1.SliceIter[string], error) { +func (p *Planner) tenants(ctx context.Context, table config.DayTable) (*iter.SliceIter[string], error) { tenants, err := p.tsdbStore.UsersForPeriod(ctx, table) if err != nil { return nil, fmt.Errorf("error loading tenants for table (%s): %w", table, err) } - return v1.NewSliceIter(tenants), nil + return iter.NewSliceIter(tenants), nil } // blockPlan is a plan for all the work needed to build a meta.json @@ -720,24 +721,24 @@ func blockPlansForGaps(tsdbs []tsdbGaps, metas []bloomshipper.Meta) ([]blockPlan return planGap.Blocks[i].Bounds.Less(planGap.Blocks[j].Bounds) }) - peekingBlocks := v1.NewPeekingIter[bloomshipper.BlockRef]( - v1.NewSliceIter[bloomshipper.BlockRef]( + peekingBlocks := iter.NewPeekIter[bloomshipper.BlockRef]( + iter.NewSliceIter[bloomshipper.BlockRef]( planGap.Blocks, ), ) // dedupe blocks which could be in multiple metas - itr := v1.NewDedupingIter[bloomshipper.BlockRef, bloomshipper.BlockRef]( + itr := iter.NewDedupingIter[bloomshipper.BlockRef, bloomshipper.BlockRef]( func(a, b bloomshipper.BlockRef) bool { return a == b }, - v1.Identity[bloomshipper.BlockRef], + iter.Identity[bloomshipper.BlockRef], func(a, _ bloomshipper.BlockRef) bloomshipper.BlockRef { return a }, peekingBlocks, ) - deduped, err := v1.Collect[bloomshipper.BlockRef](itr) + deduped, err := iter.Collect[bloomshipper.BlockRef](itr) if err != nil { return nil, fmt.Errorf("failed to dedupe blocks: %w", err) } diff --git a/pkg/bloomcompactor/batch.go b/pkg/bloomcompactor/batch.go index 4525bca006a07..c4e1043b44831 100644 --- a/pkg/bloomcompactor/batch.go +++ b/pkg/bloomcompactor/batch.go @@ -10,6 +10,7 @@ import ( "golang.org/x/exp/slices" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" logql_log "github.com/grafana/loki/v3/pkg/logql/log" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -168,9 +169,9 @@ func newBatchedBlockLoader( } // compiler checks -var _ v1.Iterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} -var _ v1.CloseableIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} -var _ v1.ResettableIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.Iterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.CloseIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} +var _ iter.ResetIterator[*v1.SeriesWithBlooms] = &blockLoadingIter{} // TODO(chaudum): testware func newBlockLoadingIter(ctx context.Context, blocks []bloomshipper.BlockRef, fetcher FetchFunc[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier], batchSize int) *blockLoadingIter { @@ -189,14 +190,14 @@ type blockLoadingIter struct { ctx context.Context fetcher Fetcher[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier] inputs []bloomshipper.BlockRef - overlapping v1.Iterator[[]bloomshipper.BlockRef] + overlapping iter.Iterator[[]bloomshipper.BlockRef] batchSize int // optional arguments filter func(*bloomshipper.CloseableBlockQuerier) bool // internals initialized bool err error - iter v1.Iterator[*v1.SeriesWithBlooms] + iter iter.Iterator[*v1.SeriesWithBlooms] loader *batchedLoader[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier, *bloomshipper.CloseableBlockQuerier] loaded map[io.Closer]struct{} } @@ -229,7 +230,7 @@ func (i *blockLoadingIter) init() { i.overlapping = overlappingBlocksIter(i.inputs) // set initial iter - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() // set "match all" filter function if not present if i.filter == nil { @@ -247,24 +248,24 @@ func (i *blockLoadingIter) loadNext() bool { blockRefs := i.overlapping.At() loader := newBatchedBlockLoader(i.ctx, i.fetcher, blockRefs, i.batchSize) - filtered := v1.NewFilterIter[*bloomshipper.CloseableBlockQuerier](loader, i.filter) + filtered := iter.NewFilterIter[*bloomshipper.CloseableBlockQuerier](loader, i.filter) - iters := make([]v1.PeekingIterator[*v1.SeriesWithBlooms], 0, len(blockRefs)) + iters := make([]iter.PeekIterator[*v1.SeriesWithBlooms], 0, len(blockRefs)) for filtered.Next() { bq := filtered.At() i.loaded[bq] = struct{}{} - iter, err := bq.SeriesIter() + itr, err := bq.SeriesIter() if err != nil { i.err = err - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() return false } - iters = append(iters, iter) + iters = append(iters, itr) } if err := filtered.Err(); err != nil { i.err = err - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() return false } @@ -278,23 +279,23 @@ func (i *blockLoadingIter) loadNext() bool { // two overlapping blocks can conceivably have the same series, so we need to dedupe, // preferring the one with the most chunks already indexed since we'll have // to add fewer chunks to the bloom - i.iter = v1.NewDedupingIter[*v1.SeriesWithBlooms, *v1.SeriesWithBlooms]( + i.iter = iter.NewDedupingIter[*v1.SeriesWithBlooms, *v1.SeriesWithBlooms]( func(a, b *v1.SeriesWithBlooms) bool { return a.Series.Fingerprint == b.Series.Fingerprint }, - v1.Identity[*v1.SeriesWithBlooms], + iter.Identity[*v1.SeriesWithBlooms], func(a, b *v1.SeriesWithBlooms) *v1.SeriesWithBlooms { if len(a.Series.Chunks) > len(b.Series.Chunks) { return a } return b }, - v1.NewPeekingIter(mergedBlocks), + iter.NewPeekIter(mergedBlocks), ) return i.iter.Next() } - i.iter = v1.NewEmptyIter[*v1.SeriesWithBlooms]() + i.iter = iter.NewEmptyIter[*v1.SeriesWithBlooms]() i.err = i.overlapping.Err() return false } @@ -335,11 +336,11 @@ func (i *blockLoadingIter) Filter(filter func(*bloomshipper.CloseableBlockQuerie i.filter = filter } -func overlappingBlocksIter(inputs []bloomshipper.BlockRef) v1.Iterator[[]bloomshipper.BlockRef] { +func overlappingBlocksIter(inputs []bloomshipper.BlockRef) iter.Iterator[[]bloomshipper.BlockRef] { // can we assume sorted blocks? - peekIter := v1.NewPeekingIter(v1.NewSliceIter(inputs)) + peekIter := iter.NewPeekIter(iter.NewSliceIter(inputs)) - return v1.NewDedupingIter[bloomshipper.BlockRef, []bloomshipper.BlockRef]( + return iter.NewDedupingIter[bloomshipper.BlockRef, []bloomshipper.BlockRef]( func(a bloomshipper.BlockRef, b []bloomshipper.BlockRef) bool { minFp := b[0].Bounds.Min maxFp := slices.MaxFunc(b, func(a, b bloomshipper.BlockRef) int { return int(a.Bounds.Max - b.Bounds.Max) }).Bounds.Max diff --git a/pkg/bloomcompactor/batch_test.go b/pkg/bloomcompactor/batch_test.go index d64b8313e1066..09d595459b509 100644 --- a/pkg/bloomcompactor/batch_test.go +++ b/pkg/bloomcompactor/batch_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" - v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" ) @@ -127,7 +127,7 @@ func TestBatchedLoader(t *testing.T) { tc.batchSize, ) - got, err := v1.Collect[int](loader) + got, err := v2.Collect[int](loader) if tc.err { require.Error(t, err) return diff --git a/pkg/bloomcompactor/bloomcompactor.go b/pkg/bloomcompactor/bloomcompactor.go index 8eed0823314a7..6f07389a0bb4a 100644 --- a/pkg/bloomcompactor/bloomcompactor.go +++ b/pkg/bloomcompactor/bloomcompactor.go @@ -17,6 +17,7 @@ import ( "github.com/prometheus/common/model" "github.com/grafana/loki/v3/pkg/bloomutils" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" @@ -185,13 +186,13 @@ type tenantTableRange struct { queueTime, startTime, endTime time.Time } -func (c *Compactor) tenants(ctx context.Context, table config.DayTable) (*v1.SliceIter[string], error) { +func (c *Compactor) tenants(ctx context.Context, table config.DayTable) (*iter.SliceIter[string], error) { tenants, err := c.tsdbStore.UsersForPeriod(ctx, table) if err != nil { return nil, errors.Wrap(err, "getting tenants") } - return v1.NewSliceIter(tenants), nil + return iter.NewSliceIter(tenants), nil } // ownsTenant returns the ownership range for the tenant, if the compactor owns the tenant, and an error. diff --git a/pkg/bloomcompactor/controller.go b/pkg/bloomcompactor/controller.go index 3929f2da3f805..fffd67f7f2f42 100644 --- a/pkg/bloomcompactor/controller.go +++ b/pkg/bloomcompactor/controller.go @@ -14,6 +14,7 @@ import ( "github.com/prometheus/common/model" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" @@ -287,7 +288,7 @@ func (s *SimpleBloomController) loadWorkForGap( tenant string, id tsdb.Identifier, gap gapWithBlocks, -) (v1.Iterator[*v1.Series], v1.CloseableResettableIterator[*v1.SeriesWithBlooms], error) { +) (iter.Iterator[*v1.Series], iter.CloseResetIterator[*v1.SeriesWithBlooms], error) { // load a series iterator for the gap seriesItr, err := s.tsdbStore.LoadTSDB(ctx, table, tenant, id, gap.bounds) if err != nil { @@ -400,7 +401,7 @@ func (s *SimpleBloomController) buildGaps( // Blocks are built consuming the series iterator. For observability, we wrap the series iterator // with a counter iterator to count the number of times Next() is called on it. // This is used to observe the number of series that are being processed. - seriesItrWithCounter := v1.NewCounterIter[*v1.Series](seriesItr) + seriesItrWithCounter := iter.NewCounterIter[*v1.Series](seriesItr) gen := NewSimpleBloomGenerator( tenant, @@ -612,24 +613,24 @@ func blockPlansForGaps(tsdbs []tsdbGaps, metas []bloomshipper.Meta) ([]blockPlan return planGap.blocks[i].Bounds.Less(planGap.blocks[j].Bounds) }) - peekingBlocks := v1.NewPeekingIter[bloomshipper.BlockRef]( - v1.NewSliceIter[bloomshipper.BlockRef]( + peekingBlocks := iter.NewPeekIter[bloomshipper.BlockRef]( + iter.NewSliceIter[bloomshipper.BlockRef]( planGap.blocks, ), ) // dedupe blocks which could be in multiple metas - itr := v1.NewDedupingIter[bloomshipper.BlockRef, bloomshipper.BlockRef]( + itr := iter.NewDedupingIter[bloomshipper.BlockRef, bloomshipper.BlockRef]( func(a, b bloomshipper.BlockRef) bool { return a == b }, - v1.Identity[bloomshipper.BlockRef], + iter.Identity[bloomshipper.BlockRef], func(a, _ bloomshipper.BlockRef) bloomshipper.BlockRef { return a }, peekingBlocks, ) - deduped, err := v1.Collect[bloomshipper.BlockRef](itr) + deduped, err := iter.Collect[bloomshipper.BlockRef](itr) if err != nil { return nil, errors.Wrap(err, "failed to dedupe blocks") } diff --git a/pkg/bloomcompactor/spec.go b/pkg/bloomcompactor/spec.go index 2cb16eac02eae..7a1d000dde709 100644 --- a/pkg/bloomcompactor/spec.go +++ b/pkg/bloomcompactor/spec.go @@ -10,6 +10,7 @@ import ( "github.com/pkg/errors" "github.com/prometheus/common/model" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/chunk" @@ -36,15 +37,15 @@ func (k Keyspace) Cmp(other Keyspace) v1.BoundsCheck { // Store is likely bound within. This allows specifying impls like ShardedStore<Store> // to only request the shard-range needed from the existing store. type BloomGenerator interface { - Generate(ctx context.Context) (skippedBlocks []v1.BlockMetadata, toClose []io.Closer, results v1.Iterator[*v1.Block], err error) + Generate(ctx context.Context) (skippedBlocks []v1.BlockMetadata, toClose []io.Closer, results iter.Iterator[*v1.Block], err error) } // Simple implementation of a BloomGenerator. type SimpleBloomGenerator struct { userID string - store v1.Iterator[*v1.Series] + store iter.Iterator[*v1.Series] chunkLoader ChunkLoader - blocksIter v1.ResettableIterator[*v1.SeriesWithBlooms] + blocksIter iter.ResetIterator[*v1.SeriesWithBlooms] // options to build blocks with opts v1.BlockOptions @@ -65,9 +66,9 @@ type SimpleBloomGenerator struct { func NewSimpleBloomGenerator( userID string, opts v1.BlockOptions, - store v1.Iterator[*v1.Series], + store iter.Iterator[*v1.Series], chunkLoader ChunkLoader, - blocksIter v1.ResettableIterator[*v1.SeriesWithBlooms], + blocksIter iter.ResetIterator[*v1.SeriesWithBlooms], readWriterFn func() (v1.BlockWriter, v1.BlockReader), reporter func(model.Fingerprint), metrics *Metrics, @@ -100,7 +101,7 @@ func NewSimpleBloomGenerator( func (s *SimpleBloomGenerator) populator(ctx context.Context) v1.BloomPopulatorFunc { return func( series *v1.Series, - srcBlooms v1.SizedIterator[*v1.Bloom], + srcBlooms iter.SizedIterator[*v1.Bloom], toAdd v1.ChunkRefs, ch chan *v1.BloomCreation, ) { @@ -126,7 +127,7 @@ func (s *SimpleBloomGenerator) populator(ctx context.Context) v1.BloomPopulatorF func (s *SimpleBloomGenerator) Generate(ctx context.Context) *LazyBlockBuilderIterator { level.Debug(s.logger).Log("msg", "generating bloom filters for blocks", "schema", fmt.Sprintf("%+v", s.opts.Schema)) - series := v1.NewPeekingIter(s.store) + series := iter.NewPeekIter(s.store) // TODO: Use interface impl, ok := s.blocksIter.(*blockLoadingIter) @@ -166,8 +167,8 @@ type LazyBlockBuilderIterator struct { metrics *Metrics populate v1.BloomPopulatorFunc readWriterFn func() (v1.BlockWriter, v1.BlockReader) - series v1.PeekingIterator[*v1.Series] - blocks v1.ResettableIterator[*v1.SeriesWithBlooms] + series iter.PeekIterator[*v1.Series] + blocks iter.ResetIterator[*v1.SeriesWithBlooms] bytesAdded int curr *v1.Block @@ -180,8 +181,8 @@ func NewLazyBlockBuilderIterator( metrics *Metrics, populate v1.BloomPopulatorFunc, readWriterFn func() (v1.BlockWriter, v1.BlockReader), - series v1.PeekingIterator[*v1.Series], - blocks v1.ResettableIterator[*v1.SeriesWithBlooms], + series iter.PeekIterator[*v1.Series], + blocks iter.ResetIterator[*v1.SeriesWithBlooms], ) *LazyBlockBuilderIterator { return &LazyBlockBuilderIterator{ ctx: ctx, @@ -250,7 +251,7 @@ type indexLoader interface { // ChunkItersByFingerprint models the chunks belonging to a fingerprint type ChunkItersByFingerprint struct { fp model.Fingerprint - itr v1.Iterator[v1.ChunkRefWithIter] + itr iter.Iterator[v1.ChunkRefWithIter] } // ChunkLoader loads chunks from a store diff --git a/pkg/bloomcompactor/spec_test.go b/pkg/bloomcompactor/spec_test.go index e08cafb68cab4..8ee914b5c8982 100644 --- a/pkg/bloomcompactor/spec_test.go +++ b/pkg/bloomcompactor/spec_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" "github.com/grafana/loki/v3/pkg/util/mempool" @@ -47,7 +48,7 @@ func blocksFromSchemaWithRange(t *testing.T, n int, options v1.BlockOptions, fro minIdx, maxIdx := i*seriesPerBlock, (i+1)*seriesPerBlock - itr := v1.NewSliceIter[v1.SeriesWithBlooms](data[minIdx:maxIdx]) + itr := v2.NewSliceIter[v1.SeriesWithBlooms](data[minIdx:maxIdx]) _, err = builder.BuildFrom(itr) require.Nil(t, err) @@ -66,11 +67,11 @@ type dummyChunkLoader struct{} func (dummyChunkLoader) Load(_ context.Context, _ string, series *v1.Series) *ChunkItersByFingerprint { return &ChunkItersByFingerprint{ fp: series.Fingerprint, - itr: v1.NewEmptyIter[v1.ChunkRefWithIter](), + itr: v2.NewEmptyIter[v1.ChunkRefWithIter](), } } -func dummyBloomGen(t *testing.T, opts v1.BlockOptions, store v1.Iterator[*v1.Series], blocks []*v1.Block, refs []bloomshipper.BlockRef) *SimpleBloomGenerator { +func dummyBloomGen(t *testing.T, opts v1.BlockOptions, store v2.Iterator[*v1.Series], blocks []*v1.Block, refs []bloomshipper.BlockRef) *SimpleBloomGenerator { bqs := make([]*bloomshipper.CloseableBlockQuerier, 0, len(blocks)) for i, b := range blocks { bqs = append(bqs, &bloomshipper.CloseableBlockQuerier{ @@ -133,8 +134,8 @@ func TestSimpleBloomGenerator(t *testing.T) { } { t.Run(fmt.Sprintf("%s/%s", tc.desc, enc), func(t *testing.T) { sourceBlocks, data, refs := blocksFromSchemaWithRange(t, 2, tc.fromSchema, 0x00000, 0x6ffff) - storeItr := v1.NewMapIter[v1.SeriesWithBlooms, *v1.Series]( - v1.NewSliceIter[v1.SeriesWithBlooms](data), + storeItr := v2.NewMapIter[v1.SeriesWithBlooms, *v1.Series]( + v2.NewSliceIter[v1.SeriesWithBlooms](data), func(swb v1.SeriesWithBlooms) *v1.Series { return swb.Series }, diff --git a/pkg/bloomcompactor/tsdb.go b/pkg/bloomcompactor/tsdb.go index c5b1ecf59307c..c522cc6dbcef2 100644 --- a/pkg/bloomcompactor/tsdb.go +++ b/pkg/bloomcompactor/tsdb.go @@ -15,6 +15,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" baseStore "github.com/grafana/loki/v3/pkg/storage" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" @@ -38,7 +39,7 @@ type TSDBStore interface { tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, - ) (v1.Iterator[*v1.Series], error) + ) (iter.Iterator[*v1.Series], error) } // BloomTSDBStore is a wrapper around the storage.Client interface which @@ -90,7 +91,7 @@ func (b *BloomTSDBStore) LoadTSDB( tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, -) (v1.Iterator[*v1.Series], error) { +) (iter.Iterator[*v1.Series], error) { withCompression := id.Name() + gzipExtension data, err := b.storage.GetUserFile(ctx, table.Addr(), tenant, withCompression) @@ -126,7 +127,7 @@ func (b *BloomTSDBStore) LoadTSDB( return NewTSDBSeriesIter(ctx, tenant, idx, bounds) } -func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, bounds v1.FingerprintBounds) (v1.Iterator[*v1.Series], error) { +func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, bounds v1.FingerprintBounds) (iter.Iterator[*v1.Series], error) { // TODO(salvacorts): Create a pool series := make([]*v1.Series, 0, 100) @@ -163,9 +164,9 @@ func NewTSDBSeriesIter(ctx context.Context, user string, f sharding.ForSeries, b select { case <-ctx.Done(): - return v1.NewEmptyIter[*v1.Series](), ctx.Err() + return iter.NewEmptyIter[*v1.Series](), ctx.Err() default: - return v1.NewCancelableIter[*v1.Series](ctx, v1.NewSliceIter[*v1.Series](series)), nil + return iter.NewCancelableIter[*v1.Series](ctx, iter.NewSliceIter[*v1.Series](series)), nil } } @@ -251,7 +252,7 @@ func (s *TSDBStores) LoadTSDB( tenant string, id tsdb.Identifier, bounds v1.FingerprintBounds, -) (v1.Iterator[*v1.Series], error) { +) (iter.Iterator[*v1.Series], error) { store, err := s.storeForPeriod(table.DayTime) if err != nil { return nil, err diff --git a/pkg/bloomcompactor/tsdb_test.go b/pkg/bloomcompactor/tsdb_test.go index a18e36ddb6d15..b81880d83b46a 100644 --- a/pkg/bloomcompactor/tsdb_test.go +++ b/pkg/bloomcompactor/tsdb_test.go @@ -9,6 +9,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/stretchr/testify/require" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" ) @@ -61,7 +62,7 @@ func TestTSDBSeriesIter(t *testing.T) { }, }, } - srcItr := v1.NewSliceIter(input) + srcItr := v2.NewSliceIter(input) itr, err := NewTSDBSeriesIter(context.Background(), "", forSeriesTestImpl(input), v1.NewBounds(0, math.MaxUint64)) require.NoError(t, err) diff --git a/pkg/bloomgateway/bloomgateway.go b/pkg/bloomgateway/bloomgateway.go index 603d41c2c4371..cdc7c96f065b5 100644 --- a/pkg/bloomgateway/bloomgateway.go +++ b/pkg/bloomgateway/bloomgateway.go @@ -21,6 +21,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "go.uber.org/atomic" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/queue" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -351,13 +352,13 @@ func filterChunkRefs(req *logproto.FilterChunkRefRequest, responses []v1.Output) // dedupe outputs, merging the same series. // This returns an Iterator[v1.Output] - dedupedResps := v1.NewDedupingIter[v1.Output, v1.Output]( + dedupedResps := iter.NewDedupingIter[v1.Output, v1.Output]( // eq func(o1, o2 v1.Output) bool { return o1.Fp == o2.Fp }, // from - v1.Identity[v1.Output], + iter.Identity[v1.Output], // merge two removal sets for the same series, deduping // requires that the removals of the outputs are sorted func(o1, o2 v1.Output) v1.Output { @@ -395,7 +396,7 @@ func filterChunkRefs(req *logproto.FilterChunkRefRequest, responses []v1.Output) res.Removals = chks return res }, - v1.NewPeekingIter(v1.NewSliceIter(responses)), + iter.NewPeekIter(iter.NewSliceIter(responses)), ) // Iterate through the requested and filtered series/chunks, diff --git a/pkg/bloomgateway/client.go b/pkg/bloomgateway/client.go index 36e5b7598da9c..d64cba01224da 100644 --- a/pkg/bloomgateway/client.go +++ b/pkg/bloomgateway/client.go @@ -18,6 +18,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/health/grpc_health_v1" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logqlmodel/stats" "github.com/grafana/loki/v3/pkg/querier/plan" @@ -300,10 +301,10 @@ func mergeSeries(input [][]*logproto.GroupedChunkRefs, buf []*logproto.GroupedCh // clear provided buffer buf = buf[:0] - iters := make([]v1.PeekingIterator[*logproto.GroupedChunkRefs], 0, len(input)) + iters := make([]iter.PeekIterator[*logproto.GroupedChunkRefs], 0, len(input)) for _, inp := range input { sort.Slice(inp, func(i, j int) bool { return inp[i].Fingerprint < inp[j].Fingerprint }) - iters = append(iters, v1.NewPeekingIter(v1.NewSliceIter(inp))) + iters = append(iters, iter.NewPeekIter(iter.NewSliceIter(inp))) } heapIter := v1.NewHeapIterator[*logproto.GroupedChunkRefs]( @@ -311,11 +312,11 @@ func mergeSeries(input [][]*logproto.GroupedChunkRefs, buf []*logproto.GroupedCh iters..., ) - dedupeIter := v1.NewDedupingIter[*logproto.GroupedChunkRefs, *logproto.GroupedChunkRefs]( + dedupeIter := iter.NewDedupingIter[*logproto.GroupedChunkRefs, *logproto.GroupedChunkRefs]( // eq func(a, b *logproto.GroupedChunkRefs) bool { return a.Fingerprint == b.Fingerprint }, // from - v1.Identity[*logproto.GroupedChunkRefs], + iter.Identity[*logproto.GroupedChunkRefs], // merge func(a, b *logproto.GroupedChunkRefs) *logproto.GroupedChunkRefs { // TODO(chaudum): Check if we can assume sorted shortrefs here @@ -332,10 +333,10 @@ func mergeSeries(input [][]*logproto.GroupedChunkRefs, buf []*logproto.GroupedCh } }, // iterator - v1.NewPeekingIter(heapIter), + iter.NewPeekIter(heapIter), ) - return v1.CollectInto(dedupeIter, buf) + return iter.CollectInto(dedupeIter, buf) } // mergeChunkSets merges and deduplicates two sorted slices of shortRefs diff --git a/pkg/bloomgateway/multiplexing.go b/pkg/bloomgateway/multiplexing.go index 3520d7b18057e..b814ae23a5a59 100644 --- a/pkg/bloomgateway/multiplexing.go +++ b/pkg/bloomgateway/multiplexing.go @@ -7,6 +7,7 @@ import ( "github.com/prometheus/common/model" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/syntax" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -133,21 +134,21 @@ func (t Task) Copy(series []*logproto.GroupedChunkRefs) Task { func (t Task) RequestIter( tokenizer *v1.NGramTokenizer, -) v1.Iterator[v1.Request] { +) iter.Iterator[v1.Request] { return &requestIterator{ recorder: t.recorder, - series: v1.NewSliceIter(t.series), + series: iter.NewSliceIter(t.series), search: v1.FiltersToBloomTest(tokenizer, t.filters...), channel: t.resCh, curr: v1.Request{}, } } -var _ v1.Iterator[v1.Request] = &requestIterator{} +var _ iter.Iterator[v1.Request] = &requestIterator{} type requestIterator struct { recorder *v1.BloomRecorder - series v1.Iterator[*logproto.GroupedChunkRefs] + series iter.Iterator[*logproto.GroupedChunkRefs] search v1.BloomTest channel chan<- v1.Output curr v1.Request diff --git a/pkg/bloomgateway/multiplexing_test.go b/pkg/bloomgateway/multiplexing_test.go index 5f71d3c9623df..d395d2a315cbb 100644 --- a/pkg/bloomgateway/multiplexing_test.go +++ b/pkg/bloomgateway/multiplexing_test.go @@ -9,6 +9,7 @@ import ( "github.com/prometheus/common/model" "github.com/stretchr/testify/require" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/syntax" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" @@ -103,9 +104,9 @@ func TestTask_RequestIterator(t *testing.T) { tasks := createTasksForRequests(t, tenant, r1, r2, r3) - iters := make([]v1.PeekingIterator[v1.Request], 0, len(tasks)) + iters := make([]v2.PeekIterator[v1.Request], 0, len(tasks)) for _, task := range tasks { - iters = append(iters, v1.NewPeekingIter(task.RequestIter(tokenizer))) + iters = append(iters, v2.NewPeekIter(task.RequestIter(tokenizer))) } // merge the request iterators using the heap sort iterator diff --git a/pkg/bloomgateway/processor.go b/pkg/bloomgateway/processor.go index b0d4f57ca5c15..4dc02fef435f7 100644 --- a/pkg/bloomgateway/processor.go +++ b/pkg/bloomgateway/processor.go @@ -11,6 +11,7 @@ import ( "github.com/grafana/dskit/concurrency" "github.com/grafana/dskit/multierror" + iter "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/config" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" @@ -149,7 +150,7 @@ func (p *processor) processBlock(_ context.Context, bq *bloomshipper.CloseableBl } tokenizer := v1.NewNGramTokenizer(schema.NGramLen(), schema.NGramSkip()) - iters := make([]v1.PeekingIterator[v1.Request], 0, len(tasks)) + iters := make([]iter.PeekIterator[v1.Request], 0, len(tasks)) for _, task := range tasks { // NB(owen-d): can be helpful for debugging, but is noisy @@ -162,7 +163,7 @@ func (p *processor) processBlock(_ context.Context, bq *bloomshipper.CloseableBl // sp.LogKV("process block", blockID, "series", len(task.series)) // } - it := v1.NewPeekingIter(task.RequestIter(tokenizer)) + it := iter.NewPeekIter(task.RequestIter(tokenizer)) iters = append(iters, it) } diff --git a/pkg/chunkenc/dumb_chunk.go b/pkg/chunkenc/dumb_chunk.go index ef8548b1438da..33df4501927bc 100644 --- a/pkg/chunkenc/dumb_chunk.go +++ b/pkg/chunkenc/dumb_chunk.go @@ -147,7 +147,7 @@ func (i *dumbChunkIterator) Next() bool { } } -func (i *dumbChunkIterator) Entry() logproto.Entry { +func (i *dumbChunkIterator) At() logproto.Entry { return i.entries[i.i] } @@ -159,7 +159,7 @@ func (i *dumbChunkIterator) StreamHash() uint64 { return 0 } -func (i *dumbChunkIterator) Error() error { +func (i *dumbChunkIterator) Err() error { return nil } diff --git a/pkg/chunkenc/memchunk.go b/pkg/chunkenc/memchunk.go index f4e27255633dd..b144c1d695e10 100644 --- a/pkg/chunkenc/memchunk.go +++ b/pkg/chunkenc/memchunk.go @@ -1121,7 +1121,7 @@ func (c *MemChunk) Rebound(start, end time.Time, filter filter.Func) (Chunk, err } for itr.Next() { - entry := itr.Entry() + entry := itr.At() if filter != nil && filter(entry.Timestamp, entry.Line, logproto.FromLabelAdaptersToLabels(entry.StructuredMetadata)...) { continue } @@ -1154,14 +1154,14 @@ type encBlock struct { func (b encBlock) Iterator(ctx context.Context, pipeline log.StreamPipeline) iter.EntryIterator { if len(b.b) == 0 { - return iter.NoopIterator + return iter.NoopEntryIterator } return newEntryIterator(ctx, GetReaderPool(b.enc), b.b, pipeline, b.format, b.symbolizer) } func (b encBlock) SampleIterator(ctx context.Context, extractor log.StreamSampleExtractor) iter.SampleIterator { if len(b.b) == 0 { - return iter.NoopIterator + return iter.NoopSampleIterator } return newSampleIterator(ctx, GetReaderPool(b.enc), b.b, b.format, extractor, b.symbolizer) } @@ -1184,7 +1184,7 @@ func (b block) MaxTime() int64 { func (hb *headBlock) Iterator(ctx context.Context, direction logproto.Direction, mint, maxt int64, pipeline log.StreamPipeline) iter.EntryIterator { if hb.IsEmpty() || (maxt < hb.mint || hb.maxt < mint) { - return iter.NoopIterator + return iter.NoopEntryIterator } stats := stats.FromContext(ctx) @@ -1239,7 +1239,7 @@ func (hb *headBlock) Iterator(ctx context.Context, direction logproto.Direction, } if len(streams) == 0 { - return iter.NoopIterator + return iter.NoopEntryIterator } streamsResult := make([]logproto.Stream, 0, len(streams)) for _, stream := range streams { @@ -1250,7 +1250,7 @@ func (hb *headBlock) Iterator(ctx context.Context, direction logproto.Direction, func (hb *headBlock) SampleIterator(ctx context.Context, mint, maxt int64, extractor log.StreamSampleExtractor) iter.SampleIterator { if hb.IsEmpty() || (maxt < hb.mint || hb.maxt < mint) { - return iter.NoopIterator + return iter.NoopSampleIterator } stats := stats.FromContext(ctx) stats.AddHeadChunkLines(int64(len(hb.entries))) @@ -1290,7 +1290,7 @@ func (hb *headBlock) SampleIterator(ctx context.Context, mint, maxt int64, extra stats.SetQueryReferencedStructuredMetadata() } if len(series) == 0 { - return iter.NoopIterator + return iter.NoopSampleIterator } seriesRes := make([]logproto.Series, 0, len(series)) for _, s := range series { @@ -1563,7 +1563,7 @@ func (si *bufferedIterator) moveNext() (int64, []byte, labels.Labels, bool) { return ts, si.buf[:lineSize], si.symbolizer.Lookup(si.symbolsBuf[:nSymbols]), true } -func (si *bufferedIterator) Error() error { return si.err } +func (si *bufferedIterator) Err() error { return si.err } func (si *bufferedIterator) Close() error { if !si.closed { @@ -1609,7 +1609,7 @@ type entryBufferedIterator struct { currLabels log.LabelsResult } -func (e *entryBufferedIterator) Entry() logproto.Entry { +func (e *entryBufferedIterator) At() logproto.Entry { return e.cur } @@ -1645,12 +1645,11 @@ func (e *entryBufferedIterator) Close() error { } func newSampleIterator(ctx context.Context, pool ReaderPool, b []byte, format byte, extractor log.StreamSampleExtractor, symbolizer *symbolizer) iter.SampleIterator { - it := &sampleBufferedIterator{ + return &sampleBufferedIterator{ bufferedIterator: newBufferedIterator(ctx, pool, b, format, symbolizer), extractor: extractor, stats: stats.FromContext(ctx), } - return it } type sampleBufferedIterator struct { @@ -1691,6 +1690,6 @@ func (e *sampleBufferedIterator) Labels() string { return e.currLabels.String() func (e *sampleBufferedIterator) StreamHash() uint64 { return e.extractor.BaseLabels().Hash() } -func (e *sampleBufferedIterator) Sample() logproto.Sample { +func (e *sampleBufferedIterator) At() logproto.Sample { return e.cur } diff --git a/pkg/chunkenc/memchunk_test.go b/pkg/chunkenc/memchunk_test.go index 1d9ef3eea21f7..af8ef89339af7 100644 --- a/pkg/chunkenc/memchunk_test.go +++ b/pkg/chunkenc/memchunk_test.go @@ -194,7 +194,7 @@ func TestBlock(t *testing.T) { idx := 0 for it.Next() { - e := it.Entry() + e := it.At() require.Equal(t, cases[idx].ts, e.Timestamp.UnixNano()) require.Equal(t, cases[idx].str, e.Line) if chunkFormat < ChunkFormatV4 { @@ -211,7 +211,7 @@ func TestBlock(t *testing.T) { idx++ } - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) require.Equal(t, len(cases), idx) @@ -226,14 +226,14 @@ func TestBlock(t *testing.T) { sampleIt := chk.SampleIterator(context.Background(), time.Unix(0, 0), time.Unix(0, math.MaxInt64), countExtractor) idx = 0 for sampleIt.Next() { - s := sampleIt.Sample() + s := sampleIt.At() require.Equal(t, cases[idx].ts, s.Timestamp) require.Equal(t, 1., s.Value) require.NotEmpty(t, s.Hash) idx++ } - require.NoError(t, sampleIt.Error()) + require.NoError(t, sampleIt.Err()) require.NoError(t, sampleIt.Close()) require.Equal(t, len(cases), idx) @@ -243,12 +243,12 @@ func TestBlock(t *testing.T) { idx := 2 for it.Next() { - e := it.Entry() + e := it.At() require.Equal(t, cases[idx].ts, e.Timestamp.UnixNano()) require.Equal(t, cases[idx].str, e.Line) idx++ } - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.Equal(t, 6, idx) }) }) @@ -287,7 +287,7 @@ func TestCorruptChunk(t *testing.T) { for it.Next() { idx++ } - require.Error(t, it.Error(), "case %d", i) + require.Error(t, it.Err(), "case %d", i) require.NoError(t, it.Close()) } }) @@ -321,8 +321,8 @@ func TestReadFormatV1(t *testing.T) { i := int64(0) for it.Next() { - require.Equal(t, i, it.Entry().Timestamp.UnixNano()) - require.Equal(t, testdata.LogString(i), it.Entry().Line) + require.Equal(t, i, it.At().Timestamp.UnixNano()) + require.Equal(t, testdata.LogString(i), it.At().Line) i++ } @@ -354,10 +354,10 @@ func TestRoundtripV2(t *testing.T) { i := int64(0) var data int64 for it.Next() { - require.Equal(t, i, it.Entry().Timestamp.UnixNano()) - require.Equal(t, testdata.LogString(i), it.Entry().Line) + require.Equal(t, i, it.At().Timestamp.UnixNano()) + require.Equal(t, testdata.LogString(i), it.At().Line) - data += int64(len(it.Entry().Line)) + data += int64(len(it.At().Line)) i++ } require.Equal(t, populated, data) @@ -462,7 +462,7 @@ func TestSerialization(t *testing.T) { for i := 0; i < numSamples; i++ { require.True(t, it.Next()) - e := it.Entry() + e := it.At() require.Equal(t, int64(i), e.Timestamp.UnixNano()) require.Equal(t, strconv.Itoa(i), e.Line) if appendWithStructuredMetadata && testData.chunkFormat >= ChunkFormatV4 { @@ -473,7 +473,7 @@ func TestSerialization(t *testing.T) { require.Nil(t, e.StructuredMetadata) } } - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) extractor := func() log.StreamSampleExtractor { ex, err := log.NewLineSampleExtractor(log.CountExtractor, nil, nil, false, false) @@ -487,7 +487,7 @@ func TestSerialization(t *testing.T) { for i := 0; i < numSamples; i++ { require.True(t, sampleIt.Next(), i) - s := sampleIt.Sample() + s := sampleIt.At() require.Equal(t, int64(i), s.Timestamp) require.Equal(t, 1., s.Value) if appendWithStructuredMetadata && testData.chunkFormat >= ChunkFormatV4 { @@ -496,7 +496,7 @@ func TestSerialization(t *testing.T) { require.Equal(t, labels.EmptyLabels().String(), sampleIt.Labels()) } } - require.NoError(t, sampleIt.Error()) + require.NoError(t, sampleIt.Err()) byt2, err := chk.Bytes() require.NoError(t, err) @@ -544,7 +544,7 @@ func TestChunkFilling(t *testing.T) { require.NoError(t, err) i = 0 for it.Next() { - entry := it.Entry() + entry := it.At() require.Equal(t, i, entry.Timestamp.UnixNano()) i++ } @@ -810,7 +810,7 @@ func TestIteratorClose(t *testing.T) { func(iter iter.EntryIterator, t *testing.T) { // close after iterating for iter.Next() { - _ = iter.Entry() + _ = iter.At() } if err := iter.Close(); err != nil { t.Fatal(err) @@ -819,7 +819,7 @@ func TestIteratorClose(t *testing.T) { func(iter iter.EntryIterator, t *testing.T) { // close after a single iteration iter.Next() - _ = iter.Entry() + _ = iter.At() if err := iter.Close(); err != nil { t.Fatal(err) } @@ -909,7 +909,7 @@ func BenchmarkRead(b *testing.B) { panic(err) } for iterator.Next() { - _ = iterator.Entry() + _ = iterator.At() } if err := iterator.Close(); err != nil { b.Fatal(err) @@ -933,7 +933,7 @@ func BenchmarkRead(b *testing.B) { for _, c := range chunks { iterator := c.SampleIterator(ctx, time.Unix(0, 0), time.Now(), countExtractor) for iterator.Next() { - _ = iterator.Sample() + _ = iterator.At() } if err := iterator.Close(); err != nil { b.Fatal(err) @@ -961,7 +961,7 @@ func BenchmarkBackwardIterator(b *testing.B) { panic(err) } for iterator.Next() { - _ = iterator.Entry() + _ = iterator.At() } if err := iterator.Close(); err != nil { b.Fatal(err) @@ -985,7 +985,7 @@ func TestGenerateDataSize(t *testing.T) { panic(err) } for iterator.Next() { - e := iterator.Entry() + e := iterator.At() bytesRead += uint64(len(e.Line)) } if err := iterator.Close(); err != nil { @@ -1022,7 +1022,7 @@ func BenchmarkHeadBlockIterator(b *testing.B) { iter := h.Iterator(context.Background(), logproto.BACKWARD, 0, math.MaxInt64, noopStreamPipeline) for iter.Next() { - _ = iter.Entry() + _ = iter.At() } } }) @@ -1053,7 +1053,7 @@ func BenchmarkHeadBlockSampleIterator(b *testing.B) { iter := h.SampleIterator(context.Background(), 0, math.MaxInt64, countExtractor) for iter.Next() { - _ = iter.Sample() + _ = iter.At() } iter.Close() } @@ -1302,7 +1302,7 @@ func BenchmarkBufferedIteratorLabels(b *testing.B) { for n := 0; n < b.N; n++ { for _, it := range iters { for it.Next() { - streams = append(streams, logproto.Stream{Labels: it.Labels(), Entries: []logproto.Entry{it.Entry()}}) + streams = append(streams, logproto.Stream{Labels: it.Labels(), Entries: []logproto.Entry{it.At()}}) } } } @@ -1337,7 +1337,7 @@ func BenchmarkBufferedIteratorLabels(b *testing.B) { for n := 0; n < b.N; n++ { for _, it := range iters { for it.Next() { - series = append(series, logproto.Series{Labels: it.Labels(), Samples: []logproto.Sample{it.Sample()}}) + series = append(series, logproto.Series{Labels: it.Labels(), Samples: []logproto.Sample{it.At()}}) } } } @@ -1374,7 +1374,7 @@ func Test_HeadIteratorReverse(t *testing.T) { require.NoError(t, err) for it.Next() { total-- - require.Equal(t, total, it.Entry().Timestamp.UnixNano()) + require.Equal(t, total, it.At().Timestamp.UnixNano()) } } @@ -1459,7 +1459,7 @@ func TestMemChunk_Rebound(t *testing.T) { break } - require.Equal(t, originalChunkItr.Entry(), newChunkItr.Entry()) + require.Equal(t, originalChunkItr.At(), newChunkItr.At()) } }) } @@ -1975,8 +1975,8 @@ func TestMemChunk_IteratorWithStructuredMetadata(t *testing.T) { var streams []string var structuredMetadata [][]logproto.LabelAdapter for it.Next() { - require.NoError(t, it.Error()) - e := it.Entry() + require.NoError(t, it.Err()) + e := it.At() lines = append(lines, e.Line) streams = append(streams, it.Labels()) @@ -2012,8 +2012,8 @@ func TestMemChunk_IteratorWithStructuredMetadata(t *testing.T) { var sumValues int var streams []string for it.Next() { - require.NoError(t, it.Error()) - e := it.Sample() + require.NoError(t, it.Err()) + e := it.At() sumValues += int(e.Value) streams = append(streams, it.Labels()) } diff --git a/pkg/chunkenc/unordered.go b/pkg/chunkenc/unordered.go index 807f80b2c0f87..683a4f17e2ad6 100644 --- a/pkg/chunkenc/unordered.go +++ b/pkg/chunkenc/unordered.go @@ -288,7 +288,7 @@ func (hb *unorderedHeadBlock) Iterator(ctx context.Context, direction logproto.D stats.FromContext(ctx).SetQueryReferencedStructuredMetadata() } if len(streams) == 0 { - return iter.NoopIterator + return iter.NoopEntryIterator } streamsResult := make([]logproto.Stream, 0, len(streams)) for _, stream := range streams { @@ -345,7 +345,7 @@ func (hb *unorderedHeadBlock) SampleIterator( } if len(series) == 0 { - return iter.NoopIterator + return iter.NoopSampleIterator } seriesRes := make([]logproto.Series, 0, len(series)) for _, s := range series { diff --git a/pkg/chunkenc/unordered_test.go b/pkg/chunkenc/unordered_test.go index 43c07d0f835f3..8a3420965bdb7 100644 --- a/pkg/chunkenc/unordered_test.go +++ b/pkg/chunkenc/unordered_test.go @@ -25,7 +25,7 @@ func iterEq(t *testing.T, exp []entry, got iter.EntryIterator) { Timestamp: time.Unix(0, exp[i].t), Line: exp[i].s, StructuredMetadata: logproto.FromLabelsToLabelAdapters(exp[i].structuredMetadata), - }, got.Entry()) + }, got.At()) require.Equal(t, exp[i].structuredMetadata.String(), got.Labels()) i++ } @@ -486,10 +486,10 @@ func TestUnorderedChunkIterators(t *testing.T) { require.Equal(t, true, forward.Next()) require.Equal(t, true, backward.Next()) require.Equal(t, true, smpl.Next()) - require.Equal(t, time.Unix(int64(i), 0), forward.Entry().Timestamp) - require.Equal(t, time.Unix(int64(99-i), 0), backward.Entry().Timestamp) - require.Equal(t, float64(1), smpl.Sample().Value) - require.Equal(t, time.Unix(int64(i), 0).UnixNano(), smpl.Sample().Timestamp) + require.Equal(t, time.Unix(int64(i), 0), forward.At().Timestamp) + require.Equal(t, time.Unix(int64(99-i), 0), backward.At().Timestamp) + require.Equal(t, float64(1), smpl.At().Value) + require.Equal(t, time.Unix(int64(i), 0).UnixNano(), smpl.At().Timestamp) } require.Equal(t, false, forward.Next()) require.Equal(t, false, backward.Next()) @@ -530,7 +530,7 @@ func BenchmarkUnorderedRead(b *testing.B) { panic(err) } for iterator.Next() { - _ = iterator.Entry() + _ = iterator.At() } if err := iterator.Close(); err != nil { b.Fatal(err) @@ -546,7 +546,7 @@ func BenchmarkUnorderedRead(b *testing.B) { for n := 0; n < b.N; n++ { iterator := tc.c.SampleIterator(context.Background(), time.Unix(0, 0), time.Unix(0, math.MaxInt64), countExtractor) for iterator.Next() { - _ = iterator.Sample() + _ = iterator.At() } if err := iterator.Close(); err != nil { b.Fatal(err) @@ -568,7 +568,7 @@ func TestUnorderedIteratorCountsAllEntries(t *testing.T) { panic(err) } for iterator.Next() { - next := iterator.Entry().Timestamp.UnixNano() + next := iterator.At().Timestamp.UnixNano() require.GreaterOrEqual(t, next, i) i = next ct++ @@ -582,10 +582,10 @@ func TestUnorderedIteratorCountsAllEntries(t *testing.T) { i = 0 smpl := c.SampleIterator(context.Background(), time.Unix(0, 0), time.Unix(0, math.MaxInt64), countExtractor) for smpl.Next() { - next := smpl.Sample().Timestamp + next := smpl.At().Timestamp require.GreaterOrEqual(t, next, i) i = next - ct += int(smpl.Sample().Value) + ct += int(smpl.At().Value) } require.Equal(t, c.Size(), ct) diff --git a/pkg/compactor/retention/retention_test.go b/pkg/compactor/retention/retention_test.go index a3f157dc77743..b140b3661f4d4 100644 --- a/pkg/compactor/retention/retention_test.go +++ b/pkg/compactor/retention/retention_test.go @@ -562,7 +562,7 @@ func TestChunkRewriter(t *testing.T) { Timestamp: curr.Time(), Line: curr.String(), StructuredMetadata: logproto.FromLabelsToLabelAdapters(expectedStructuredMetadata), - }, newChunkItr.Entry()) + }, newChunkItr.At()) require.Equal(t, expectedStructuredMetadata.String(), newChunkItr.Labels()) } } diff --git a/pkg/indexgateway/gateway.go b/pkg/indexgateway/gateway.go index 7b49490a012ef..052575647951e 100644 --- a/pkg/indexgateway/gateway.go +++ b/pkg/indexgateway/gateway.go @@ -19,6 +19,7 @@ import ( "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/syntax" "github.com/grafana/loki/v3/pkg/logqlmodel/stats" @@ -613,14 +614,14 @@ func accumulateChunksToShards( for i := range filteredChks { for j < len(chks) { switch filteredChks[i].Cmp(chks[j]) { - case v1.Less: + case iter.Less: // this chunk is not in the queried index, continue checking other chunks continue outer - case v1.Greater: + case iter.Greater: // next chunk in index but didn't pass filter; continue j++ continue - case v1.Eq: + case iter.Eq: // a match; set the sizing info filteredChks[i].KB = chks[j].KB filteredChks[i].Entries = chks[j].Entries @@ -679,32 +680,32 @@ type refWithSizingInfo struct { } // careful: only checks from,through,checksum -func (r refWithSizingInfo) Cmp(chk tsdb_index.ChunkMeta) v1.Ord { +func (r refWithSizingInfo) Cmp(chk tsdb_index.ChunkMeta) iter.Ord { ref := *r.ref chkFrom := model.Time(chk.MinTime) if ref.From != chkFrom { if ref.From < chkFrom { - return v1.Less + return iter.Less } - return v1.Greater + return iter.Greater } chkThrough := model.Time(chk.MaxTime) if ref.Through != chkThrough { if ref.Through < chkThrough { - return v1.Less + return iter.Less } - return v1.Greater + return iter.Greater } if ref.Checksum != chk.Checksum { if ref.Checksum < chk.Checksum { - return v1.Less + return iter.Less } - return v1.Greater + return iter.Greater } - return v1.Eq + return iter.Eq } type failingIndexClient struct{} diff --git a/pkg/indexgateway/gateway_test.go b/pkg/indexgateway/gateway_test.go index aa17482776e73..cf5cd7256486e 100644 --- a/pkg/indexgateway/gateway_test.go +++ b/pkg/indexgateway/gateway_test.go @@ -14,8 +14,8 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" - v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/chunk" "github.com/grafana/loki/v3/pkg/storage/config" "github.com/grafana/loki/v3/pkg/storage/stores/series/index" @@ -307,7 +307,7 @@ func TestRefWithSizingInfo(t *testing.T) { desc string a refWithSizingInfo b tsdb_index.ChunkMeta - exp v1.Ord + exp v2.Ord }{ { desc: "less by from", @@ -319,7 +319,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MinTime: 2, }, - exp: v1.Less, + exp: v2.Less, }, { desc: "eq by from", @@ -331,7 +331,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MinTime: 1, }, - exp: v1.Eq, + exp: v2.Eq, }, { desc: "gt by from", @@ -343,7 +343,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MinTime: 1, }, - exp: v1.Greater, + exp: v2.Greater, }, { desc: "less by through", @@ -355,7 +355,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MaxTime: 2, }, - exp: v1.Less, + exp: v2.Less, }, { desc: "eq by through", @@ -367,7 +367,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MaxTime: 2, }, - exp: v1.Eq, + exp: v2.Eq, }, { desc: "gt by through", @@ -379,7 +379,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ MaxTime: 1, }, - exp: v1.Greater, + exp: v2.Greater, }, { desc: "less by checksum", @@ -391,7 +391,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ Checksum: 2, }, - exp: v1.Less, + exp: v2.Less, }, { desc: "eq by checksum", @@ -403,7 +403,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ Checksum: 2, }, - exp: v1.Eq, + exp: v2.Eq, }, { desc: "gt by checksum", @@ -415,7 +415,7 @@ func TestRefWithSizingInfo(t *testing.T) { b: tsdb_index.ChunkMeta{ Checksum: 1, }, - exp: v1.Greater, + exp: v2.Greater, }, } { t.Run(tc.desc, func(t *testing.T) { diff --git a/pkg/ingester/checkpoint_test.go b/pkg/ingester/checkpoint_test.go index 1b0c76466dc15..5a816a3b779df 100644 --- a/pkg/ingester/checkpoint_test.go +++ b/pkg/ingester/checkpoint_test.go @@ -484,7 +484,7 @@ func Test_SeriesIterator(t *testing.T) { Labels: logproto.FromLabelAdaptersToLabels(iter.Stream().Labels).String(), } for it.Next() { - stream.Entries = append(stream.Entries, it.Entry()) + stream.Entries = append(stream.Entries, it.At()) } require.NoError(t, it.Close()) streams = append(streams, stream) diff --git a/pkg/ingester/chunk_test.go b/pkg/ingester/chunk_test.go index 9ceb3c740926e..f6a16731e6d44 100644 --- a/pkg/ingester/chunk_test.go +++ b/pkg/ingester/chunk_test.go @@ -19,25 +19,25 @@ import ( func testIteratorForward(t *testing.T, iter iter.EntryIterator, from, through int64) { i := from for iter.Next() { - entry := iter.Entry() + entry := iter.At() require.Equal(t, time.Unix(i, 0).Unix(), entry.Timestamp.Unix()) require.Equal(t, fmt.Sprintf("line %d", i), entry.Line) i++ } require.Equal(t, through, i) - require.NoError(t, iter.Error()) + require.NoError(t, iter.Err()) } func testIteratorBackward(t *testing.T, iter iter.EntryIterator, from, through int64) { i := through - 1 for iter.Next() { - entry := iter.Entry() + entry := iter.At() require.Equal(t, time.Unix(i, 0).Unix(), entry.Timestamp.Unix()) require.Equal(t, fmt.Sprintf("line %d", i), entry.Line) i-- } require.Equal(t, from-1, i) - require.NoError(t, iter.Error()) + require.NoError(t, iter.Err()) } func TestIterator(t *testing.T) { diff --git a/pkg/ingester/flush_test.go b/pkg/ingester/flush_test.go index 1287be3d4bfdb..69462a3d352a5 100644 --- a/pkg/ingester/flush_test.go +++ b/pkg/ingester/flush_test.go @@ -588,8 +588,8 @@ func buildStreamsFromChunk(t *testing.T, lbs string, chk chunkenc.Chunk) logprot Labels: lbs, } for it.Next() { - stream.Entries = append(stream.Entries, it.Entry()) + stream.Entries = append(stream.Entries, it.At()) } - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) return stream } diff --git a/pkg/ingester/ingester_test.go b/pkg/ingester/ingester_test.go index 570452af44eb0..17daa7b3ba580 100644 --- a/pkg/ingester/ingester_test.go +++ b/pkg/ingester/ingester_test.go @@ -1043,8 +1043,8 @@ func Test_DedupeIngester(t *testing.T) { actualHashes := []uint64{} for j := 0; j < int(streamCount); j++ { require.True(t, it.Next()) - require.Equal(t, fmt.Sprintf("line %d", i), it.Entry().Line) - require.Equal(t, i, it.Entry().Timestamp.UnixNano()) + require.Equal(t, fmt.Sprintf("line %d", i), it.At().Line) + require.Equal(t, i, it.At().Timestamp.UnixNano()) require.Equal(t, `{bar="", foo="bar"}`, it.Labels()) actualHashes = append(actualHashes, it.StreamHash()) } @@ -1052,7 +1052,7 @@ func Test_DedupeIngester(t *testing.T) { require.Equal(t, streamHashes, actualHashes) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("forward log", func(t *testing.T) { iterators := make([]iter.EntryIterator, 0, len(ingesterSet)) @@ -1073,8 +1073,8 @@ func Test_DedupeIngester(t *testing.T) { actualHashes := []uint64{} for j := 0; j < int(streamCount); j++ { require.True(t, it.Next()) - require.Equal(t, fmt.Sprintf("line %d", i), it.Entry().Line) - require.Equal(t, i, it.Entry().Timestamp.UnixNano()) + require.Equal(t, fmt.Sprintf("line %d", i), it.At().Line) + require.Equal(t, i, it.At().Timestamp.UnixNano()) require.Equal(t, `{bar="", foo="bar"}`, it.Labels()) actualHashes = append(actualHashes, it.StreamHash()) } @@ -1082,7 +1082,7 @@ func Test_DedupeIngester(t *testing.T) { require.Equal(t, streamHashes, actualHashes) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("sum by metrics", func(t *testing.T) { iterators := make([]iter.SampleIterator, 0, len(ingesterSet)) @@ -1109,8 +1109,8 @@ func Test_DedupeIngester(t *testing.T) { actualHashes := []uint64{} for j := 0; j < int(streamCount); j++ { require.True(t, it.Next()) - require.Equal(t, float64(1), it.Sample().Value) - require.Equal(t, i, it.Sample().Timestamp) + require.Equal(t, float64(1), it.At().Value) + require.Equal(t, i, it.At().Timestamp) labels = append(labels, it.Labels()) actualHashes = append(actualHashes, it.StreamHash()) } @@ -1120,7 +1120,7 @@ func Test_DedupeIngester(t *testing.T) { require.Equal(t, streamHashes, actualHashes) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("sum metrics", func(t *testing.T) { iterators := make([]iter.SampleIterator, 0, len(ingesterSet)) @@ -1141,8 +1141,8 @@ func Test_DedupeIngester(t *testing.T) { actualHashes := []uint64{} for j := 0; j < int(streamCount); j++ { require.True(t, it.Next()) - require.Equal(t, float64(1), it.Sample().Value) - require.Equal(t, i, it.Sample().Timestamp) + require.Equal(t, float64(1), it.At().Value) + require.Equal(t, i, it.At().Timestamp) require.Equal(t, "{}", it.Labels()) actualHashes = append(actualHashes, it.StreamHash()) } @@ -1150,7 +1150,7 @@ func Test_DedupeIngester(t *testing.T) { require.Equal(t, streamHashes, actualHashes) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) } @@ -1205,12 +1205,12 @@ func Test_DedupeIngesterParser(t *testing.T) { for j := 0; j < streamCount; j++ { for k := 0; k < 2; k++ { // 2 line per entry require.True(t, it.Next()) - require.Equal(t, int64(i), it.Entry().Timestamp.UnixNano()) + require.Equal(t, int64(i), it.At().Timestamp.UnixNano()) } } } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("forward log", func(t *testing.T) { @@ -1235,12 +1235,12 @@ func Test_DedupeIngesterParser(t *testing.T) { for j := 0; j < streamCount; j++ { for k := 0; k < 2; k++ { // 2 line per entry require.True(t, it.Next()) - require.Equal(t, int64(i), it.Entry().Timestamp.UnixNano()) + require.Equal(t, int64(i), it.At().Timestamp.UnixNano()) } } } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("no sum metrics", func(t *testing.T) { iterators := make([]iter.SampleIterator, 0, len(ingesterSet)) @@ -1262,13 +1262,13 @@ func Test_DedupeIngesterParser(t *testing.T) { for j := 0; j < streamCount; j++ { for k := 0; k < 2; k++ { // 2 line per entry require.True(t, it.Next()) - require.Equal(t, float64(1), it.Sample().Value) - require.Equal(t, int64(i), it.Sample().Timestamp) + require.Equal(t, float64(1), it.At().Value) + require.Equal(t, int64(i), it.At().Timestamp) } } } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) t.Run("sum metrics", func(t *testing.T) { iterators := make([]iter.SampleIterator, 0, len(ingesterSet)) @@ -1290,13 +1290,13 @@ func Test_DedupeIngesterParser(t *testing.T) { for j := 0; j < streamCount; j++ { for k := 0; k < 2; k++ { // 2 line per entry require.True(t, it.Next()) - require.Equal(t, float64(1), it.Sample().Value) - require.Equal(t, int64(i), it.Sample().Timestamp) + require.Equal(t, float64(1), it.At().Value) + require.Equal(t, int64(i), it.At().Timestamp) } } } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) }) } diff --git a/pkg/ingester/instance_test.go b/pkg/ingester/instance_test.go index 80074f6391e90..7a2647a3bb015 100644 --- a/pkg/ingester/instance_test.go +++ b/pkg/ingester/instance_test.go @@ -681,7 +681,7 @@ func Test_ChunkFilter(t *testing.T) { defer it.Close() for it.Next() { - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) lbs, err := syntax.ParseLabels(it.Labels()) require.NoError(t, err) require.NotEqual(t, "dispatcher", lbs.Get("log_stream")) @@ -721,7 +721,7 @@ func Test_PipelineWrapper(t *testing.T) { for it.Next() { // Consume the iterator - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } require.Equal(t, "test-user", wrapper.tenant) @@ -762,7 +762,7 @@ func Test_PipelineWrapper_disabled(t *testing.T) { for it.Next() { // Consume the iterator - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } require.Equal(t, "", wrapper.tenant) @@ -853,7 +853,7 @@ func Test_ExtractorWrapper(t *testing.T) { for it.Next() { // Consume the iterator - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } require.Equal(t, `sum(count_over_time({job="3"}[1m]))`, wrapper.query) @@ -888,7 +888,7 @@ func Test_ExtractorWrapper_disabled(t *testing.T) { for it.Next() { // Consume the iterator - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } require.Equal(t, ``, wrapper.query) @@ -990,7 +990,7 @@ func Test_QueryWithDelete(t *testing.T) { var logs []string for it.Next() { - logs = append(logs, it.Entry().Line) + logs = append(logs, it.At().Line) } require.Equal(t, logs, []string{`msg="dispatcher_7"`}) @@ -1033,7 +1033,7 @@ func Test_QuerySampleWithDelete(t *testing.T) { var samples []float64 for it.Next() { - samples = append(samples, it.Sample().Value) + samples = append(samples, it.At().Value) } require.Equal(t, samples, []float64{1.}) diff --git a/pkg/ingester/stream_test.go b/pkg/ingester/stream_test.go index 68974ae016b39..3bbd091b25c5c 100644 --- a/pkg/ingester/stream_test.go +++ b/pkg/ingester/stream_test.go @@ -456,8 +456,8 @@ func TestUnorderedPush(t *testing.T) { require.Nil(t, err) for _, x := range exp { require.Equal(t, true, sItr.Next()) - require.Equal(t, x.Timestamp, time.Unix(0, sItr.Sample().Timestamp)) - require.Equal(t, float64(1), sItr.Sample().Value) + require.Equal(t, x.Timestamp, time.Unix(0, sItr.At().Timestamp)) + require.Equal(t, float64(1), sItr.At().Value) } require.Equal(t, false, sItr.Next()) } @@ -599,8 +599,8 @@ func TestReplayAppendIgnoresValidityWindow(t *testing.T) { func iterEq(t *testing.T, exp []logproto.Entry, got iter.EntryIterator) { var i int for got.Next() { - require.Equal(t, exp[i].Timestamp, got.Entry().Timestamp, "failed on the (%d) ts", i) - require.Equal(t, exp[i].Line, got.Entry().Line) + require.Equal(t, exp[i].Timestamp, got.At().Timestamp, "failed on the (%d) ts", i) + require.Equal(t, exp[i].Line, got.At().Line) i++ } require.Equal(t, i, len(exp), "incorrect number of entries expected") diff --git a/pkg/iter/cache.go b/pkg/iter/cache.go index a6e12dffbce20..3066bdbb67b29 100644 --- a/pkg/iter/cache.go +++ b/pkg/iter/cache.go @@ -48,12 +48,12 @@ func (it *cachedIterator) consumeWrapped() bool { // we're done with the base iterator. if !ok { it.closeErr = it.Wrapped().Close() - it.iterErr = it.Wrapped().Error() + it.iterErr = it.Wrapped().Err() it.wrapped = nil return false } // we're caching entries - it.cache = append(it.cache, entryWithLabels{Entry: it.Wrapped().Entry(), labels: it.Wrapped().Labels(), streamHash: it.Wrapped().StreamHash()}) + it.cache = append(it.cache, entryWithLabels{Entry: it.Wrapped().At(), labels: it.Wrapped().Labels(), streamHash: it.Wrapped().StreamHash()}) it.curr++ return true } @@ -72,7 +72,7 @@ func (it *cachedIterator) Next() bool { return true } -func (it *cachedIterator) Entry() logproto.Entry { +func (it *cachedIterator) At() logproto.Entry { if len(it.cache) == 0 || it.curr < 0 || it.curr >= len(it.cache) { return logproto.Entry{} } @@ -94,7 +94,7 @@ func (it *cachedIterator) StreamHash() uint64 { return it.cache[it.curr].streamHash } -func (it *cachedIterator) Error() error { return it.iterErr } +func (it *cachedIterator) Err() error { return it.iterErr } func (it *cachedIterator) Close() error { it.Reset() @@ -145,12 +145,12 @@ func (it *cachedSampleIterator) consumeWrapped() bool { // we're done with the base iterator. if !ok { it.closeErr = it.Wrapped().Close() - it.iterErr = it.Wrapped().Error() + it.iterErr = it.Wrapped().Err() it.wrapped = nil return false } // we're caching entries - it.cache = append(it.cache, sampleWithLabels{Sample: it.Wrapped().Sample(), labels: it.Wrapped().Labels(), streamHash: it.Wrapped().StreamHash()}) + it.cache = append(it.cache, sampleWithLabels{Sample: it.Wrapped().At(), labels: it.Wrapped().Labels(), streamHash: it.Wrapped().StreamHash()}) it.curr++ return true } @@ -169,7 +169,7 @@ func (it *cachedSampleIterator) Next() bool { return true } -func (it *cachedSampleIterator) Sample() logproto.Sample { +func (it *cachedSampleIterator) At() logproto.Sample { if len(it.cache) == 0 || it.curr < 0 || it.curr >= len(it.cache) { return logproto.Sample{} } @@ -190,7 +190,7 @@ func (it *cachedSampleIterator) StreamHash() uint64 { return it.cache[it.curr].streamHash } -func (it *cachedSampleIterator) Error() error { return it.iterErr } +func (it *cachedSampleIterator) Err() error { return it.iterErr } func (it *cachedSampleIterator) Close() error { it.Reset() diff --git a/pkg/iter/cache_test.go b/pkg/iter/cache_test.go index 23ee9cb7d9954..3d5c7340a43e8 100644 --- a/pkg/iter/cache_test.go +++ b/pkg/iter/cache_test.go @@ -23,16 +23,16 @@ func Test_CachedIterator(t *testing.T) { assert := func() { require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) + require.Equal(t, logproto.Entry{}, c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[0], c.Entry()) + require.Equal(t, stream.Entries[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[1], c.Entry()) + require.Equal(t, stream.Entries[1], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[2], c.Entry()) + require.Equal(t, stream.Entries[2], c.At()) require.Equal(t, false, c.Next()) - require.NoError(t, c.Error()) - require.Equal(t, stream.Entries[2], c.Entry()) + require.NoError(t, c.Err()) + require.Equal(t, stream.Entries[2], c.At()) require.Equal(t, false, c.Next()) } @@ -45,30 +45,30 @@ func Test_CachedIterator(t *testing.T) { } func Test_EmptyCachedIterator(t *testing.T) { - c := NewCachedIterator(NoopIterator, 0) + c := NewCachedIterator(NoopEntryIterator, 0) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) + require.Equal(t, logproto.Entry{}, c.At()) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) + require.Equal(t, logproto.Entry{}, c.At()) require.Equal(t, nil, c.Close()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) + require.Equal(t, logproto.Entry{}, c.At()) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) + require.Equal(t, logproto.Entry{}, c.At()) } func Test_ErrorCachedIterator(t *testing.T) { - c := NewCachedIterator(&errorIter{}, 0) + c := NewCachedIterator(ErrorEntryIterator, 0) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Entry{}, c.Entry()) - require.Equal(t, errors.New("error"), c.Error()) + require.Equal(t, logproto.Entry{}, c.At()) + require.Equal(t, errors.New("error"), c.Err()) require.Equal(t, errors.New("close"), c.Close()) } @@ -84,19 +84,19 @@ func Test_CachedIteratorResetNotExhausted(t *testing.T) { c := NewCachedIterator(NewStreamIterator(stream), 3) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[0], c.Entry()) + require.Equal(t, stream.Entries[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[1], c.Entry()) + require.Equal(t, stream.Entries[1], c.At()) c.Reset() require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[0], c.Entry()) + require.Equal(t, stream.Entries[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[1], c.Entry()) + require.Equal(t, stream.Entries[1], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[2], c.Entry()) + require.Equal(t, stream.Entries[2], c.At()) require.Equal(t, false, c.Next()) - require.NoError(t, c.Error()) - require.Equal(t, stream.Entries[2], c.Entry()) + require.NoError(t, c.Err()) + require.Equal(t, stream.Entries[2], c.At()) require.Equal(t, false, c.Next()) // Close the iterator reset it to the beginning. @@ -114,14 +114,14 @@ func Test_CachedIteratorResetExhausted(t *testing.T) { c := NewCachedIterator(NewStreamIterator(stream), 3) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[0], c.Entry()) + require.Equal(t, stream.Entries[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[1], c.Entry()) + require.Equal(t, stream.Entries[1], c.At()) c.Reset() require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[0], c.Entry()) + require.Equal(t, stream.Entries[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, stream.Entries[1], c.Entry()) + require.Equal(t, stream.Entries[1], c.At()) require.Equal(t, false, c.Next()) // Close the iterator reset it to the beginning. @@ -141,16 +141,16 @@ func Test_CachedSampleIterator(t *testing.T) { assert := func() { require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) + require.Equal(t, logproto.Sample{}, c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[0], c.Sample()) + require.Equal(t, series.Samples[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[1], c.Sample()) + require.Equal(t, series.Samples[1], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[2], c.Sample()) + require.Equal(t, series.Samples[2], c.At()) require.Equal(t, false, c.Next()) - require.NoError(t, c.Error()) - require.Equal(t, series.Samples[2], c.Sample()) + require.NoError(t, c.Err()) + require.Equal(t, series.Samples[2], c.At()) require.Equal(t, false, c.Next()) } @@ -174,19 +174,19 @@ func Test_CachedSampleIteratorResetNotExhausted(t *testing.T) { c := NewCachedSampleIterator(NewSeriesIterator(series), 3) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[0], c.Sample()) + require.Equal(t, series.Samples[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[1], c.Sample()) + require.Equal(t, series.Samples[1], c.At()) c.Reset() require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[0], c.Sample()) + require.Equal(t, series.Samples[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[1], c.Sample()) + require.Equal(t, series.Samples[1], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[2], c.Sample()) + require.Equal(t, series.Samples[2], c.At()) require.Equal(t, false, c.Next()) - require.NoError(t, c.Error()) - require.Equal(t, series.Samples[2], c.Sample()) + require.NoError(t, c.Err()) + require.Equal(t, series.Samples[2], c.At()) require.Equal(t, false, c.Next()) // Close the iterator reset it to the beginning. @@ -204,14 +204,14 @@ func Test_CachedSampleIteratorResetExhausted(t *testing.T) { c := NewCachedSampleIterator(NewSeriesIterator(series), 3) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[0], c.Sample()) + require.Equal(t, series.Samples[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[1], c.Sample()) + require.Equal(t, series.Samples[1], c.At()) c.Reset() require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[0], c.Sample()) + require.Equal(t, series.Samples[0], c.At()) require.Equal(t, true, c.Next()) - require.Equal(t, series.Samples[1], c.Sample()) + require.Equal(t, series.Samples[1], c.At()) require.Equal(t, false, c.Next()) // Close the iterator reset it to the beginning. @@ -219,39 +219,29 @@ func Test_CachedSampleIteratorResetExhausted(t *testing.T) { } func Test_EmptyCachedSampleIterator(t *testing.T) { - c := NewCachedSampleIterator(NoopIterator, 0) + c := NewCachedSampleIterator(NoopSampleIterator, 0) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) + require.Equal(t, logproto.Sample{}, c.At()) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) + require.Equal(t, logproto.Sample{}, c.At()) require.Equal(t, nil, c.Close()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) + require.Equal(t, logproto.Sample{}, c.At()) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) + require.Equal(t, logproto.Sample{}, c.At()) } func Test_ErrorCachedSampleIterator(t *testing.T) { - c := NewCachedSampleIterator(&errorIter{}, 0) + c := NewCachedSampleIterator(ErrorSampleIterator, 0) require.Equal(t, false, c.Next()) require.Equal(t, "", c.Labels()) - require.Equal(t, logproto.Sample{}, c.Sample()) - require.Equal(t, errors.New("error"), c.Error()) + require.Equal(t, logproto.Sample{}, c.At()) + require.Equal(t, errors.New("error"), c.Err()) require.Equal(t, errors.New("close"), c.Close()) } - -type errorIter struct{} - -func (errorIter) Next() bool { return false } -func (errorIter) Error() error { return errors.New("error") } -func (errorIter) Labels() string { return "" } -func (errorIter) StreamHash() uint64 { return 0 } -func (errorIter) Entry() logproto.Entry { return logproto.Entry{} } -func (errorIter) Sample() logproto.Sample { return logproto.Sample{} } -func (errorIter) Close() error { return errors.New("close") } diff --git a/pkg/iter/categorized_labels_iterator.go b/pkg/iter/categorized_labels_iterator.go index c91aa49911163..81c1b8f00ac75 100644 --- a/pkg/iter/categorized_labels_iterator.go +++ b/pkg/iter/categorized_labels_iterator.go @@ -5,13 +5,12 @@ import ( "github.com/prometheus/prometheus/model/labels" - "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/syntax" ) type categorizeLabelsIterator struct { EntryIterator - currEntry logproto.Entry + currStreamLabels string currHash uint64 currErr error @@ -28,8 +27,8 @@ func (c *categorizeLabelsIterator) Next() bool { return false } - c.currEntry = c.Entry() - if len(c.currEntry.StructuredMetadata) == 0 && len(c.currEntry.Parsed) == 0 { + currEntry := c.At() + if len(currEntry.StructuredMetadata) == 0 && len(currEntry.Parsed) == 0 { c.currStreamLabels = c.EntryIterator.Labels() c.currHash = c.EntryIterator.StreamHash() return true @@ -44,10 +43,10 @@ func (c *categorizeLabelsIterator) Next() bool { } builder := labels.NewBuilder(lbls) - for _, label := range c.currEntry.StructuredMetadata { + for _, label := range currEntry.StructuredMetadata { builder.Del(label.Name) } - for _, label := range c.currEntry.Parsed { + for _, label := range currEntry.Parsed { builder.Del(label.Name) } @@ -58,7 +57,7 @@ func (c *categorizeLabelsIterator) Next() bool { return true } -func (c *categorizeLabelsIterator) Error() error { +func (c *categorizeLabelsIterator) Err() error { return c.currErr } diff --git a/pkg/iter/categorized_labels_iterator_test.go b/pkg/iter/categorized_labels_iterator_test.go index 790ca5413aba6..0043053fdd1c1 100644 --- a/pkg/iter/categorized_labels_iterator_test.go +++ b/pkg/iter/categorized_labels_iterator_test.go @@ -127,8 +127,8 @@ func TestNewCategorizeLabelsIterator(t *testing.T) { streamsEntries := make(map[string][]logproto.Entry) for itr.Next() { - streamsEntries[itr.Labels()] = append(streamsEntries[itr.Labels()], itr.Entry()) - require.NoError(t, itr.Error()) + streamsEntries[itr.Labels()] = append(streamsEntries[itr.Labels()], itr.At()) + require.NoError(t, itr.Err()) } var streams []logproto.Stream diff --git a/pkg/iter/entry_iterator.go b/pkg/iter/entry_iterator.go index 43394fbfe1333..b0b5a4635d1e9 100644 --- a/pkg/iter/entry_iterator.go +++ b/pkg/iter/entry_iterator.go @@ -15,13 +15,6 @@ import ( "github.com/grafana/loki/v3/pkg/util/loser" ) -// EntryIterator iterates over entries in time-order. -type EntryIterator interface { - Iterator - Entry() logproto.Entry -} - -// streamIterator iterates over entries in a stream. type streamIterator struct { i int stream logproto.Stream @@ -40,7 +33,7 @@ func (i *streamIterator) Next() bool { return i.i < len(i.stream.Entries) } -func (i *streamIterator) Error() error { +func (i *streamIterator) Err() error { return nil } @@ -48,9 +41,11 @@ func (i *streamIterator) Labels() string { return i.stream.Labels } -func (i *streamIterator) StreamHash() uint64 { return i.stream.Hash } +func (i *streamIterator) StreamHash() uint64 { + return i.stream.Hash +} -func (i *streamIterator) Entry() logproto.Entry { +func (i *streamIterator) At() logproto.Entry { return i.stream.Entries[i.i] } @@ -92,7 +87,7 @@ func NewMergeEntryIterator(ctx context.Context, is []EntryIterator, direction lo } func (i *mergeEntryIterator) closeEntry(e EntryIterator) { - if err := e.Error(); err != nil { + if err := e.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", e.Close) @@ -129,7 +124,7 @@ func (i *mergeEntryIterator) fillBuffer() { // Entries with identical timestamp and line are removed as duplicates. for { next := i.tree.Winner() - entry := next.Entry() + entry := next.At() i.buffer = append(i.buffer, entryWithLabels{ Entry: entry, labels: next.Labels(), @@ -175,7 +170,7 @@ func (i *mergeEntryIterator) nextFromBuffer() { i.buffer = i.buffer[1:] } -func (i *mergeEntryIterator) Entry() logproto.Entry { +func (i *mergeEntryIterator) At() logproto.Entry { return i.currEntry.Entry } @@ -185,7 +180,7 @@ func (i *mergeEntryIterator) Labels() string { func (i *mergeEntryIterator) StreamHash() uint64 { return i.currEntry.streamHash } -func (i *mergeEntryIterator) Error() error { +func (i *mergeEntryIterator) Err() error { switch len(i.errs) { case 0: return nil @@ -199,7 +194,7 @@ func (i *mergeEntryIterator) Error() error { func (i *mergeEntryIterator) Close() error { i.tree.Close() i.buffer = nil - return i.Error() + return i.Err() } func (i *mergeEntryIterator) Peek() time.Time { @@ -232,7 +227,7 @@ type entrySortIterator struct { // When timestamp is equal, the iterator sorts samples by their label alphabetically. func NewSortEntryIterator(is []EntryIterator, direction logproto.Direction) EntryIterator { if len(is) == 0 { - return NoopIterator + return NoopEntryIterator } if len(is) == 1 { return is[0] @@ -265,7 +260,7 @@ type sortFields struct { func sortFieldsAt(i EntryIterator) sortFields { return sortFields{ - timeNanos: i.Entry().Timestamp.UnixNano(), + timeNanos: i.At().Timestamp.UnixNano(), labels: i.Labels(), streamHash: i.StreamHash(), } @@ -295,7 +290,7 @@ func lessDescending(e1, e2 sortFields) bool { } func (i *entrySortIterator) closeEntry(e EntryIterator) { - if err := e.Error(); err != nil { + if err := e.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", e.Close) @@ -307,13 +302,13 @@ func (i *entrySortIterator) Next() bool { return false } next := i.tree.Winner() - i.currEntry.Entry = next.Entry() + i.currEntry.Entry = next.At() i.currEntry.labels = next.Labels() i.currEntry.streamHash = next.StreamHash() return true } -func (i *entrySortIterator) Entry() logproto.Entry { +func (i *entrySortIterator) At() logproto.Entry { return i.currEntry.Entry } @@ -325,7 +320,7 @@ func (i *entrySortIterator) StreamHash() uint64 { return i.currEntry.streamHash } -func (i *entrySortIterator) Error() error { +func (i *entrySortIterator) Err() error { switch len(i.errs) { case 0: return nil @@ -338,7 +333,7 @@ func (i *entrySortIterator) Error() error { func (i *entrySortIterator) Close() error { i.tree.Close() - return i.Error() + return i.Err() } // NewStreamsIterator returns an iterator over logproto.Stream @@ -388,8 +383,8 @@ func (i *queryClientIterator) Next() bool { return true } -func (i *queryClientIterator) Entry() logproto.Entry { - return i.curr.Entry() +func (i *queryClientIterator) At() logproto.Entry { + return i.curr.At() } func (i *queryClientIterator) Labels() string { @@ -398,7 +393,7 @@ func (i *queryClientIterator) Labels() string { func (i *queryClientIterator) StreamHash() uint64 { return i.curr.StreamHash() } -func (i *queryClientIterator) Error() error { +func (i *queryClientIterator) Err() error { return i.err } @@ -435,8 +430,8 @@ func (i *nonOverlappingIterator) Next() bool { return true } -func (i *nonOverlappingIterator) Entry() logproto.Entry { - return i.curr.Entry() +func (i *nonOverlappingIterator) At() logproto.Entry { + return i.curr.At() } func (i *nonOverlappingIterator) Labels() string { @@ -453,11 +448,11 @@ func (i *nonOverlappingIterator) StreamHash() uint64 { return i.curr.StreamHash() } -func (i *nonOverlappingIterator) Error() error { +func (i *nonOverlappingIterator) Err() error { if i.curr == nil { return nil } - return i.curr.Error() + return i.curr.Err() } func (i *nonOverlappingIterator) Close() error { @@ -492,13 +487,13 @@ func (i *timeRangedIterator) Next() bool { i.EntryIterator.Close() return ok } - ts := i.EntryIterator.Entry().Timestamp + ts := i.EntryIterator.At().Timestamp for ok && i.mint.After(ts) { ok = i.EntryIterator.Next() if !ok { continue } - ts = i.EntryIterator.Entry().Timestamp + ts = i.EntryIterator.At().Timestamp } if ok { if ts.Equal(i.mint) { // The mint is inclusive @@ -537,7 +532,7 @@ func NewReversedIter(it EntryIterator, limit uint32, preload bool) (EntryIterato iter: it, entriesWithLabels: make([]entryWithLabels, 0, 1024), limit: limit, - }, it.Error() + }, it.Err() if err != nil { return nil, err } @@ -553,7 +548,7 @@ func (i *reverseIterator) load() { if !i.loaded { i.loaded = true for count := uint32(0); (i.limit == 0 || count < i.limit) && i.iter.Next(); count++ { - i.entriesWithLabels = append(i.entriesWithLabels, entryWithLabels{i.iter.Entry(), i.iter.Labels(), i.iter.StreamHash()}) + i.entriesWithLabels = append(i.entriesWithLabels, entryWithLabels{i.iter.At(), i.iter.Labels(), i.iter.StreamHash()}) } i.iter.Close() } @@ -569,7 +564,7 @@ func (i *reverseIterator) Next() bool { return true } -func (i *reverseIterator) Entry() logproto.Entry { +func (i *reverseIterator) At() logproto.Entry { return i.cur.Entry } @@ -581,7 +576,7 @@ func (i *reverseIterator) StreamHash() uint64 { return i.cur.streamHash } -func (i *reverseIterator) Error() error { return nil } +func (i *reverseIterator) Err() error { return nil } func (i *reverseIterator) Close() error { if !i.loaded { @@ -616,7 +611,7 @@ func NewEntryReversedIter(it EntryIterator) (EntryIterator, error) { iter, err := &reverseEntryIterator{ iter: it, buf: entryBufferPool.Get().(*entryBuffer), - }, it.Error() + }, it.Err() if err != nil { return nil, err } @@ -628,7 +623,7 @@ func (i *reverseEntryIterator) load() { if !i.loaded { i.loaded = true for i.iter.Next() { - i.buf.entries = append(i.buf.entries, entryWithLabels{i.iter.Entry(), i.iter.Labels(), i.iter.StreamHash()}) + i.buf.entries = append(i.buf.entries, entryWithLabels{i.iter.At(), i.iter.Labels(), i.iter.StreamHash()}) } i.iter.Close() } @@ -644,7 +639,7 @@ func (i *reverseEntryIterator) Next() bool { return true } -func (i *reverseEntryIterator) Entry() logproto.Entry { +func (i *reverseEntryIterator) At() logproto.Entry { return i.cur.Entry } @@ -656,7 +651,7 @@ func (i *reverseEntryIterator) StreamHash() uint64 { return i.cur.streamHash } -func (i *reverseEntryIterator) Error() error { return nil } +func (i *reverseEntryIterator) Err() error { return nil } func (i *reverseEntryIterator) release() { if i.buf == nil { @@ -687,7 +682,7 @@ func ReadBatch(i EntryIterator, size uint32) (*logproto.QueryResponse, uint32, e streamsCount int ) for ; respSize < size && i.Next(); respSize++ { - labels, hash, entry := i.Labels(), i.StreamHash(), i.Entry() + labels, hash, entry := i.Labels(), i.StreamHash(), i.At() mutatedStreams, ok := streams[hash] if !ok { mutatedStreams = map[string]*logproto.Stream{} @@ -713,7 +708,7 @@ func ReadBatch(i EntryIterator, size uint32) (*logproto.QueryResponse, uint32, e result.Streams = append(result.Streams, *s) } } - return &result, respSize, i.Error() + return &result, respSize, i.Err() } type peekingEntryIterator struct { @@ -737,7 +732,7 @@ func NewPeekingIterator(iter EntryIterator) PeekingEntryIterator { next := &entryWithLabels{} if iter.Next() { cache = &entryWithLabels{ - Entry: iter.Entry(), + Entry: iter.At(), labels: iter.Labels(), streamHash: iter.StreamHash(), } @@ -766,7 +761,7 @@ func (it *peekingEntryIterator) Next() bool { // cacheNext caches the next element if it exists. func (it *peekingEntryIterator) cacheNext() { if it.iter.Next() { - it.cache.Entry = it.iter.Entry() + it.cache.Entry = it.iter.At() it.cache.labels = it.iter.Labels() it.cache.streamHash = it.iter.StreamHash() return @@ -799,7 +794,7 @@ func (it *peekingEntryIterator) StreamHash() uint64 { } // Entry implements `EntryIterator` -func (it *peekingEntryIterator) Entry() logproto.Entry { +func (it *peekingEntryIterator) At() logproto.Entry { if it.next != nil { return it.next.Entry } @@ -807,8 +802,8 @@ func (it *peekingEntryIterator) Entry() logproto.Entry { } // Error implements `EntryIterator` -func (it *peekingEntryIterator) Error() error { - return it.iter.Error() +func (it *peekingEntryIterator) Err() error { + return it.iter.Err() } // Close implements `EntryIterator` diff --git a/pkg/iter/entry_iterator_test.go b/pkg/iter/entry_iterator_test.go index 3c64c01e296e8..e49ecf3ee528a 100644 --- a/pkg/iter/entry_iterator_test.go +++ b/pkg/iter/entry_iterator_test.go @@ -91,12 +91,12 @@ func TestIterator(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { for i := int64(0); i < tc.length; i++ { assert.Equal(t, true, tc.iterator.Next()) - assert.Equal(t, tc.generator(i), tc.iterator.Entry(), fmt.Sprintln("iteration", i)) + assert.Equal(t, tc.generator(i), tc.iterator.At(), fmt.Sprintln("iteration", i)) assert.Equal(t, tc.labels, tc.iterator.Labels(), fmt.Sprintln("iteration", i)) } assert.Equal(t, false, tc.iterator.Next()) - assert.Equal(t, nil, tc.iterator.Error()) + assert.Equal(t, nil, tc.iterator.Err()) assert.NoError(t, tc.iterator.Close()) }) } @@ -148,12 +148,12 @@ func TestIteratorMultipleLabels(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { for i := int64(0); i < tc.length; i++ { assert.Equal(t, true, tc.iterator.Next()) - assert.Equal(t, tc.generator(i), tc.iterator.Entry(), fmt.Sprintln("iteration", i)) + assert.Equal(t, tc.generator(i), tc.iterator.At(), fmt.Sprintln("iteration", i)) assert.Equal(t, tc.labels(i), tc.iterator.Labels(), fmt.Sprintln("iteration", i)) } assert.Equal(t, false, tc.iterator.Next()) - assert.Equal(t, nil, tc.iterator.Error()) + assert.Equal(t, nil, tc.iterator.Err()) assert.NoError(t, tc.iterator.Close()) }) } @@ -173,7 +173,7 @@ func TestMergeIteratorPrefetch(t *testing.T) { }, "prefetch on Next() when called as first method": func(t *testing.T, i HeapIterator) { assert.True(t, i.Next()) - assert.Equal(t, logproto.Entry{Timestamp: time.Unix(0, 0), Line: "0"}, i.Entry()) + assert.Equal(t, logproto.Entry{Timestamp: time.Unix(0, 0), Line: "0"}, i.At()) }, } @@ -268,18 +268,18 @@ func TestMergeIteratorDeduplication(t *testing.T) { j = length - 1 - i } require.True(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.Equal(t, bar.Labels, it.Labels()) - require.Equal(t, bar.Entries[j], it.Entry()) + require.Equal(t, bar.Entries[j], it.At()) require.True(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.Equal(t, foo.Labels, it.Labels()) - require.Equal(t, foo.Entries[j], it.Entry()) + require.Equal(t, foo.Entries[j], it.At()) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } // forward iteration it := NewMergeEntryIterator(context.Background(), []EntryIterator{ @@ -340,18 +340,18 @@ func TestMergeIteratorWithoutLabels(t *testing.T) { for i := 0; i < 3; i++ { require.True(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.Equal(t, bar.Labels, it.Labels()) - require.Equal(t, bar.Entries[i], it.Entry()) + require.Equal(t, bar.Entries[i], it.At()) require.True(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.Equal(t, foo.Labels, it.Labels()) - require.Equal(t, foo.Entries[i], it.Entry()) + require.Equal(t, foo.Entries[i], it.At()) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) } func mustReverseStreamIterator(it EntryIterator) EntryIterator { @@ -372,15 +372,15 @@ func TestReverseIterator(t *testing.T) { for i := int64((testSize / 2) + 1); i <= testSize; i++ { assert.Equal(t, true, reversedIter.Next()) - assert.Equal(t, identity(i), reversedIter.Entry(), fmt.Sprintln("iteration", i)) + assert.Equal(t, identity(i), reversedIter.At(), fmt.Sprintln("iteration", i)) assert.Equal(t, reversedIter.Labels(), itr2.Labels()) assert.Equal(t, true, reversedIter.Next()) - assert.Equal(t, identity(i), reversedIter.Entry(), fmt.Sprintln("iteration", i)) + assert.Equal(t, identity(i), reversedIter.At(), fmt.Sprintln("iteration", i)) assert.Equal(t, reversedIter.Labels(), itr1.Labels()) } assert.Equal(t, false, reversedIter.Next()) - assert.Equal(t, nil, reversedIter.Error()) + assert.Equal(t, nil, reversedIter.Err()) assert.NoError(t, reversedIter.Close()) } @@ -392,12 +392,12 @@ func TestReverseEntryIterator(t *testing.T) { for i := int64(testSize - 1); i >= 0; i-- { assert.Equal(t, true, reversedIter.Next()) - assert.Equal(t, identity(i), reversedIter.Entry(), fmt.Sprintln("iteration", i)) + assert.Equal(t, identity(i), reversedIter.At(), fmt.Sprintln("iteration", i)) assert.Equal(t, reversedIter.Labels(), defaultLabels) } assert.Equal(t, false, reversedIter.Next()) - assert.Equal(t, nil, reversedIter.Error()) + assert.Equal(t, nil, reversedIter.Err()) assert.NoError(t, reversedIter.Close()) } @@ -443,7 +443,7 @@ func Test_PeekingIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Entry().Timestamp.UnixNano() != 1 { + if iter.At().Timestamp.UnixNano() != 1 { t.Fatal("wrong peeked time.") } @@ -458,7 +458,7 @@ func Test_PeekingIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Entry().Timestamp.UnixNano() != 2 { + if iter.At().Timestamp.UnixNano() != 2 { t.Fatal("wrong peeked time.") } _, peek, ok = iter.Peek() @@ -472,7 +472,7 @@ func Test_PeekingIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Entry().Timestamp.UnixNano() != 3 { + if iter.At().Timestamp.UnixNano() != 3 { t.Fatal("wrong peeked time.") } _, _, ok = iter.Peek() @@ -671,11 +671,11 @@ type CloseTestingIterator struct { e logproto.Entry } -func (i *CloseTestingIterator) Next() bool { return true } -func (i *CloseTestingIterator) Entry() logproto.Entry { return i.e } -func (i *CloseTestingIterator) Labels() string { return "" } -func (i *CloseTestingIterator) StreamHash() uint64 { return 0 } -func (i *CloseTestingIterator) Error() error { return nil } +func (i *CloseTestingIterator) Next() bool { return true } +func (i *CloseTestingIterator) At() logproto.Entry { return i.e } +func (i *CloseTestingIterator) Labels() string { return "" } +func (i *CloseTestingIterator) StreamHash() uint64 { return 0 } +func (i *CloseTestingIterator) Err() error { return nil } func (i *CloseTestingIterator) Close() error { i.closed.Store(true) return nil @@ -730,7 +730,7 @@ func BenchmarkSortIterator(b *testing.B) { b.StartTimer() it := NewMergeEntryIterator(ctx, itrs, logproto.BACKWARD) for it.Next() { - it.Entry() + it.At() } it.Close() } @@ -749,7 +749,7 @@ func BenchmarkSortIterator(b *testing.B) { b.StartTimer() it := NewMergeEntryIterator(ctx, itrs, logproto.BACKWARD) for it.Next() { - it.Entry() + it.At() } it.Close() } @@ -767,7 +767,7 @@ func BenchmarkSortIterator(b *testing.B) { b.StartTimer() it := NewSortEntryIterator(itrs, logproto.BACKWARD) for it.Next() { - it.Entry() + it.At() } it.Close() } @@ -799,7 +799,7 @@ func Test_EntrySortIterator(t *testing.T) { var i int64 = 5 defer it.Close() for it.Next() { - require.Equal(t, time.Unix(0, i), it.Entry().Timestamp) + require.Equal(t, time.Unix(0, i), it.At().Timestamp) i-- } }) @@ -827,7 +827,7 @@ func Test_EntrySortIterator(t *testing.T) { var i int64 defer it.Close() for it.Next() { - require.Equal(t, time.Unix(0, i), it.Entry().Timestamp) + require.Equal(t, time.Unix(0, i), it.At().Timestamp) i++ } }) @@ -855,13 +855,13 @@ func Test_EntrySortIterator(t *testing.T) { }, logproto.FORWARD) // The first entry appears in both so we expect it to be sorted by Labels. require.True(t, it.Next()) - require.Equal(t, time.Unix(0, 0), it.Entry().Timestamp) + require.Equal(t, time.Unix(0, 0), it.At().Timestamp) require.Equal(t, `a`, it.Labels()) var i int64 defer it.Close() for it.Next() { - require.Equal(t, time.Unix(0, i), it.Entry().Timestamp) + require.Equal(t, time.Unix(0, i), it.At().Timestamp) i++ } }) @@ -906,17 +906,17 @@ func TestDedupeMergeEntryIterator(t *testing.T) { }), }, logproto.FORWARD) require.True(t, it.Next()) - lines := []string{it.Entry().Line} - require.Equal(t, time.Unix(1, 0), it.Entry().Timestamp) + lines := []string{it.At().Line} + require.Equal(t, time.Unix(1, 0), it.At().Timestamp) require.True(t, it.Next()) - lines = append(lines, it.Entry().Line) - require.Equal(t, time.Unix(1, 0), it.Entry().Timestamp) + lines = append(lines, it.At().Line) + require.Equal(t, time.Unix(1, 0), it.At().Timestamp) require.True(t, it.Next()) - lines = append(lines, it.Entry().Line) - require.Equal(t, time.Unix(1, 0), it.Entry().Timestamp) + lines = append(lines, it.At().Line) + require.Equal(t, time.Unix(1, 0), it.At().Timestamp) require.True(t, it.Next()) - lines = append(lines, it.Entry().Line) - require.Equal(t, time.Unix(2, 0), it.Entry().Timestamp) + lines = append(lines, it.At().Line) + require.Equal(t, time.Unix(2, 0), it.At().Timestamp) // Two orderings are consistent with the inputs. if lines[0] == "1" { require.Equal(t, []string{"1", "0", "2", "3"}, lines) diff --git a/pkg/iter/iterator.go b/pkg/iter/iterator.go index 61c727428c71a..4b4ef03cb922a 100644 --- a/pkg/iter/iterator.go +++ b/pkg/iter/iterator.go @@ -1,28 +1,50 @@ package iter -import "github.com/grafana/loki/v3/pkg/logproto" +import ( + "errors" -// Iterator iterates over data in time-order. -type Iterator interface { - // Returns true if there is more data to iterate. - Next() bool + v2 "github.com/grafana/loki/v3/pkg/iter/v2" + "github.com/grafana/loki/v3/pkg/logproto" +) + +type Value interface { + logproto.Entry | logproto.Sample +} + +type StreamIterator[T Value] interface { + v2.CloseIterator[T] // Labels returns the labels for the current entry. // The labels can be mutated by the query engine and not reflect the original stream. Labels() string // StreamHash returns the hash of the original stream for the current entry. StreamHash() uint64 - Error() error - Close() error } -type noOpIterator struct{} +type EntryIterator StreamIterator[logproto.Entry] +type SampleIterator StreamIterator[logproto.Sample] + +// noOpIterator implements StreamIterator +type noOpIterator[T Value] struct{} + +func (noOpIterator[T]) Next() bool { return false } +func (noOpIterator[T]) Err() error { return nil } +func (noOpIterator[T]) At() (zero T) { return zero } +func (noOpIterator[T]) Labels() string { return "" } +func (noOpIterator[T]) StreamHash() uint64 { return 0 } +func (noOpIterator[T]) Close() error { return nil } + +var NoopEntryIterator = noOpIterator[logproto.Entry]{} +var NoopSampleIterator = noOpIterator[logproto.Sample]{} + +// errorIterator implements StreamIterator +type errorIterator[T Value] struct{} -var NoopIterator = noOpIterator{} +func (errorIterator[T]) Next() bool { return false } +func (errorIterator[T]) Err() error { return errors.New("error") } +func (errorIterator[T]) At() (zero T) { return zero } +func (errorIterator[T]) Labels() string { return "" } +func (errorIterator[T]) StreamHash() uint64 { return 0 } +func (errorIterator[T]) Close() error { return errors.New("close") } -func (noOpIterator) Next() bool { return false } -func (noOpIterator) Error() error { return nil } -func (noOpIterator) Labels() string { return "" } -func (noOpIterator) StreamHash() uint64 { return 0 } -func (noOpIterator) Entry() logproto.Entry { return logproto.Entry{} } -func (noOpIterator) Sample() logproto.Sample { return logproto.Sample{} } -func (noOpIterator) Close() error { return nil } +var ErrorEntryIterator = errorIterator[logproto.Entry]{} +var ErrorSampleIterator = errorIterator[logproto.Sample]{} diff --git a/pkg/iter/sample_iterator.go b/pkg/iter/sample_iterator.go index be55678ce6285..cac1cac6c83e4 100644 --- a/pkg/iter/sample_iterator.go +++ b/pkg/iter/sample_iterator.go @@ -13,14 +13,6 @@ import ( "github.com/grafana/loki/v3/pkg/util" ) -// SampleIterator iterates over samples in time-order. -type SampleIterator interface { - Iterator - // todo(ctovena) we should add `Seek(t int64) bool` - // This way we can skip when ranging over samples. - Sample() logproto.Sample -} - // PeekingSampleIterator is a sample iterator that can peek sample without moving the current sample. type PeekingSampleIterator interface { SampleIterator @@ -46,7 +38,7 @@ func NewPeekingSampleIterator(iter SampleIterator) PeekingSampleIterator { next := &sampleWithLabels{} if iter.Next() { cache = &sampleWithLabels{ - Sample: iter.Sample(), + Sample: iter.At(), labels: iter.Labels(), streamHash: iter.StreamHash(), } @@ -92,7 +84,7 @@ func (it *peekingSampleIterator) Next() bool { // cacheNext caches the next element if it exists. func (it *peekingSampleIterator) cacheNext() { if it.iter.Next() { - it.cache.Sample = it.iter.Sample() + it.cache.Sample = it.iter.At() it.cache.labels = it.iter.Labels() it.cache.streamHash = it.iter.StreamHash() return @@ -101,7 +93,7 @@ func (it *peekingSampleIterator) cacheNext() { it.cache = nil } -func (it *peekingSampleIterator) Sample() logproto.Sample { +func (it *peekingSampleIterator) At() logproto.Sample { if it.next != nil { return it.next.Sample } @@ -115,8 +107,8 @@ func (it *peekingSampleIterator) Peek() (string, logproto.Sample, bool) { return "", logproto.Sample{}, false } -func (it *peekingSampleIterator) Error() error { - return it.iter.Error() +func (it *peekingSampleIterator) Err() error { + return it.iter.Err() } type SampleIteratorHeap struct { @@ -144,7 +136,7 @@ func (h *SampleIteratorHeap) Pop() interface{} { } func (h SampleIteratorHeap) Less(i, j int) bool { - s1, s2 := h.its[i].Sample(), h.its[j].Sample() + s1, s2 := h.its[i].At(), h.its[j].At() if s1.Timestamp == s2.Timestamp { if h.its[i].StreamHash() == 0 { return h.its[i].Labels() < h.its[j].Labels() @@ -218,7 +210,7 @@ func (i *mergeSampleIterator) requeue(ei SampleIterator, advanced bool) { return } - if err := ei.Error(); err != nil { + if err := ei.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", ei.Close) @@ -238,7 +230,7 @@ func (i *mergeSampleIterator) Next() bool { // shortcut for the last iterator. if i.heap.Len() == 1 { - i.curr.Sample = i.heap.Peek().Sample() + i.curr.Sample = i.heap.Peek().At() i.curr.labels = i.heap.Peek().Labels() i.curr.streamHash = i.heap.Peek().StreamHash() if !i.heap.Peek().Next() { @@ -254,7 +246,7 @@ func (i *mergeSampleIterator) Next() bool { Outer: for i.heap.Len() > 0 { next := i.heap.Peek() - sample := next.Sample() + sample := next.At() if len(i.buffer) > 0 && (i.buffer[0].streamHash != next.StreamHash() || i.buffer[0].Timestamp != sample.Timestamp) { break } @@ -280,7 +272,7 @@ Outer: if !next.Next() { continue Outer } - sample := next.Sample() + sample := next.At() if next.StreamHash() != i.buffer[0].streamHash || sample.Timestamp != i.buffer[0].Timestamp { break @@ -321,7 +313,7 @@ func (i *mergeSampleIterator) nextFromBuffer() { i.buffer = i.buffer[1:] } -func (i *mergeSampleIterator) Sample() logproto.Sample { +func (i *mergeSampleIterator) At() logproto.Sample { return i.curr.Sample } @@ -333,7 +325,7 @@ func (i *mergeSampleIterator) StreamHash() uint64 { return i.curr.streamHash } -func (i *mergeSampleIterator) Error() error { +func (i *mergeSampleIterator) Err() error { switch len(i.errs) { case 0: return nil @@ -370,7 +362,7 @@ type sortSampleIterator struct { // When timestamp is equal, the iterator sorts samples by their label alphabetically. func NewSortSampleIterator(is []SampleIterator) SampleIterator { if len(is) == 0 { - return NoopIterator + return NoopSampleIterator } if len(is) == 1 { return is[0] @@ -397,7 +389,7 @@ func (i *sortSampleIterator) init() { continue } - if err := it.Error(); err != nil { + if err := it.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", it.Close) @@ -417,13 +409,13 @@ func (i *sortSampleIterator) Next() bool { } next := i.heap.Peek() - i.curr.Sample = next.Sample() + i.curr.Sample = next.At() i.curr.labels = next.Labels() i.curr.streamHash = next.StreamHash() // if the top iterator is empty, we remove it. if !next.Next() { heap.Pop(i.heap) - if err := next.Error(); err != nil { + if err := next.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", next.Close) @@ -435,7 +427,7 @@ func (i *sortSampleIterator) Next() bool { return true } -func (i *sortSampleIterator) Sample() logproto.Sample { +func (i *sortSampleIterator) At() logproto.Sample { return i.curr.Sample } @@ -447,7 +439,7 @@ func (i *sortSampleIterator) StreamHash() uint64 { return i.curr.streamHash } -func (i *sortSampleIterator) Error() error { +func (i *sortSampleIterator) Err() error { switch len(i.errs) { case 0: return nil @@ -505,8 +497,8 @@ func (i *sampleQueryClientIterator) Next() bool { return true } -func (i *sampleQueryClientIterator) Sample() logproto.Sample { - return i.curr.Sample() +func (i *sampleQueryClientIterator) At() logproto.Sample { + return i.curr.At() } func (i *sampleQueryClientIterator) Labels() string { @@ -517,7 +509,7 @@ func (i *sampleQueryClientIterator) StreamHash() uint64 { return i.curr.StreamHash() } -func (i *sampleQueryClientIterator) Error() error { +func (i *sampleQueryClientIterator) Err() error { return i.err } @@ -587,7 +579,7 @@ func (i *seriesIterator) Next() bool { return i.i < len(i.series.Samples) } -func (i *seriesIterator) Error() error { +func (i *seriesIterator) Err() error { return nil } @@ -599,7 +591,7 @@ func (i *seriesIterator) StreamHash() uint64 { return i.series.StreamHash } -func (i *seriesIterator) Sample() logproto.Sample { +func (i *seriesIterator) At() logproto.Sample { return i.series.Samples[i.i] } @@ -638,8 +630,8 @@ func (i *nonOverlappingSampleIterator) Next() bool { return true } -func (i *nonOverlappingSampleIterator) Sample() logproto.Sample { - return i.curr.Sample() +func (i *nonOverlappingSampleIterator) At() logproto.Sample { + return i.curr.At() } func (i *nonOverlappingSampleIterator) Labels() string { @@ -656,11 +648,11 @@ func (i *nonOverlappingSampleIterator) StreamHash() uint64 { return i.curr.StreamHash() } -func (i *nonOverlappingSampleIterator) Error() error { +func (i *nonOverlappingSampleIterator) Err() error { if i.curr == nil { return nil } - return i.curr.Error() + return i.curr.Err() } func (i *nonOverlappingSampleIterator) Close() error { @@ -694,13 +686,13 @@ func (i *timeRangedSampleIterator) Next() bool { i.SampleIterator.Close() return ok } - ts := i.SampleIterator.Sample().Timestamp + ts := i.SampleIterator.At().Timestamp for ok && i.mint > ts { ok = i.SampleIterator.Next() if !ok { continue } - ts = i.SampleIterator.Sample().Timestamp + ts = i.SampleIterator.At().Timestamp } if ok { if ts == i.mint { // The mint is inclusive @@ -724,7 +716,7 @@ func ReadSampleBatch(i SampleIterator, size uint32) (*logproto.SampleQueryRespon seriesCount int ) for ; respSize < size && i.Next(); respSize++ { - labels, hash, sample := i.Labels(), i.StreamHash(), i.Sample() + labels, hash, sample := i.Labels(), i.StreamHash(), i.At() streams, ok := series[hash] if !ok { streams = map[string]*logproto.Series{} @@ -750,5 +742,5 @@ func ReadSampleBatch(i SampleIterator, size uint32) (*logproto.SampleQueryRespon result.Series = append(result.Series, *s) } } - return &result, respSize, i.Error() + return &result, respSize, i.Err() } diff --git a/pkg/iter/sample_iterator_test.go b/pkg/iter/sample_iterator_test.go index da3113c547e66..2f37d40c1c2a5 100644 --- a/pkg/iter/sample_iterator_test.go +++ b/pkg/iter/sample_iterator_test.go @@ -43,7 +43,7 @@ func TestNewPeekingSampleIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Sample().Timestamp != 1 { + if iter.At().Timestamp != 1 { t.Fatal("wrong peeked time.") } @@ -58,7 +58,7 @@ func TestNewPeekingSampleIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Sample().Timestamp != 2 { + if iter.At().Timestamp != 2 { t.Fatal("wrong peeked time.") } _, peek, ok = iter.Peek() @@ -72,7 +72,7 @@ func TestNewPeekingSampleIterator(t *testing.T) { if !hasNext { t.Fatal("should have next.") } - if iter.Sample().Timestamp != 3 { + if iter.At().Timestamp != 3 { t.Fatal("wrong peeked time.") } _, _, ok = iter.Peek() @@ -80,7 +80,7 @@ func TestNewPeekingSampleIterator(t *testing.T) { t.Fatal("should not be ok.") } require.NoError(t, iter.Close()) - require.NoError(t, iter.Error()) + require.NoError(t, iter.Err()) } func sample(i int) logproto.Sample { @@ -123,13 +123,13 @@ func TestNewMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="car"}`, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, `{foo="var"}`, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) t.Run("no labels", func(t *testing.T) { @@ -169,13 +169,13 @@ func TestNewMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) } @@ -208,15 +208,15 @@ func TestNewSampleQueryClientIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="var"}`, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) } for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="car"}`, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) } @@ -232,10 +232,10 @@ func TestNewNonOverlappingSampleIterator(t *testing.T) { for i := 1; i < 6; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="var"}`, it.Labels(), i) - require.Equal(t, sample(i), it.Sample(), i) + require.Equal(t, sample(i), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) } @@ -256,11 +256,11 @@ type CloseTestingSmplIterator struct { s logproto.Sample } -func (i *CloseTestingSmplIterator) Next() bool { return true } -func (i *CloseTestingSmplIterator) Sample() logproto.Sample { return i.s } -func (i *CloseTestingSmplIterator) StreamHash() uint64 { return 0 } -func (i *CloseTestingSmplIterator) Labels() string { return "" } -func (i *CloseTestingSmplIterator) Error() error { return nil } +func (i *CloseTestingSmplIterator) Next() bool { return true } +func (i *CloseTestingSmplIterator) At() logproto.Sample { return i.s } +func (i *CloseTestingSmplIterator) StreamHash() uint64 { return 0 } +func (i *CloseTestingSmplIterator) Labels() string { return "" } +func (i *CloseTestingSmplIterator) Err() error { return nil } func (i *CloseTestingSmplIterator) Close() error { i.closed.Store(true) return nil @@ -287,8 +287,7 @@ func TestSampleIteratorWithClose_CloseIdempotent(t *testing.T) { c++ return nil } - ni := noOpIterator{} - it := SampleIteratorWithClose(ni, closeFn) + it := SampleIteratorWithClose(NoopSampleIterator, closeFn) // Multiple calls to close should result in c only ever having been incremented one time from 0 to 1 err := it.Close() assert.NoError(t, err) @@ -301,25 +300,16 @@ func TestSampleIteratorWithClose_CloseIdempotent(t *testing.T) { assert.EqualValues(t, 1, c) } -type alwaysErrorIterator struct { - noOpIterator -} - -func (alwaysErrorIterator) Close() error { - return errors.New("i always error") -} - func TestSampleIteratorWithClose_ReturnsError(t *testing.T) { closeFn := func() error { return errors.New("i broke") } - ei := alwaysErrorIterator{} - it := SampleIteratorWithClose(ei, closeFn) + it := SampleIteratorWithClose(ErrorSampleIterator, closeFn) err := it.Close() // Verify that a proper multi error is returned when both the iterator and the close function return errors if me, ok := err.(util.MultiError); ok { assert.True(t, len(me) == 2, "Expected 2 errors, one from the iterator and one from the close function") - assert.EqualError(t, me[0], "i always error") + assert.EqualError(t, me[0], "close") assert.EqualError(t, me[1], "i broke") } else { t.Error("Expected returned error to be of type util.MultiError") @@ -362,7 +352,7 @@ func BenchmarkSortSampleIterator(b *testing.B) { b.StartTimer() it := NewMergeSampleIterator(ctx, itrs) for it.Next() { - it.Sample() + it.At() } it.Close() } @@ -378,7 +368,7 @@ func BenchmarkSortSampleIterator(b *testing.B) { b.StartTimer() it := NewSortSampleIterator(itrs) for it.Next() { - it.Sample() + it.At() } it.Close() } @@ -410,7 +400,7 @@ func Test_SampleSortIterator(t *testing.T) { var i int64 defer it.Close() for it.Next() { - require.Equal(t, i, it.Sample().Timestamp) + require.Equal(t, i, it.At().Timestamp) i++ } }) @@ -439,13 +429,13 @@ func Test_SampleSortIterator(t *testing.T) { // The first entry appears in both so we expect it to be sorted by Labels. require.True(t, it.Next()) - require.Equal(t, int64(0), it.Sample().Timestamp) + require.Equal(t, int64(0), it.At().Timestamp) require.Equal(t, `a`, it.Labels()) var i int64 defer it.Close() for it.Next() { - require.Equal(t, i, it.Sample().Timestamp) + require.Equal(t, i, it.At().Timestamp) i++ } }) @@ -489,15 +479,15 @@ func TestDedupeMergeSampleIterator(t *testing.T) { }) require.True(t, it.Next()) - require.Equal(t, time.Unix(1, 0).UnixNano(), it.Sample().Timestamp) - require.Equal(t, 1., it.Sample().Value) - require.Equal(t, xxhash.Sum64String("1"), it.Sample().Hash) + require.Equal(t, time.Unix(1, 0).UnixNano(), it.At().Timestamp) + require.Equal(t, 1., it.At().Value) + require.Equal(t, xxhash.Sum64String("1"), it.At().Hash) require.True(t, it.Next()) - require.Equal(t, time.Unix(1, 0).UnixNano(), it.Sample().Timestamp) - require.Equal(t, 1., it.Sample().Value) - require.Equal(t, xxhash.Sum64String("2"), it.Sample().Hash) + require.Equal(t, time.Unix(1, 0).UnixNano(), it.At().Timestamp) + require.Equal(t, 1., it.At().Value) + require.Equal(t, xxhash.Sum64String("2"), it.At().Hash) require.True(t, it.Next()) - require.Equal(t, time.Unix(2, 0).UnixNano(), it.Sample().Timestamp) - require.Equal(t, 1., it.Sample().Value) - require.Equal(t, xxhash.Sum64String("3"), it.Sample().Hash) + require.Equal(t, time.Unix(2, 0).UnixNano(), it.At().Timestamp) + require.Equal(t, 1., it.At().Value) + require.Equal(t, xxhash.Sum64String("3"), it.At().Hash) } diff --git a/pkg/storage/bloom/v1/dedupe.go b/pkg/iter/v2/dedupe.go similarity index 95% rename from pkg/storage/bloom/v1/dedupe.go rename to pkg/iter/v2/dedupe.go index 2e1a7cca42f36..7ea73480ca67e 100644 --- a/pkg/storage/bloom/v1/dedupe.go +++ b/pkg/iter/v2/dedupe.go @@ -1,4 +1,4 @@ -package v1 +package v2 // DedupeIter is a deduplicating iterator which creates an Iterator[B] // from a sequence of Iterator[A]. @@ -6,7 +6,7 @@ type DedupeIter[A, B any] struct { eq func(A, B) bool // equality check from func(A) B // convert A to B, used on first element merge func(A, B) B // merge A into B - itr PeekingIterator[A] + itr PeekIterator[A] tmp B } @@ -18,7 +18,7 @@ func NewDedupingIter[A, B any]( eq func(A, B) bool, from func(A) B, merge func(A, B) B, - itr PeekingIterator[A], + itr PeekIterator[A], ) *DedupeIter[A, B] { return &DedupeIter[A, B]{ eq: eq, diff --git a/pkg/iter/v2/interface.go b/pkg/iter/v2/interface.go new file mode 100644 index 0000000000000..05aee30f390f3 --- /dev/null +++ b/pkg/iter/v2/interface.go @@ -0,0 +1,64 @@ +package v2 + +// Iterator is the basic iterator type with the common functions for advancing +// and retrieving the current value. +// +// General usage of the iterator: +// +// for it.Next() { +// curr := it.At() +// // do something +// } +// if it.Err() != nil { +// // do something +// } +type Iterator[T any] interface { + Next() bool + Err() error + At() T +} + +// Iterators with one single added functionality. + +type SizedIterator[T any] interface { + Iterator[T] + Remaining() int // remaining +} + +type PeekIterator[T any] interface { + Iterator[T] + Peek() (T, bool) +} + +type SeekIterator[K, V any] interface { + Iterator[V] + Seek(K) error +} + +type CloseIterator[T any] interface { + Iterator[T] + Close() error +} + +type CountIterator[T any] interface { + Iterator[T] + Count() int +} + +type ResetIterator[T any] interface { + Reset() error + Iterator[T] +} + +// Iterators which are an intersection type of two or more iterators with a +// single added functionality. + +type PeekCloseIterator[T any] interface { + PeekIterator[T] + CloseIterator[T] +} + +type CloseResetIterator[T any] interface { + CloseIterator[T] + ResetIterator[T] +} diff --git a/pkg/iter/v2/iter.go b/pkg/iter/v2/iter.go new file mode 100644 index 0000000000000..45e17fcad5ac0 --- /dev/null +++ b/pkg/iter/v2/iter.go @@ -0,0 +1,228 @@ +package v2 + +import ( + "context" + "io" +) + +type PeekIter[T any] struct { + itr Iterator[T] + + // the first call to Next() will populate cur & next + init bool + zero T // zero value of T for returning empty Peek's + cur, next *T +} + +func NewPeekIter[T any](itr Iterator[T]) *PeekIter[T] { + return &PeekIter[T]{itr: itr} +} + +// populates the first element so Peek can be used and subsequent Next() +// calls will work as expected +func (it *PeekIter[T]) ensureInit() { + if it.init { + return + } + if it.itr.Next() { + at := it.itr.At() + it.next = &at + } + it.init = true +} + +// load the next element and return the cached one +func (it *PeekIter[T]) cacheNext() { + it.cur = it.next + if it.cur != nil && it.itr.Next() { + at := it.itr.At() + it.next = &at + } else { + it.next = nil + } +} + +func (it *PeekIter[T]) Next() bool { + it.ensureInit() + it.cacheNext() + return it.cur != nil +} + +func (it *PeekIter[T]) Peek() (T, bool) { + it.ensureInit() + if it.next == nil { + return it.zero, false + } + return *it.next, true +} + +func (it *PeekIter[T]) Err() error { + return it.itr.Err() +} + +func (it *PeekIter[T]) At() T { + return *it.cur +} + +type SliceIter[T any] struct { + cur int + xs []T +} + +func NewSliceIter[T any](xs []T) *SliceIter[T] { + return &SliceIter[T]{xs: xs, cur: -1} +} + +func (it *SliceIter[T]) Remaining() int { + return max(0, len(it.xs)-(it.cur+1)) +} + +func (it *SliceIter[T]) Next() bool { + it.cur++ + return it.cur < len(it.xs) +} + +func (it *SliceIter[T]) Err() error { + return nil +} + +func (it *SliceIter[T]) At() T { + return it.xs[it.cur] +} + +type MapIter[A any, B any] struct { + Iterator[A] + f func(A) B +} + +func NewMapIter[A any, B any](src Iterator[A], f func(A) B) *MapIter[A, B] { + return &MapIter[A, B]{Iterator: src, f: f} +} + +func (it *MapIter[A, B]) At() B { + return it.f(it.Iterator.At()) +} + +type EmptyIter[T any] struct { + zero T +} + +func (it *EmptyIter[T]) Next() bool { + return false +} + +func (it *EmptyIter[T]) Err() error { + return nil +} + +func (it *EmptyIter[T]) At() T { + return it.zero +} + +func (it *EmptyIter[T]) Peek() (T, bool) { + return it.zero, false +} + +func (it *EmptyIter[T]) Remaining() int { + return 0 +} + +// noop +func (it *EmptyIter[T]) Reset() {} + +func NewEmptyIter[T any]() *EmptyIter[T] { + return &EmptyIter[T]{} +} + +type CancellableIter[T any] struct { + ctx context.Context + Iterator[T] +} + +func (cii *CancellableIter[T]) Next() bool { + select { + case <-cii.ctx.Done(): + return false + default: + return cii.Iterator.Next() + } +} + +func (cii *CancellableIter[T]) Err() error { + if err := cii.ctx.Err(); err != nil { + return err + } + return cii.Iterator.Err() +} + +func NewCancelableIter[T any](ctx context.Context, itr Iterator[T]) *CancellableIter[T] { + return &CancellableIter[T]{ctx: ctx, Iterator: itr} +} + +func NewCloseableIterator[T io.Closer](itr Iterator[T]) *CloseIter[T] { + return &CloseIter[T]{itr} +} + +type CloseIter[T io.Closer] struct { + Iterator[T] +} + +func (i *CloseIter[T]) Close() error { + return i.At().Close() +} + +type PeekCloseIter[T any] struct { + *PeekIter[T] + close func() error +} + +func NewPeekCloseIter[T any](itr CloseIterator[T]) *PeekCloseIter[T] { + return &PeekCloseIter[T]{PeekIter: NewPeekIter[T](itr), close: itr.Close} +} + +func (it *PeekCloseIter[T]) Close() error { + return it.close() +} + +type Predicate[T any] func(T) bool + +func NewFilterIter[T any](it Iterator[T], p Predicate[T]) *FilterIter[T] { + return &FilterIter[T]{ + Iterator: it, + match: p, + } +} + +type FilterIter[T any] struct { + Iterator[T] + match Predicate[T] +} + +func (i *FilterIter[T]) Next() bool { + hasNext := i.Iterator.Next() + for hasNext && !i.match(i.Iterator.At()) { + hasNext = i.Iterator.Next() + } + return hasNext +} + +type CounterIter[T any] struct { + Iterator[T] // the underlying iterator + count int +} + +func NewCounterIter[T any](itr Iterator[T]) *CounterIter[T] { + return &CounterIter[T]{Iterator: itr} +} + +func (it *CounterIter[T]) Next() bool { + if it.Iterator.Next() { + it.count++ + return true + } + return false +} + +func (it *CounterIter[T]) Count() int { + return it.count +} diff --git a/pkg/storage/bloom/v1/util_test.go b/pkg/iter/v2/iter_test.go similarity index 92% rename from pkg/storage/bloom/v1/util_test.go rename to pkg/iter/v2/iter_test.go index 8af93231313be..054a539f9eabc 100644 --- a/pkg/storage/bloom/v1/util_test.go +++ b/pkg/iter/v2/iter_test.go @@ -1,4 +1,4 @@ -package v1 +package v2 import ( "testing" @@ -9,7 +9,7 @@ import ( func TestPeekingIterator(t *testing.T) { t.Parallel() data := []int{1, 2, 3, 4, 5} - itr := NewPeekingIter[int](NewSliceIter[int](data)) + itr := NewPeekIter[int](NewSliceIter[int](data)) for i := 0; i < len(data)*2; i++ { if i%2 == 0 { @@ -32,7 +32,7 @@ func TestCounterIter(t *testing.T) { data := []int{1, 2, 3, 4, 5} itr := NewCounterIter[int](NewSliceIter[int](data)) - peekItr := NewPeekingIter[int](itr) + peekItr := NewPeekIter[int](itr) // Consume the outer iter and use peek for { diff --git a/pkg/storage/bloom/v1/ordering.go b/pkg/iter/v2/ordering.go similarity index 89% rename from pkg/storage/bloom/v1/ordering.go rename to pkg/iter/v2/ordering.go index e534fbf29bfc5..4231f249fddde 100644 --- a/pkg/storage/bloom/v1/ordering.go +++ b/pkg/iter/v2/ordering.go @@ -1,4 +1,4 @@ -package v1 +package v2 type Ord byte @@ -36,21 +36,21 @@ func NewOrderable[T any](val T, cmp func(T, T) Ord) OrderedImpl[T] { } type UnlessIterator[T Orderable[T]] struct { - a, b PeekingIterator[T] + a, b PeekIterator[T] } // Iterators _must_ be sorted. Defers to underlying `PeekingIterator` implementation // for both iterators if they implement it. func NewUnlessIterator[T Orderable[T]](a, b Iterator[T]) *UnlessIterator[T] { - var peekA, peekB PeekingIterator[T] + var peekA, peekB PeekIterator[T] var ok bool - if peekA, ok = a.(PeekingIterator[T]); !ok { - peekA = NewPeekingIter(a) + if peekA, ok = a.(PeekIterator[T]); !ok { + peekA = NewPeekIter(a) } - if peekB, ok = b.(PeekingIterator[T]); !ok { - peekB = NewPeekingIter(b) + if peekB, ok = b.(PeekIterator[T]); !ok { + peekB = NewPeekIter(b) } return &UnlessIterator[T]{ diff --git a/pkg/storage/bloom/v1/ordering_test.go b/pkg/iter/v2/ordering_test.go similarity index 83% rename from pkg/storage/bloom/v1/ordering_test.go rename to pkg/iter/v2/ordering_test.go index 2da09a1964b0f..6a2e81abae014 100644 --- a/pkg/storage/bloom/v1/ordering_test.go +++ b/pkg/iter/v2/ordering_test.go @@ -1,7 +1,9 @@ -package v1 +package v2 import ( "testing" + + "github.com/stretchr/testify/require" ) func TestOrdering(t *testing.T) { @@ -86,3 +88,14 @@ func TestOrdering(t *testing.T) { }) } } + +func EqualIterators[T any](t *testing.T, test func(a, b T), expected, actual Iterator[T]) { + for expected.Next() { + require.True(t, actual.Next()) + a, b := expected.At(), actual.At() + test(a, b) + } + require.False(t, actual.Next()) + require.Nil(t, expected.Err()) + require.Nil(t, actual.Err()) +} diff --git a/pkg/logcli/client/file.go b/pkg/logcli/client/file.go index eabf29aef255c..1267681d75c85 100644 --- a/pkg/logcli/client/file.go +++ b/pkg/logcli/client/file.go @@ -278,7 +278,7 @@ func newFileIterator( }) if len(lines) == 0 { - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } streams := map[uint64]*logproto.Stream{} @@ -317,7 +317,7 @@ func newFileIterator( } if len(streams) == 0 { - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } streamResult := make([]logproto.Stream, 0, len(streams)) diff --git a/pkg/logql/engine.go b/pkg/logql/engine.go index 8b46ed4d833fb..f35a1b397a3b0 100644 --- a/pkg/logql/engine.go +++ b/pkg/logql/engine.go @@ -540,7 +540,7 @@ func readStreams(i iter.EntryIterator, size uint32, dir logproto.Direction, inte // value here because many unit tests start at time.Unix(0,0) lastEntry := lastEntryMinTime for respSize < size && i.Next() { - streamLabels, entry := i.Labels(), i.Entry() + streamLabels, entry := i.Labels(), i.At() forwardShouldOutput := dir == logproto.FORWARD && (entry.Timestamp.Equal(lastEntry.Add(interval)) || entry.Timestamp.After(lastEntry.Add(interval))) @@ -559,7 +559,7 @@ func readStreams(i iter.EntryIterator, size uint32, dir logproto.Direction, inte streams[streamLabels] = stream } stream.Entries = append(stream.Entries, entry) - lastEntry = i.Entry().Timestamp + lastEntry = i.At().Timestamp respSize++ } } @@ -569,7 +569,7 @@ func readStreams(i iter.EntryIterator, size uint32, dir logproto.Direction, inte result = append(result, *stream) } sort.Sort(result) - return result, i.Error() + return result, i.Err() } type groupedAggregation struct { diff --git a/pkg/logql/engine_test.go b/pkg/logql/engine_test.go index 48e0e28323030..274276a02c8f1 100644 --- a/pkg/logql/engine_test.go +++ b/pkg/logql/engine_test.go @@ -35,7 +35,7 @@ import ( var ( testSize = int64(300) - ErrMock = errors.New("mock error") + ErrMock = errors.New("error") ErrMockMultiple = util.MultiError{ErrMock, ErrMock} ) @@ -2298,13 +2298,13 @@ type statsQuerier struct{} func (statsQuerier) SelectLogs(ctx context.Context, _ SelectLogParams) (iter.EntryIterator, error) { st := stats.FromContext(ctx) st.AddDecompressedBytes(1) - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } func (statsQuerier) SelectSamples(ctx context.Context, _ SelectSampleParams) (iter.SampleIterator, error) { st := stats.FromContext(ctx) st.AddDecompressedBytes(1) - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } func TestEngine_Stats(t *testing.T) { @@ -2332,14 +2332,14 @@ func (metaQuerier) SelectLogs(ctx context.Context, _ SelectLogParams) (iter.Entr Values: []string{"value"}, }, }) - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } func (metaQuerier) SelectSamples(ctx context.Context, _ SelectSampleParams) (iter.SampleIterator, error) { _ = metadata.JoinHeaders(ctx, []*definitions.PrometheusResponseHeader{ {Name: "Header", Values: []string{"value"}}, }) - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } func TestEngine_Metadata(t *testing.T) { @@ -2409,7 +2409,7 @@ func TestStepEvaluator_Error(t *testing.T) { samples: func() []iter.SampleIterator { return []iter.SampleIterator{ iter.NewSeriesIterator(newSeries(testSize, identity, `{app="foo"}`)), - NewErrorSampleIterator(), + iter.ErrorSampleIterator, } }, }, @@ -2422,7 +2422,7 @@ func TestStepEvaluator_Error(t *testing.T) { entries: func() []iter.EntryIterator { return []iter.EntryIterator{ iter.NewStreamIterator(newStream(testSize, identity, `{app="foo"}`)), - NewErrorEntryIterator(), + iter.ErrorEntryIterator, } }, }, @@ -2435,7 +2435,7 @@ func TestStepEvaluator_Error(t *testing.T) { samples: func() []iter.SampleIterator { return []iter.SampleIterator{ iter.NewSeriesIterator(newSeries(testSize, identity, `{app="foo"}`)), - NewErrorSampleIterator(), + iter.ErrorSampleIterator, } }, }, @@ -2745,7 +2745,7 @@ func (q *querierRecorder) SelectSamples(_ context.Context, p SelectSampleParams) } recordID := paramsID(p) if len(q.series) == 0 { - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } series, ok := q.series[recordID] if !ok { @@ -2926,30 +2926,3 @@ func inverse(g generator) generator { return g(-i) } } - -// errorIterator -type errorIterator struct{} - -// NewErrorSampleIterator return an sample iterator that errors out -func NewErrorSampleIterator() iter.SampleIterator { - return &errorIterator{} -} - -// NewErrorEntryIterator return an entry iterator that errors out -func NewErrorEntryIterator() iter.EntryIterator { - return &errorIterator{} -} - -func (errorIterator) Next() bool { return false } - -func (errorIterator) Error() error { return ErrMock } - -func (errorIterator) Labels() string { return "" } - -func (errorIterator) StreamHash() uint64 { return 0 } - -func (errorIterator) Entry() logproto.Entry { return logproto.Entry{} } - -func (errorIterator) Sample() logproto.Sample { return logproto.Sample{} } - -func (errorIterator) Close() error { return nil } diff --git a/pkg/logql/range_vector.go b/pkg/logql/range_vector.go index 180a1bde27cac..f551c6512db4f 100644 --- a/pkg/logql/range_vector.go +++ b/pkg/logql/range_vector.go @@ -133,7 +133,7 @@ func (r *batchRangeVectorIterator) Close() error { } func (r *batchRangeVectorIterator) Error() error { - return r.iter.Error() + return r.iter.Err() } // popBack removes all entries out of the current window from the back. @@ -552,7 +552,7 @@ func (r *streamRangeVectorIterator) Close() error { } func (r *streamRangeVectorIterator) Error() error { - return r.iter.Error() + return r.iter.Err() } // load the next sample range window. diff --git a/pkg/pattern/instance.go b/pkg/pattern/instance.go index f19b0373858d9..21520ae7d26df 100644 --- a/pkg/pattern/instance.go +++ b/pkg/pattern/instance.go @@ -22,7 +22,7 @@ import ( "github.com/grafana/loki/v3/pkg/util" "github.com/grafana/loki/v3/pkg/util/spanlogger" - loki_iter "github.com/grafana/loki/v3/pkg/iter" + "github.com/grafana/loki/v3/pkg/iter" pattern_iter "github.com/grafana/loki/v3/pkg/pattern/iter" ) @@ -115,10 +115,10 @@ func (i *instance) QuerySample( ctx context.Context, expr syntax.SampleExpr, req *logproto.QuerySamplesRequest, -) (loki_iter.SampleIterator, error) { +) (iter.SampleIterator, error) { if !i.aggregationCfg.Enabled { // Should never get here, but this will prevent nil pointer panics in test - return loki_iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } from, through := util.RoundToMilliseconds(req.Start, req.End) @@ -132,11 +132,11 @@ func (i *instance) QuerySample( return nil, err } - var iters []loki_iter.SampleIterator + var iters []iter.SampleIterator err = i.forMatchingStreams( selector.Matchers(), func(stream *stream) error { - var iter loki_iter.SampleIterator + var iter iter.SampleIterator var err error iter, err = stream.SampleIterator(ctx, expr, from, through, step) if err != nil { diff --git a/pkg/pattern/instance_test.go b/pkg/pattern/instance_test.go index 07351089ca8d9..2db0c2797fa44 100644 --- a/pkg/pattern/instance_test.go +++ b/pkg/pattern/instance_test.go @@ -113,7 +113,7 @@ func TestInstance_QuerySample(t *testing.T) { next := iter.Next() require.True(t, next) - sample := iter.Sample() + sample := iter.At() require.Equal(t, float64(4), sample.Value) require.Equal(t, model.Time(thirdPoint).UnixNano(), sample.Timestamp) @@ -132,7 +132,7 @@ func TestInstance_QuerySample(t *testing.T) { next := iter.Next() require.True(t, next) - sample := iter.Sample() + sample := iter.At() require.Equal(t, float64(80), sample.Value) require.Equal(t, model.Time(thirdPoint).UnixNano(), sample.Timestamp) @@ -273,7 +273,7 @@ func TestInstance_QuerySample(t *testing.T) { next := iter.Next() require.True(t, next) - sample := iter.Sample() + sample := iter.At() require.Equal(t, model.Time(thirdStep).UnixNano(), sample.Timestamp) require.Equal(t, float64(8), sample.Value) require.Equal(t, expectedLabels.String(), iter.Labels()) @@ -284,7 +284,7 @@ func TestInstance_QuerySample(t *testing.T) { next = iter.Next() require.True(t, next) - sample = iter.Sample() + sample = iter.At() require.Equal(t, model.Time(fifthStep).UnixNano(), sample.Timestamp) require.Equal(t, float64(6), sample.Value) require.Equal(t, expectedLabels.String(), iter.Labels()) @@ -315,7 +315,7 @@ func TestInstance_QuerySample(t *testing.T) { next := iter.Next() require.True(t, next) - sample := iter.Sample() + sample := iter.At() require.Equal(t, model.Time(thirdStep).UnixNano(), sample.Timestamp) require.Equal(t, float64(8), sample.Value) require.Equal(t, expectedLabels.String(), iter.Labels()) @@ -324,7 +324,7 @@ func TestInstance_QuerySample(t *testing.T) { next = iter.Next() require.True(t, next) - sample = iter.Sample() + sample = iter.At() require.Equal(t, model.Time(fourthStep).UnixNano(), sample.Timestamp) require.Equal(t, float64(8), sample.Value) require.Equal(t, expectedLabels.String(), iter.Labels()) @@ -333,7 +333,7 @@ func TestInstance_QuerySample(t *testing.T) { next = iter.Next() require.True(t, next) - sample = iter.Sample() + sample = iter.At() require.Equal(t, model.Time(fifthStep).UnixNano(), sample.Timestamp) require.Equal(t, float64(14), sample.Value) require.Equal(t, expectedLabels.String(), iter.Labels()) diff --git a/pkg/pattern/iter/batch.go b/pkg/pattern/iter/batch.go index 9d091429ce095..c61fa6ee1700a 100644 --- a/pkg/pattern/iter/batch.go +++ b/pkg/pattern/iter/batch.go @@ -56,7 +56,7 @@ func ReadMetricsBatch(it iter.SampleIterator, batchSize int, logger log.Logger) series[hash] = s } - s.Samples = append(s.Samples, it.Sample()) + s.Samples = append(s.Samples, it.At()) series[hash] = s } @@ -68,7 +68,7 @@ func ReadMetricsBatch(it iter.SampleIterator, batchSize int, logger log.Logger) level.Debug(logger).Log("msg", "appending series", "s", fmt.Sprintf("%v", s)) result.Series = append(result.Series, s) } - return &result, it.Error() + return &result, it.Err() } // ReadAllSamples reads all samples from the given iterator. It is only used in tests. diff --git a/pkg/pattern/iter/iterator.go b/pkg/pattern/iter/iterator.go index 5a277c0f27349..7bbdb0ed2738b 100644 --- a/pkg/pattern/iter/iterator.go +++ b/pkg/pattern/iter/iterator.go @@ -6,6 +6,7 @@ import ( var Empty Iterator = &emptyIterator{} +// TODO(chaudum): inline v2.Iteratpr[logproto.PatternSample] type Iterator interface { Next() bool @@ -17,6 +18,7 @@ type Iterator interface { } func NewSlice(pattern string, s []logproto.PatternSample) Iterator { + // TODO(chaudum): replace with v2.NewSliceIter() return &sliceIterator{ values: s, pattern: pattern, diff --git a/pkg/pattern/iter/merge_sample.go b/pkg/pattern/iter/merge_sample.go index 7e8f250b48f26..a1f15c5c33c4c 100644 --- a/pkg/pattern/iter/merge_sample.go +++ b/pkg/pattern/iter/merge_sample.go @@ -78,7 +78,7 @@ func (i *sumMergeSampleIterator) requeue(ei iter.SampleIterator, advanced bool) return } - if err := ei.Error(); err != nil { + if err := ei.Err(); err != nil { i.errs = append(i.errs, err) } util.LogError("closing iterator", ei.Close) @@ -98,7 +98,7 @@ func (i *sumMergeSampleIterator) Next() bool { // shortcut for the last iterator. if i.heap.Len() == 1 { - i.curr.Sample = i.heap.Peek().Sample() + i.curr.Sample = i.heap.Peek().At() i.curr.labels = i.heap.Peek().Labels() i.curr.streamHash = i.heap.Peek().StreamHash() if !i.heap.Peek().Next() { @@ -112,7 +112,7 @@ func (i *sumMergeSampleIterator) Next() bool { // heap with the same timestamp, and add them to the buffer to sum their values. for i.heap.Len() > 0 { next := i.heap.Peek() - sample := next.Sample() + sample := next.At() if len(i.buffer) > 0 && (i.buffer[0].streamHash != next.StreamHash() || i.buffer[0].Timestamp != sample.Timestamp) { @@ -169,7 +169,7 @@ func (i *sumMergeSampleIterator) nextFromBuffer() { i.buffer = i.buffer[numSamples:] } -func (i *sumMergeSampleIterator) Sample() logproto.Sample { +func (i *sumMergeSampleIterator) At() logproto.Sample { return i.curr.Sample } @@ -181,7 +181,7 @@ func (i *sumMergeSampleIterator) StreamHash() uint64 { return i.curr.streamHash } -func (i *sumMergeSampleIterator) Error() error { +func (i *sumMergeSampleIterator) Err() error { switch len(i.errs) { case 0: return nil diff --git a/pkg/pattern/iter/merge_sample_test.go b/pkg/pattern/iter/merge_sample_test.go index 3f619ca44c3a6..298b5ac1c17b1 100644 --- a/pkg/pattern/iter/merge_sample_test.go +++ b/pkg/pattern/iter/merge_sample_test.go @@ -21,13 +21,13 @@ func TestNewSumMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="car"}`, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i)), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, `{foo="var"}`, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i)), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) @@ -45,13 +45,13 @@ func TestNewSumMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, `{foo="car"}`, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i*3)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i*3)), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, `{foo="var"}`, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i*3)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i*3)), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) @@ -73,13 +73,13 @@ func TestNewSumMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i)), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i)), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) @@ -121,13 +121,13 @@ func TestNewSumMergeSampleIterator(t *testing.T) { for i := 1; i < 4; i++ { require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i*3)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i*3)), it.At(), i) require.True(t, it.Next(), i) require.Equal(t, ``, it.Labels(), i) - require.Equal(t, sample(int64(i), float64(i*3)), it.Sample(), i) + require.Equal(t, sample(int64(i), float64(i*3)), it.At(), i) } require.False(t, it.Next()) - require.NoError(t, it.Error()) + require.NoError(t, it.Err()) require.NoError(t, it.Close()) }) t.Run("it sums the values from two identical points", func(t *testing.T) { @@ -146,15 +146,15 @@ func TestNewSumMergeSampleIterator(t *testing.T) { require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(1, 2), it.Sample()) + require.Equal(t, sample(1, 2), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(2, 4), it.Sample()) + require.Equal(t, sample(2, 4), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(3, 6), it.Sample()) + require.Equal(t, sample(3, 6), it.At()) require.False(t, it.Next()) }) @@ -189,31 +189,31 @@ func TestNewSumMergeSampleIterator(t *testing.T) { require.True(t, it.Next()) require.Equal(t, `{foo="baz"}`, it.Labels()) - require.Equal(t, sample(1, 1), it.Sample()) + require.Equal(t, sample(1, 1), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(1, 1), it.Sample()) // first only + require.Equal(t, sample(1, 1), it.At()) // first only require.True(t, it.Next()) require.Equal(t, `{foo="baz"}`, it.Labels()) - require.Equal(t, sample(2, 2), it.Sample()) + require.Equal(t, sample(2, 2), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(2, 4), it.Sample()) // merged + require.Equal(t, sample(2, 4), it.At()) // merged require.True(t, it.Next()) require.Equal(t, `{foo="baz"}`, it.Labels()) - require.Equal(t, sample(3, 4), it.Sample()) + require.Equal(t, sample(3, 4), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(3, 3), it.Sample()) + require.Equal(t, sample(3, 3), it.At()) require.True(t, it.Next()) require.Equal(t, `{foo="bar"}`, it.Labels()) - require.Equal(t, sample(4, 4), it.Sample()) // second only + require.Equal(t, sample(4, 4), it.At()) // second only require.False(t, it.Next()) }) diff --git a/pkg/pattern/iter/query_client.go b/pkg/pattern/iter/query_client.go index 997a2623b6f1b..8bb82b9be7504 100644 --- a/pkg/pattern/iter/query_client.go +++ b/pkg/pattern/iter/query_client.go @@ -99,8 +99,8 @@ func (i *querySamplesClientIterator) Next() bool { return true } -func (i *querySamplesClientIterator) Sample() logproto.Sample { - return i.curr.Sample() +func (i *querySamplesClientIterator) At() logproto.Sample { + return i.curr.At() } func (i *querySamplesClientIterator) StreamHash() uint64 { @@ -111,7 +111,7 @@ func (i *querySamplesClientIterator) Labels() string { return i.curr.Labels() } -func (i *querySamplesClientIterator) Error() error { +func (i *querySamplesClientIterator) Err() error { return i.err } diff --git a/pkg/querier/multi_tenant_querier_test.go b/pkg/querier/multi_tenant_querier_test.go index 38f190562ea1a..cac6f981651d7 100644 --- a/pkg/querier/multi_tenant_querier_test.go +++ b/pkg/querier/multi_tenant_querier_test.go @@ -97,7 +97,7 @@ func TestMultiTenantQuerier_SelectLogs(t *testing.T) { entriesCount := 0 for iter.Next() { require.Equal(t, tc.expLabels[entriesCount], iter.Labels()) - require.Equal(t, tc.expLines[entriesCount], iter.Entry().Line) + require.Equal(t, tc.expLines[entriesCount], iter.At().Line) entriesCount++ } require.Equalf(t, len(tc.expLabels), entriesCount, "Expected %d entries but got %d", len(tc.expLabels), entriesCount) @@ -256,7 +256,7 @@ func (it mockEntryIterator) Labels() string { return it.labels } -func (it mockEntryIterator) Entry() logproto.Entry { +func (it mockEntryIterator) At() logproto.Entry { return logproto.Entry{} } @@ -268,7 +268,7 @@ func (it mockEntryIterator) StreamHash() uint64 { return 0 } -func (it mockEntryIterator) Error() error { +func (it mockEntryIterator) Err() error { return nil } diff --git a/pkg/querier/querier.go b/pkg/querier/querier.go index 9f31cb9b82a34..f903317773776 100644 --- a/pkg/querier/querier.go +++ b/pkg/querier/querier.go @@ -1310,7 +1310,7 @@ func streamsForFieldDetection(i iter.EntryIterator, size uint32) (logqlmodel.Str // value here because many unit tests start at time.Unix(0,0) lastEntry := time.Unix(-100, 0) for respSize < size && i.Next() { - streamLabels, entry := i.Labels(), i.Entry() + streamLabels, entry := i.Labels(), i.At() // Always going backward as the direction for field detection is hard-coded to BACKWARD shouldOutput := entry.Timestamp.Equal(lastEntry) || entry.Timestamp.Before(lastEntry) @@ -1326,7 +1326,7 @@ func streamsForFieldDetection(i iter.EntryIterator, size uint32) (logqlmodel.Str streams[streamLabels] = stream } stream.Entries = append(stream.Entries, entry) - lastEntry = i.Entry().Timestamp + lastEntry = i.At().Timestamp respSize++ } } @@ -1336,5 +1336,5 @@ func streamsForFieldDetection(i iter.EntryIterator, size uint32) (logqlmodel.Str result = append(result, *stream) } sort.Sort(result) - return result, i.Error() + return result, i.Err() } diff --git a/pkg/querier/tail.go b/pkg/querier/tail.go index 1bdc01159ed65..56c5ef8f7e5ed 100644 --- a/pkg/querier/tail.go +++ b/pkg/querier/tail.go @@ -259,7 +259,7 @@ func (t *Tailer) next() bool { return false } - t.currEntry = t.openStreamIterator.Entry() + t.currEntry = t.openStreamIterator.At() t.currLabels = t.openStreamIterator.Labels() t.recordStream(t.openStreamIterator.StreamHash()) diff --git a/pkg/ruler/compat_test.go b/pkg/ruler/compat_test.go index 6855368aefdee..2097be3dec21e 100644 --- a/pkg/ruler/compat_test.go +++ b/pkg/ruler/compat_test.go @@ -118,11 +118,11 @@ func TestNonMetricQuery(t *testing.T) { type FakeQuerier struct{} func (q *FakeQuerier) SelectLogs(context.Context, logql.SelectLogParams) (iter.EntryIterator, error) { - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } func (q *FakeQuerier) SelectSamples(context.Context, logql.SelectSampleParams) (iter.SampleIterator, error) { - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } type fakeChecker struct{} diff --git a/pkg/storage/batch.go b/pkg/storage/batch.go index ff47345670ac9..46f708d09155a 100644 --- a/pkg/storage/batch.go +++ b/pkg/storage/batch.go @@ -352,12 +352,12 @@ func (it *logBatchIterator) StreamHash() uint64 { return it.curr.StreamHash() } -func (it *logBatchIterator) Error() error { +func (it *logBatchIterator) Err() error { if it.err != nil { return it.err } - if it.curr != nil && it.curr.Error() != nil { - return it.curr.Error() + if it.curr != nil && it.curr.Err() != nil { + return it.curr.Err() } if it.ctx.Err() != nil { return it.ctx.Err() @@ -373,8 +373,8 @@ func (it *logBatchIterator) Close() error { return nil } -func (it *logBatchIterator) Entry() logproto.Entry { - return it.curr.Entry() +func (it *logBatchIterator) At() logproto.Entry { + return it.curr.At() } func (it *logBatchIterator) Next() bool { @@ -497,12 +497,12 @@ func (it *sampleBatchIterator) StreamHash() uint64 { return it.curr.StreamHash() } -func (it *sampleBatchIterator) Error() error { +func (it *sampleBatchIterator) Err() error { if it.err != nil { return it.err } - if it.curr != nil && it.curr.Error() != nil { - return it.curr.Error() + if it.curr != nil && it.curr.Err() != nil { + return it.curr.Err() } if it.ctx.Err() != nil { return it.ctx.Err() @@ -518,8 +518,8 @@ func (it *sampleBatchIterator) Close() error { return nil } -func (it *sampleBatchIterator) Sample() logproto.Sample { - return it.curr.Sample() +func (it *sampleBatchIterator) At() logproto.Sample { + return it.curr.At() } func (it *sampleBatchIterator) Next() bool { diff --git a/pkg/storage/batch_test.go b/pkg/storage/batch_test.go index e041ad186fe89..0159c20a19f65 100644 --- a/pkg/storage/batch_test.go +++ b/pkg/storage/batch_test.go @@ -1745,7 +1745,7 @@ func TestBatchCancel(t *testing.T) { //nolint:revive for it.Next() { } - require.Equal(t, context.Canceled, it.Error()) + require.Equal(t, context.Canceled, it.Err()) } var entry logproto.Entry @@ -1784,7 +1784,7 @@ func Benchmark_store_OverlappingChunks(b *testing.B) { b.Fatal(err) } for it.Next() { - entry = it.Entry() + entry = it.At() } if err := it.Close(); err != nil { b.Fatal(err) diff --git a/pkg/storage/bloom/v1/archive_test.go b/pkg/storage/bloom/v1/archive_test.go index 63a321bca4f3f..8ebcdb9aebccf 100644 --- a/pkg/storage/bloom/v1/archive_test.go +++ b/pkg/storage/bloom/v1/archive_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" ) func TestArchive(t *testing.T) { @@ -32,7 +33,7 @@ func TestArchive(t *testing.T) { ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.Nil(t, err) diff --git a/pkg/storage/bloom/v1/bloom_tester.go b/pkg/storage/bloom/v1/bloom_tester.go index 80178a54deabe..349f3691f6ea0 100644 --- a/pkg/storage/bloom/v1/bloom_tester.go +++ b/pkg/storage/bloom/v1/bloom_tester.go @@ -5,6 +5,7 @@ import ( "github.com/grafana/regexp" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logql/log" "github.com/grafana/loki/v3/pkg/logql/log/pattern" "github.com/grafana/loki/v3/pkg/logql/syntax" @@ -176,7 +177,7 @@ func (n matchAllTest) MatchesWithPrefixBuf(_ filter.Checker, _ []byte, _ int) bo // Extracting this interface allows us to test the bloom filter without having to use the actual tokenizer // TODO: This should be moved to tokenizer.go type NGramBuilder interface { - Tokens(line string) Iterator[[]byte] + Tokens(line string) iter.Iterator[[]byte] N() int SkipFactor() int } diff --git a/pkg/storage/bloom/v1/bloom_tokenizer.go b/pkg/storage/bloom/v1/bloom_tokenizer.go index f0365f7cc78d8..7e3623aea9336 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer.go @@ -5,12 +5,12 @@ import ( "github.com/go-kit/log/level" + "github.com/grafana/loki/pkg/push" + "github.com/grafana/loki/v3/pkg/iter" + v2iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/storage/bloom/v1/filter" - - "github.com/grafana/loki/pkg/push" - "github.com/grafana/loki/v3/pkg/util/encoding" util_log "github.com/grafana/loki/v3/pkg/util/log" ) @@ -100,8 +100,8 @@ func (bt *BloomTokenizer) newBloom() *Bloom { // Populates a bloom filter(s) with the tokens from the given chunks. // Called once per series func (bt *BloomTokenizer) Populate( - blooms SizedIterator[*Bloom], - chks Iterator[ChunkRefWithIter], + blooms v2iter.SizedIterator[*Bloom], + chks v2iter.Iterator[ChunkRefWithIter], ch chan *BloomCreation, ) { clear(bt.cache) // MUST always clear the cache before starting a new series @@ -187,7 +187,7 @@ func (bt *BloomTokenizer) sendBloom( // so we can advance the iterator only after we're sure the bloom has accepted the line. // This is because the _line_ is the atom in Loki's data model and a query must either match (or not) an individual line. // Therefore, we index entire lines into a bloom to ensure a lookups are accurate. -func (bt *BloomTokenizer) addChunkToBloom(bloom *Bloom, ref ChunkRef, entryIter PeekingIterator[push.Entry]) (full bool, bytesAdded int) { +func (bt *BloomTokenizer) addChunkToBloom(bloom *Bloom, ref ChunkRef, entryIter v2iter.PeekIterator[push.Entry]) (full bool, bytesAdded int) { var ( tokenBuf, prefixLn = prefixedToken(bt.lineTokenizer.N(), ref, nil) tokens int @@ -204,7 +204,7 @@ outer: line := entry.Line chunkBytes += len(line) - tokenItrs := []Iterator[[]byte]{ + tokenItrs := []v2iter.Iterator[[]byte]{ // two iterators, one for the raw tokens and one for the chunk prefixed tokens. // Warning: the underlying line tokenizer (used in both iterators) uses the same buffer for tokens. // They are NOT SAFE for concurrent use. @@ -273,13 +273,13 @@ type entryIterAdapter struct { } func (a entryIterAdapter) At() logproto.Entry { - return a.EntryIterator.Entry() + return a.EntryIterator.At() } func (a entryIterAdapter) Err() error { - return a.EntryIterator.Error() + return a.EntryIterator.Err() } -func newPeekingEntryIterAdapter(itr iter.EntryIterator) *PeekIter[logproto.Entry] { - return NewPeekingIter[logproto.Entry](entryIterAdapter{itr}) +func newPeekingEntryIterAdapter(itr iter.EntryIterator) *v2iter.PeekIter[logproto.Entry] { + return v2iter.NewPeekIter[logproto.Entry](entryIterAdapter{itr}) } diff --git a/pkg/storage/bloom/v1/bloom_tokenizer_test.go b/pkg/storage/bloom/v1/bloom_tokenizer_test.go index 0f837fbee27bc..7023958eca112 100644 --- a/pkg/storage/bloom/v1/bloom_tokenizer_test.go +++ b/pkg/storage/bloom/v1/bloom_tokenizer_test.go @@ -14,6 +14,7 @@ import ( "github.com/grafana/loki/v3/pkg/chunkenc" "github.com/grafana/loki/v3/pkg/iter" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/logql/log" @@ -120,8 +121,8 @@ func TestTokenizerPopulate(t *testing.T) { blooms, err := populateAndConsumeBloom( bt, - NewSliceIter([]*Bloom{&bloom}), - NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, + v2.NewSliceIter([]*Bloom{&bloom}), + v2.NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, Itr: itr}}), ) require.NoError(t, err) @@ -155,8 +156,8 @@ func TestBloomTokenizerPopulateWithoutPreexistingBloom(t *testing.T) { blooms, err := populateAndConsumeBloom( bt, - NewEmptyIter[*Bloom](), - NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, + v2.NewEmptyIter[*Bloom](), + v2.NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, Itr: itr}}), ) require.NoError(t, err) @@ -211,12 +212,12 @@ func TestTokenizerPopulateWontExceedMaxSize(t *testing.T) { itr, err := chunkRefItrFromLines(line) require.NoError(t, err) go bt.Populate( - NewSliceIter([]*Bloom{ + v2.NewSliceIter([]*Bloom{ { *filter.NewScalableBloomFilter(1024, 0.01, 0.8), }, }), - NewSliceIter([]ChunkRefWithIter{ + v2.NewSliceIter([]ChunkRefWithIter{ { Ref: ChunkRef{}, Itr: itr, @@ -237,8 +238,8 @@ func TestTokenizerPopulateWontExceedMaxSize(t *testing.T) { func populateAndConsumeBloom( bt *BloomTokenizer, - blooms SizedIterator[*Bloom], - chks Iterator[ChunkRefWithIter], + blooms v2.SizedIterator[*Bloom], + chks v2.Iterator[ChunkRefWithIter], ) (res []*Bloom, err error) { var e multierror.MultiError ch := make(chan *BloomCreation) @@ -280,8 +281,8 @@ func BenchmarkPopulateSeriesWithBloom(b *testing.B) { _, err = populateAndConsumeBloom( bt, - NewSliceIter([]*Bloom{&bloom}), - NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, + v2.NewSliceIter([]*Bloom{&bloom}), + v2.NewSliceIter([]ChunkRefWithIter{{Ref: ChunkRef{}, Itr: itr}}), ) require.NoError(b, err) @@ -298,8 +299,8 @@ func TestTokenizerClearsCacheBetweenPopulateCalls(t *testing.T) { itr, err := chunkRefItrFromLines(line) require.NoError(t, err) go bt.Populate( - NewEmptyIter[*Bloom](), - NewSliceIter([]ChunkRefWithIter{ + v2.NewEmptyIter[*Bloom](), + v2.NewSliceIter([]ChunkRefWithIter{ { Ref: ChunkRef{}, Itr: itr, diff --git a/pkg/storage/bloom/v1/bounds.go b/pkg/storage/bloom/v1/bounds.go index 1b482e46665bf..d33a3dec6aa63 100644 --- a/pkg/storage/bloom/v1/bounds.go +++ b/pkg/storage/bloom/v1/bounds.go @@ -11,6 +11,7 @@ import ( "github.com/prometheus/common/model" "golang.org/x/exp/slices" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/logproto" "github.com/grafana/loki/v3/pkg/util/encoding" ) @@ -242,7 +243,7 @@ func (mb MultiFingerprintBounds) Union(target FingerprintBounds) MultiFingerprin // unused, but illustrative type BoundedIter[V any] struct { - Iterator[V] + iter.Iterator[V] cmp func(V) BoundsCheck } @@ -260,6 +261,6 @@ func (bi *BoundedIter[V]) Next() bool { return false } -func NewBoundedIter[V any](itr Iterator[V], cmp func(V) BoundsCheck) *BoundedIter[V] { +func NewBoundedIter[V any](itr iter.Iterator[V], cmp func(V) BoundsCheck) *BoundedIter[V] { return &BoundedIter[V]{Iterator: itr, cmp: cmp} } diff --git a/pkg/storage/bloom/v1/builder.go b/pkg/storage/bloom/v1/builder.go index 4ccd011fd1ec3..09a0dc2778f42 100644 --- a/pkg/storage/bloom/v1/builder.go +++ b/pkg/storage/bloom/v1/builder.go @@ -8,6 +8,7 @@ import ( "github.com/pkg/errors" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/util/encoding" ) @@ -160,23 +161,23 @@ type BloomCreation struct { // from a list of blocks and a store of series. type MergeBuilder struct { // existing blocks - blocks Iterator[*SeriesWithBlooms] + blocks iter.Iterator[*SeriesWithBlooms] // store - store Iterator[*Series] + store iter.Iterator[*Series] // Add chunks to a bloom - populate func(s *Series, srcBlooms SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) + populate func(s *Series, srcBlooms iter.SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) metrics *Metrics } -type BloomPopulatorFunc = func(s *Series, srcBlooms SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) +type BloomPopulatorFunc = func(s *Series, srcBlooms iter.SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) // NewMergeBuilder is a specific builder which does the following: // 1. merges multiple blocks into a single ordered querier, // i) When two blocks have the same series, it will prefer the one with the most chunks already indexed // 2. iterates through the store, adding chunks to the relevant blooms via the `populate` argument func NewMergeBuilder( - blocks Iterator[*SeriesWithBlooms], - store Iterator[*Series], + blocks iter.Iterator[*SeriesWithBlooms], + store iter.Iterator[*Series], populate BloomPopulatorFunc, metrics *Metrics, ) *MergeBuilder { @@ -184,13 +185,13 @@ func NewMergeBuilder( // because blooms dont contain the label-set (only the fingerprint), // in the case of a fingerprint collision we simply treat it as one // series with multiple chunks. - combinedSeriesIter := NewDedupingIter[*Series, *Series]( + combinedSeriesIter := iter.NewDedupingIter[*Series, *Series]( // eq func(s1, s2 *Series) bool { return s1.Fingerprint == s2.Fingerprint }, // from - Identity[*Series], + iter.Identity[*Series], // merge func(s1, s2 *Series) *Series { return &Series{ @@ -198,7 +199,7 @@ func NewMergeBuilder( Chunks: s1.Chunks.Union(s2.Chunks), } }, - NewPeekingIter[*Series](store), + iter.NewPeekIter[*Series](store), ) return &MergeBuilder{ @@ -256,8 +257,8 @@ func (mb *MergeBuilder) processNextSeries( var ( offsets []BloomOffset - chunksToAdd = nextInStore.Chunks - preExistingBlooms SizedIterator[*Bloom] = NewEmptyIter[*Bloom]() + chunksToAdd = nextInStore.Chunks + preExistingBlooms iter.SizedIterator[*Bloom] = iter.NewEmptyIter[*Bloom]() ) if nextInBlocks != nil && nextInBlocks.Series.Fingerprint == nextInStore.Fingerprint { diff --git a/pkg/storage/bloom/v1/builder_test.go b/pkg/storage/bloom/v1/builder_test.go index 15f0de0842a93..6abed637d7c79 100644 --- a/pkg/storage/bloom/v1/builder_test.go +++ b/pkg/storage/bloom/v1/builder_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage/bloom/v1/filter" "github.com/grafana/loki/v3/pkg/util/encoding" "github.com/grafana/loki/v3/pkg/util/mempool" @@ -101,9 +102,9 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { builder, err := NewBlockBuilder(blockOpts, tc.writer) require.Nil(t, err) - itr := NewPeekingIter[SeriesWithBlooms]( - NewMapIter( - NewSliceIter[SeriesWithLiteralBlooms](data), + itr := iter.NewPeekIter[SeriesWithBlooms]( + iter.NewMapIter( + iter.NewSliceIter[SeriesWithLiteralBlooms](data), func(x SeriesWithLiteralBlooms) SeriesWithBlooms { return x.SeriesWithBlooms() }, ), ) @@ -132,7 +133,7 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { for i := 0; i < len(processedData); i++ { require.Equal(t, true, querier.Next(), "on iteration %d with error %v", i, querier.Err()) got := querier.At() - blooms, err := Collect(got.Blooms) + blooms, err := iter.Collect(got.Blooms) require.Nil(t, err) require.Equal(t, processedData[i].Series, got.Series) for _, key := range keys[i] { @@ -159,7 +160,7 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { for j := 0; j < len(halfData); j++ { require.Equal(t, true, querier.Next(), "on iteration %d", j) got := querier.At() - blooms, err := Collect(got.Blooms) + blooms, err := iter.Collect(got.Blooms) require.Nil(t, err) require.Equal(t, halfData[j].Series, got.Series) for _, key := range halfKeys[j] { @@ -183,20 +184,20 @@ func TestBlockBuilder_RoundTrip(t *testing.T) { } } -func dedupedBlocks(blocks []PeekingIterator[*SeriesWithBlooms]) Iterator[*SeriesWithBlooms] { +func dedupedBlocks(blocks []iter.PeekIterator[*SeriesWithBlooms]) iter.Iterator[*SeriesWithBlooms] { orderedBlocks := NewHeapIterForSeriesWithBloom(blocks...) - return NewDedupingIter[*SeriesWithBlooms]( + return iter.NewDedupingIter[*SeriesWithBlooms]( func(a *SeriesWithBlooms, b *SeriesWithBlooms) bool { return a.Series.Fingerprint == b.Series.Fingerprint }, - Identity[*SeriesWithBlooms], + iter.Identity[*SeriesWithBlooms], func(a *SeriesWithBlooms, b *SeriesWithBlooms) *SeriesWithBlooms { if len(a.Series.Chunks) > len(b.Series.Chunks) { return a } return b }, - NewPeekingIter[*SeriesWithBlooms](orderedBlocks), + iter.NewPeekIter[*SeriesWithBlooms](orderedBlocks), ) } @@ -205,7 +206,7 @@ func TestMergeBuilder(t *testing.T) { nBlocks := 10 numSeries := 100 - blocks := make([]PeekingIterator[*SeriesWithBlooms], 0, nBlocks) + blocks := make([]iter.PeekIterator[*SeriesWithBlooms], 0, nBlocks) data, _ := MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) blockOpts := BlockOptions{ Schema: Schema{ @@ -237,14 +238,14 @@ func TestMergeBuilder(t *testing.T) { ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data[min:max]) + itr := iter.NewSliceIter[SeriesWithBlooms](data[min:max]) _, err = builder.BuildFrom(itr) require.Nil(t, err) - blocks = append(blocks, NewPeekingIter[*SeriesWithBlooms](NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize).Iter())) + blocks = append(blocks, iter.NewPeekIter[*SeriesWithBlooms](NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize).Iter())) } // We're not testing the ability to extend a bloom in this test - pop := func(s *Series, srcBlooms SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { + pop := func(s *Series, srcBlooms iter.SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { for srcBlooms.Next() { bloom := srcBlooms.At() ch <- &BloomCreation{ @@ -257,8 +258,8 @@ func TestMergeBuilder(t *testing.T) { // storage should contain references to all the series we ingested, // regardless of block allocation/overlap. - storeItr := NewMapIter[SeriesWithBlooms, *Series]( - NewSliceIter[SeriesWithBlooms](data), + storeItr := iter.NewMapIter[SeriesWithBlooms, *Series]( + iter.NewSliceIter[SeriesWithBlooms](data), func(swb SeriesWithBlooms) *Series { return swb.Series }, @@ -288,7 +289,7 @@ func TestMergeBuilder(t *testing.T) { func(a, b *SeriesWithBlooms) { require.Equal(t, a.Series, b.Series, "expected %+v, got %+v", a, b) }, - NewSliceIter[*SeriesWithBlooms](PointerSlice(data)), + iter.NewSliceIter[*SeriesWithBlooms](PointerSlice(data)), querier.Iter(), ) } @@ -352,7 +353,7 @@ func TestMergeBuilderFingerprintCollision(t *testing.T) { } // We're not testing the ability to extend a bloom in this test - pop := func(s *Series, srcBlooms SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { + pop := func(s *Series, srcBlooms iter.SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { ch <- &BloomCreation{ Bloom: &Bloom{ ScalableBloomFilter: *filter.NewScalableBloomFilter(1024, 0.01, 0.8), @@ -363,8 +364,8 @@ func TestMergeBuilderFingerprintCollision(t *testing.T) { require.Nil(t, err) mergeBuilder := NewMergeBuilder( - NewEmptyIter[*SeriesWithBlooms](), - NewSliceIter(data), + iter.NewEmptyIter[*SeriesWithBlooms](), + iter.NewSliceIter(data), pop, NewMetrics(nil), ) @@ -414,7 +415,7 @@ func TestBlockReset(t *testing.T) { ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := iter.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) @@ -479,7 +480,7 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { require.Nil(t, err) // each set of copies gets a different slice of the data minIdx, maxIdx := i*len(xs)/len(sets), (i+1)*len(xs)/len(sets) - itr := NewSliceIter[SeriesWithBlooms](xs[minIdx:maxIdx]) + itr := iter.NewSliceIter[SeriesWithBlooms](xs[minIdx:maxIdx]) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) @@ -497,16 +498,16 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { // we keep 2 copies of the data as iterators. One for the blocks, and one for the "store" // which will force it to reference the same series - var blocks []PeekingIterator[*SeriesWithBlooms] - var store []PeekingIterator[*SeriesWithBlooms] + var blocks []iter.PeekIterator[*SeriesWithBlooms] + var store []iter.PeekIterator[*SeriesWithBlooms] for _, x := range data { - blocks = append(blocks, NewPeekingIter[*SeriesWithBlooms](NewSliceIter[*SeriesWithBlooms](x))) - store = append(store, NewPeekingIter[*SeriesWithBlooms](NewSliceIter[*SeriesWithBlooms](x))) + blocks = append(blocks, iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](x))) + store = append(store, iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](x))) } orderedStore := NewHeapIterForSeriesWithBloom(store...) - dedupedStore := NewDedupingIter[*SeriesWithBlooms, *Series]( + dedupedStore := iter.NewDedupingIter[*SeriesWithBlooms, *Series]( func(a *SeriesWithBlooms, b *Series) bool { return a.Series.Fingerprint == b.Fingerprint }, @@ -519,11 +520,11 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { } return b }, - NewPeekingIter[*SeriesWithBlooms](orderedStore), + iter.NewPeekIter[*SeriesWithBlooms](orderedStore), ) // We're not testing the ability to extend a bloom in this test - pop := func(s *Series, srcBlooms SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { + pop := func(s *Series, srcBlooms iter.SizedIterator[*Bloom], toAdd ChunkRefs, ch chan *BloomCreation) { for srcBlooms.Next() { bloom := srcBlooms.At() ch <- &BloomCreation{ @@ -554,7 +555,7 @@ func TestMergeBuilder_Roundtrip(t *testing.T) { // ensure the new block contains one copy of all the data // by comparing it against an iterator over the source data mergedBlockQuerier := NewBlockQuerier(NewBlock(reader, NewMetrics(nil)), &mempool.SimpleHeapAllocator{}, DefaultMaxPageSize) - sourceItr := NewSliceIter[*SeriesWithBlooms](PointerSlice[SeriesWithBlooms](xs)) + sourceItr := iter.NewSliceIter[*SeriesWithBlooms](PointerSlice[SeriesWithBlooms](xs)) EqualIterators[*SeriesWithBlooms]( t, diff --git a/pkg/storage/bloom/v1/dedupe_test.go b/pkg/storage/bloom/v1/dedupe_test.go index e008bee6834c1..8c4dd43629b5a 100644 --- a/pkg/storage/bloom/v1/dedupe_test.go +++ b/pkg/storage/bloom/v1/dedupe_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/stretchr/testify/require" + + iter "github.com/grafana/loki/v3/pkg/iter/v2" ) func TestMergeDedupeIter(t *testing.T) { @@ -12,11 +14,11 @@ func TestMergeDedupeIter(t *testing.T) { numSeries = 100 data, _ = MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) dataPtr = PointerSlice(data) - queriers = make([]PeekingIterator[*SeriesWithBlooms], 4) + queriers = make([]iter.PeekIterator[*SeriesWithBlooms], 4) ) for i := 0; i < len(queriers); i++ { - queriers[i] = NewPeekingIter[*SeriesWithBlooms](NewSliceIter[*SeriesWithBlooms](dataPtr)) + queriers[i] = iter.NewPeekIter[*SeriesWithBlooms](iter.NewSliceIter[*SeriesWithBlooms](dataPtr)) } mbq := NewHeapIterForSeriesWithBloom(queriers...) @@ -26,11 +28,11 @@ func TestMergeDedupeIter(t *testing.T) { merge := func(a, _ *SeriesWithBlooms) *SeriesWithBlooms { return a } - deduper := NewDedupingIter[*SeriesWithBlooms, *SeriesWithBlooms]( + deduper := iter.NewDedupingIter[*SeriesWithBlooms, *SeriesWithBlooms]( eq, - Identity[*SeriesWithBlooms], + iter.Identity[*SeriesWithBlooms], merge, - NewPeekingIter[*SeriesWithBlooms](mbq), + iter.NewPeekIter[*SeriesWithBlooms](mbq), ) for i := 0; i < len(data); i++ { diff --git a/pkg/storage/bloom/v1/fuse.go b/pkg/storage/bloom/v1/fuse.go index 435299d129717..3e14e57c58065 100644 --- a/pkg/storage/bloom/v1/fuse.go +++ b/pkg/storage/bloom/v1/fuse.go @@ -9,6 +9,7 @@ import ( "github.com/prometheus/common/model" "go.uber.org/atomic" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/util/spanlogger" ) @@ -125,17 +126,17 @@ type Output struct { // Fuse combines multiple requests into a single loop iteration // over the data set and returns the corresponding outputs // TODO(owen-d): better async control -func (bq *BlockQuerier) Fuse(inputs []PeekingIterator[Request], logger log.Logger) *FusedQuerier { +func (bq *BlockQuerier) Fuse(inputs []iter.PeekIterator[Request], logger log.Logger) *FusedQuerier { return NewFusedQuerier(bq, inputs, logger) } type FusedQuerier struct { bq *BlockQuerier - inputs Iterator[[]Request] + inputs iter.Iterator[[]Request] logger log.Logger } -func NewFusedQuerier(bq *BlockQuerier, inputs []PeekingIterator[Request], logger log.Logger) *FusedQuerier { +func NewFusedQuerier(bq *BlockQuerier, inputs []iter.PeekIterator[Request], logger log.Logger) *FusedQuerier { heap := NewHeapIterator[Request]( func(a, b Request) bool { return a.Fp < b.Fp @@ -143,7 +144,7 @@ func NewFusedQuerier(bq *BlockQuerier, inputs []PeekingIterator[Request], logger inputs..., ) - merging := NewDedupingIter[Request, []Request]( + merging := iter.NewDedupingIter[Request, []Request]( func(a Request, b []Request) bool { return a.Fp == b[0].Fp }, @@ -151,7 +152,7 @@ func NewFusedQuerier(bq *BlockQuerier, inputs []PeekingIterator[Request], logger func(a Request, b []Request) []Request { return append(b, a) }, - NewPeekingIter[Request](heap), + iter.NewPeekIter[Request](heap), ) return &FusedQuerier{ bq: bq, diff --git a/pkg/storage/bloom/v1/fuse_test.go b/pkg/storage/bloom/v1/fuse_test.go index 7459819658937..47c9348b3fe5c 100644 --- a/pkg/storage/bloom/v1/fuse_test.go +++ b/pkg/storage/bloom/v1/fuse_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage/bloom/v1/filter" "github.com/grafana/loki/v3/pkg/util/mempool" ) @@ -31,8 +32,8 @@ type fakeNgramBuilder struct{} func (f fakeNgramBuilder) N() int { return 4 } func (f fakeNgramBuilder) SkipFactor() int { return 0 } -func (f fakeNgramBuilder) Tokens(line string) Iterator[[]byte] { - return NewSliceIter[[]byte]([][]byte{[]byte(line)}) +func (f fakeNgramBuilder) Tokens(line string) v2.Iterator[[]byte] { + return v2.NewSliceIter[[]byte]([][]byte{[]byte(line)}) } func keysToBloomTest(keys [][]byte) BloomTest { @@ -66,7 +67,7 @@ func TestFusedQuerier(t *testing.T) { writer, ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.NoError(t, err) require.False(t, itr.Next()) @@ -95,9 +96,9 @@ func TestFusedQuerier(t *testing.T) { resChans = append(resChans, ch) } - var itrs []PeekingIterator[Request] + var itrs []v2.PeekIterator[Request] for _, reqs := range inputs { - itrs = append(itrs, NewPeekingIter[Request](NewSliceIter[Request](reqs))) + itrs = append(itrs, v2.NewPeekIter[Request](v2.NewSliceIter[Request](reqs))) } resps := make([][]Output, nReqs) @@ -189,10 +190,10 @@ func TestFuseMultiPage(t *testing.T) { b2.Add(key2) b2.Add(append(buf[:prefixLn], key2...)) - _, err = builder.BuildFrom(NewSliceIter([]SeriesWithBlooms{ + _, err = builder.BuildFrom(v2.NewSliceIter([]SeriesWithBlooms{ { series, - NewSliceIter([]*Bloom{ + v2.NewSliceIter([]*Bloom{ b1, b2, }), }, @@ -231,8 +232,8 @@ func TestFuseMultiPage(t *testing.T) { } fused := querier.Fuse( - []PeekingIterator[Request]{ - NewPeekingIter(NewSliceIter(reqs)), + []v2.PeekIterator[Request]{ + v2.NewPeekIter(v2.NewSliceIter(reqs)), }, log.NewNopLogger(), ) @@ -300,7 +301,7 @@ func TestLazyBloomIter_Seek_ResetError(t *testing.T) { data = append(data, SeriesWithBlooms{ Series: &series, - Blooms: NewSliceIter([]*Bloom{&bloom}), + Blooms: v2.NewSliceIter([]*Bloom{&bloom}), }) } @@ -316,7 +317,7 @@ func TestLazyBloomIter_Seek_ResetError(t *testing.T) { writer, ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.NoError(t, err) require.False(t, itr.Next()) @@ -375,7 +376,7 @@ func setupBlockForBenchmark(b *testing.B) (*BlockQuerier, [][]Request, []chan Ou writer, ) require.Nil(b, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := v2.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.Nil(b, err) block := NewBlock(reader, NewMetrics(nil)) @@ -432,12 +433,12 @@ func BenchmarkBlockQuerying(b *testing.B) { )) }() - var itrs []PeekingIterator[Request] + var itrs []v2.PeekIterator[Request] for i := 0; i < b.N; i++ { itrs = itrs[:0] for _, reqs := range requestChains { - itrs = append(itrs, NewPeekingIter[Request](NewSliceIter[Request](reqs))) + itrs = append(itrs, v2.NewPeekIter[Request](v2.NewSliceIter[Request](reqs))) } fused := querier.Fuse(itrs, log.NewNopLogger()) _ = fused.Run() diff --git a/pkg/storage/bloom/v1/index_querier.go b/pkg/storage/bloom/v1/index_querier.go index ef270551952ba..7fdaa4617571f 100644 --- a/pkg/storage/bloom/v1/index_querier.go +++ b/pkg/storage/bloom/v1/index_querier.go @@ -5,10 +5,12 @@ import ( "github.com/efficientgo/core/errors" "github.com/prometheus/common/model" + + iter "github.com/grafana/loki/v3/pkg/iter/v2" ) type SeriesIterator interface { - Iterator[*SeriesWithOffset] + iter.Iterator[*SeriesWithOffset] Reset() } diff --git a/pkg/storage/bloom/v1/iter.go b/pkg/storage/bloom/v1/iter.go deleted file mode 100644 index b1b460fb64207..0000000000000 --- a/pkg/storage/bloom/v1/iter.go +++ /dev/null @@ -1,70 +0,0 @@ -package v1 - -type IndexedValue[T any] struct { - idx int - val T -} - -func (iv IndexedValue[T]) Value() T { - return iv.val -} - -func (iv IndexedValue[T]) Index() int { - return iv.idx -} - -type IterWithIndex[T any] struct { - Iterator[T] - zero T // zero value of T - cache IndexedValue[T] -} - -func (it *IterWithIndex[T]) At() IndexedValue[T] { - it.cache.val = it.Iterator.At() - return it.cache -} - -func NewIterWithIndex[T any](iter Iterator[T], idx int) Iterator[IndexedValue[T]] { - return &IterWithIndex[T]{ - Iterator: iter, - cache: IndexedValue[T]{idx: idx}, - } -} - -type SliceIterWithIndex[T any] struct { - xs []T // source slice - pos int // position within the slice - zero T // zero value of T - cache IndexedValue[T] -} - -func (it *SliceIterWithIndex[T]) Next() bool { - it.pos++ - return it.pos < len(it.xs) -} - -func (it *SliceIterWithIndex[T]) Err() error { - return nil -} - -func (it *SliceIterWithIndex[T]) At() IndexedValue[T] { - it.cache.val = it.xs[it.pos] - return it.cache -} - -func (it *SliceIterWithIndex[T]) Peek() (IndexedValue[T], bool) { - if it.pos+1 >= len(it.xs) { - it.cache.val = it.zero - return it.cache, false - } - it.cache.val = it.xs[it.pos+1] - return it.cache, true -} - -func NewSliceIterWithIndex[T any](xs []T, idx int) PeekingIterator[IndexedValue[T]] { - return &SliceIterWithIndex[T]{ - xs: xs, - pos: -1, - cache: IndexedValue[T]{idx: idx}, - } -} diff --git a/pkg/storage/bloom/v1/iter_test.go b/pkg/storage/bloom/v1/iter_test.go deleted file mode 100644 index 91604dd27868c..0000000000000 --- a/pkg/storage/bloom/v1/iter_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package v1 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSliceIterWithIndex(t *testing.T) { - t.Parallel() - t.Run("SliceIterWithIndex implements PeekingIterator interface", func(t *testing.T) { - xs := []string{"a", "b", "c"} - it := NewSliceIterWithIndex(xs, 123) - - // peek at first item - p, ok := it.Peek() - require.True(t, ok) - require.Equal(t, "a", p.val) - require.Equal(t, 123, p.idx) - - // proceed to first item - require.True(t, it.Next()) - require.Equal(t, "a", it.At().val) - require.Equal(t, 123, it.At().idx) - - // proceed to second and third item - require.True(t, it.Next()) - require.True(t, it.Next()) - - // peek at non-existing fourth item - p, ok = it.Peek() - require.False(t, ok) - require.Equal(t, "", p.val) // "" is zero value for type string - require.Equal(t, 123, p.idx) - }) -} diff --git a/pkg/storage/bloom/v1/merge.go b/pkg/storage/bloom/v1/merge.go index d89ca2a7d7f96..0e94d0d506408 100644 --- a/pkg/storage/bloom/v1/merge.go +++ b/pkg/storage/bloom/v1/merge.go @@ -1,11 +1,15 @@ package v1 +import ( + iter "github.com/grafana/loki/v3/pkg/iter/v2" +) + // HeapIterator is a heap implementation of BlockQuerier backed by multiple blocks // It is used to merge multiple blocks into a single ordered querier // NB(owen-d): it uses a custom heap implementation because Pop() only returns a single // value of the top-most iterator, rather than the iterator itself type HeapIterator[T any] struct { - itrs []PeekingIterator[T] + itrs []iter.PeekIterator[T] less func(T, T) bool zero T // zero value of T @@ -13,7 +17,7 @@ type HeapIterator[T any] struct { ok bool } -func NewHeapIterForSeriesWithBloom(queriers ...PeekingIterator[*SeriesWithBlooms]) *HeapIterator[*SeriesWithBlooms] { +func NewHeapIterForSeriesWithBloom(queriers ...iter.PeekIterator[*SeriesWithBlooms]) *HeapIterator[*SeriesWithBlooms] { return NewHeapIterator( func(a, b *SeriesWithBlooms) bool { return a.Series.Fingerprint < b.Series.Fingerprint @@ -22,7 +26,7 @@ func NewHeapIterForSeriesWithBloom(queriers ...PeekingIterator[*SeriesWithBlooms ) } -func NewHeapIterator[T any](less func(T, T) bool, itrs ...PeekingIterator[T]) *HeapIterator[T] { +func NewHeapIterator[T any](less func(T, T) bool, itrs ...iter.PeekIterator[T]) *HeapIterator[T] { res := &HeapIterator[T]{ itrs: itrs, less: less, @@ -65,7 +69,7 @@ func (mbq *HeapIterator[T]) At() T { return mbq.cache } -func (mbq *HeapIterator[T]) push(x PeekingIterator[T]) { +func (mbq *HeapIterator[T]) push(x iter.PeekIterator[T]) { mbq.itrs = append(mbq.itrs, x) mbq.up(mbq.Len() - 1) } diff --git a/pkg/storage/bloom/v1/merge_test.go b/pkg/storage/bloom/v1/merge_test.go index 259888ae064d0..f57c629d75429 100644 --- a/pkg/storage/bloom/v1/merge_test.go +++ b/pkg/storage/bloom/v1/merge_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/stretchr/testify/require" + + v2 "github.com/grafana/loki/v3/pkg/iter/v2" ) func TestMergeBlockQuerier_NonOverlapping(t *testing.T) { @@ -11,7 +13,7 @@ func TestMergeBlockQuerier_NonOverlapping(t *testing.T) { var ( numSeries = 100 numQueriers = 4 - queriers []PeekingIterator[*SeriesWithBlooms] + queriers []v2.PeekIterator[*SeriesWithBlooms] data, _ = MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) ) for i := 0; i < numQueriers; i++ { @@ -19,7 +21,7 @@ func TestMergeBlockQuerier_NonOverlapping(t *testing.T) { for j := 0; j < numSeries/numQueriers; j++ { ptrs = append(ptrs, &data[i*numSeries/numQueriers+j]) } - queriers = append(queriers, NewPeekingIter[*SeriesWithBlooms](NewSliceIter[*SeriesWithBlooms](ptrs))) + queriers = append(queriers, v2.NewPeekIter[*SeriesWithBlooms](v2.NewSliceIter[*SeriesWithBlooms](ptrs))) } mbq := NewHeapIterForSeriesWithBloom(queriers...) @@ -38,14 +40,14 @@ func TestMergeBlockQuerier_Duplicate(t *testing.T) { var ( numSeries = 100 numQueriers = 2 - queriers []PeekingIterator[*SeriesWithBlooms] + queriers []v2.PeekIterator[*SeriesWithBlooms] data, _ = MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) ) for i := 0; i < numQueriers; i++ { queriers = append( queriers, - NewPeekingIter[*SeriesWithBlooms]( - NewSliceIter[*SeriesWithBlooms]( + v2.NewPeekIter[*SeriesWithBlooms]( + v2.NewSliceIter[*SeriesWithBlooms]( PointerSlice[SeriesWithBlooms](data), ), ), @@ -69,7 +71,7 @@ func TestMergeBlockQuerier_Overlapping(t *testing.T) { var ( numSeries = 100 numQueriers = 4 - queriers []PeekingIterator[*SeriesWithBlooms] + queriers []v2.PeekIterator[*SeriesWithBlooms] data, _ = MkBasicSeriesWithBlooms(numSeries, 0, 0xffff, 0, 10000) slices = make([][]*SeriesWithBlooms, numQueriers) ) @@ -77,7 +79,7 @@ func TestMergeBlockQuerier_Overlapping(t *testing.T) { slices[i%numQueriers] = append(slices[i%numQueriers], &data[i]) } for i := 0; i < numQueriers; i++ { - queriers = append(queriers, NewPeekingIter[*SeriesWithBlooms](NewSliceIter[*SeriesWithBlooms](slices[i]))) + queriers = append(queriers, v2.NewPeekIter[*SeriesWithBlooms](v2.NewSliceIter[*SeriesWithBlooms](slices[i]))) } mbq := NewHeapIterForSeriesWithBloom(queriers...) diff --git a/pkg/storage/bloom/v1/reader.go b/pkg/storage/bloom/v1/reader.go index d73ce38c1ca8d..d402ee1fd9717 100644 --- a/pkg/storage/bloom/v1/reader.go +++ b/pkg/storage/bloom/v1/reader.go @@ -7,12 +7,14 @@ import ( "path/filepath" "github.com/pkg/errors" + + iter "github.com/grafana/loki/v3/pkg/iter/v2" ) type BlockReader interface { Index() (io.ReadSeeker, error) Blooms() (io.ReadSeeker, error) - TarEntries() (Iterator[TarEntry], error) + TarEntries() (iter.Iterator[TarEntry], error) } // In memory reader @@ -32,7 +34,7 @@ func (r *ByteReader) Blooms() (io.ReadSeeker, error) { return bytes.NewReader(r.blooms.Bytes()), nil } -func (r *ByteReader) TarEntries() (Iterator[TarEntry], error) { +func (r *ByteReader) TarEntries() (iter.Iterator[TarEntry], error) { indexLn := r.index.Len() index, err := r.Index() if err != nil { @@ -56,7 +58,7 @@ func (r *ByteReader) TarEntries() (Iterator[TarEntry], error) { }, } - return NewSliceIter[TarEntry](entries), err + return iter.NewSliceIter[TarEntry](entries), err } // File reader @@ -110,7 +112,7 @@ func (r *DirectoryBlockReader) Blooms() (io.ReadSeeker, error) { return r.blooms, nil } -func (r *DirectoryBlockReader) TarEntries() (Iterator[TarEntry], error) { +func (r *DirectoryBlockReader) TarEntries() (iter.Iterator[TarEntry], error) { if !r.initialized { if err := r.Init(); err != nil { return nil, err @@ -140,5 +142,5 @@ func (r *DirectoryBlockReader) TarEntries() (Iterator[TarEntry], error) { }, } - return NewSliceIter[TarEntry](entries), nil + return iter.NewSliceIter[TarEntry](entries), nil } diff --git a/pkg/storage/bloom/v1/test_util.go b/pkg/storage/bloom/v1/test_util.go index 9c1fb6047497b..4fbbfa8d7bc1d 100644 --- a/pkg/storage/bloom/v1/test_util.go +++ b/pkg/storage/bloom/v1/test_util.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + iter "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/storage/bloom/v1/filter" ) @@ -38,7 +39,7 @@ func MakeBlock(t testing.TB, nth int, fromFp, throughFp model.Fingerprint, fromT writer, ) require.Nil(t, err) - itr := NewSliceIter[SeriesWithBlooms](data) + itr := iter.NewSliceIter[SeriesWithBlooms](data) _, err = builder.BuildFrom(itr) require.Nil(t, err) block := NewBlock(reader, NewMetrics(nil)) @@ -55,7 +56,7 @@ type SeriesWithLiteralBlooms struct { func (s *SeriesWithLiteralBlooms) SeriesWithBlooms() SeriesWithBlooms { return SeriesWithBlooms{ Series: s.Series, - Blooms: NewSliceIter[*Bloom](s.Blooms), + Blooms: iter.NewSliceIter[*Bloom](s.Blooms), } } @@ -124,7 +125,7 @@ func MkBasicSeriesWithLiteralBlooms(nSeries int, fromFp, throughFp model.Fingerp return } -func EqualIterators[T any](t *testing.T, test func(a, b T), expected, actual Iterator[T]) { +func EqualIterators[T any](t *testing.T, test func(a, b T), expected, actual iter.Iterator[T]) { for expected.Next() { require.True(t, actual.Next()) a, b := expected.At(), actual.At() @@ -142,8 +143,8 @@ func EqualIterators[T any](t *testing.T, test func(a, b T), expected, actual Ite func CompareIterators[A, B any]( t *testing.T, f func(t *testing.T, a A, b B), - a Iterator[A], - b Iterator[B], + a iter.Iterator[A], + b iter.Iterator[B], ) { for a.Next() { require.True(t, b.Next()) diff --git a/pkg/storage/bloom/v1/tokenizer.go b/pkg/storage/bloom/v1/tokenizer.go index 131a1d057edf5..dcd7c21468691 100644 --- a/pkg/storage/bloom/v1/tokenizer.go +++ b/pkg/storage/bloom/v1/tokenizer.go @@ -2,6 +2,8 @@ package v1 import ( "unicode/utf8" + + iter "github.com/grafana/loki/v3/pkg/iter/v2" ) const ( @@ -51,7 +53,7 @@ func NewNGramTokenizer(n, skip int) *NGramTokenizer { // Token implements the NGramBuilder interface // The Token iterator uses shared buffers for performance. The []byte returned by At() // is not safe for use after subsequent calls to Next() -func (t *NGramTokenizer) Tokens(line string) Iterator[[]byte] { +func (t *NGramTokenizer) Tokens(line string) iter.Iterator[[]byte] { return &NGramTokenIter{ n: t.N(), skip: t.SkipFactor(), @@ -108,17 +110,17 @@ type PrefixedTokenIter struct { buf []byte prefixLen int - Iterator[[]byte] + iter.Iterator[[]byte] } func (t *PrefixedTokenIter) At() []byte { return append(t.buf[:t.prefixLen], t.Iterator.At()...) } -func NewPrefixedTokenIter(buf []byte, prefixLn int, iter Iterator[[]byte]) *PrefixedTokenIter { +func NewPrefixedTokenIter(buf []byte, prefixLn int, itr iter.Iterator[[]byte]) *PrefixedTokenIter { return &PrefixedTokenIter{ buf: buf, prefixLen: prefixLn, - Iterator: iter, + Iterator: itr, } } diff --git a/pkg/storage/bloom/v1/util.go b/pkg/storage/bloom/v1/util.go index ae0a70453098d..ec46d2633b7ad 100644 --- a/pkg/storage/bloom/v1/util.go +++ b/pkg/storage/bloom/v1/util.go @@ -1,7 +1,6 @@ package v1 import ( - "context" "fmt" "hash" "hash/crc32" @@ -65,181 +64,6 @@ func (p *ChecksumPool) Put(h hash.Hash32) { p.Pool.Put(h) } -type Iterator[T any] interface { - Next() bool - Err() error - At() T -} - -type SizedIterator[T any] interface { - Iterator[T] - Remaining() int // remaining -} - -type PeekingIterator[T any] interface { - Peek() (T, bool) - Iterator[T] -} - -type PeekIter[T any] struct { - itr Iterator[T] - - // the first call to Next() will populate cur & next - init bool - zero T // zero value of T for returning empty Peek's - cur, next *T -} - -func NewPeekingIter[T any](itr Iterator[T]) *PeekIter[T] { - return &PeekIter[T]{itr: itr} -} - -// populates the first element so Peek can be used and subsequent Next() -// calls will work as expected -func (it *PeekIter[T]) ensureInit() { - if it.init { - return - } - if it.itr.Next() { - at := it.itr.At() - it.next = &at - } - it.init = true -} - -// load the next element and return the cached one -func (it *PeekIter[T]) cacheNext() { - it.cur = it.next - if it.cur != nil && it.itr.Next() { - at := it.itr.At() - it.next = &at - } else { - it.next = nil - } -} - -func (it *PeekIter[T]) Next() bool { - it.ensureInit() - it.cacheNext() - return it.cur != nil -} - -func (it *PeekIter[T]) Peek() (T, bool) { - it.ensureInit() - if it.next == nil { - return it.zero, false - } - return *it.next, true -} - -func (it *PeekIter[T]) Err() error { - return it.itr.Err() -} - -func (it *PeekIter[T]) At() T { - return *it.cur -} - -type SeekIter[K, V any] interface { - Seek(K) error - Iterator[V] -} - -type SliceIter[T any] struct { - cur int - xs []T -} - -func NewSliceIter[T any](xs []T) *SliceIter[T] { - return &SliceIter[T]{xs: xs, cur: -1} -} - -func (it *SliceIter[T]) Remaining() int { - return max(0, len(it.xs)-(it.cur+1)) -} - -func (it *SliceIter[T]) Next() bool { - it.cur++ - return it.cur < len(it.xs) -} - -func (it *SliceIter[T]) Err() error { - return nil -} - -func (it *SliceIter[T]) At() T { - return it.xs[it.cur] -} - -type MapIter[A any, B any] struct { - Iterator[A] - f func(A) B -} - -func NewMapIter[A any, B any](src Iterator[A], f func(A) B) *MapIter[A, B] { - return &MapIter[A, B]{Iterator: src, f: f} -} - -func (it *MapIter[A, B]) At() B { - return it.f(it.Iterator.At()) -} - -type EmptyIter[T any] struct { - zero T -} - -func (it *EmptyIter[T]) Next() bool { - return false -} - -func (it *EmptyIter[T]) Err() error { - return nil -} - -func (it *EmptyIter[T]) At() T { - return it.zero -} - -func (it *EmptyIter[T]) Peek() (T, bool) { - return it.zero, false -} - -func (it *EmptyIter[T]) Remaining() int { - return 0 -} - -// noop -func (it *EmptyIter[T]) Reset() {} - -func NewEmptyIter[T any]() *EmptyIter[T] { - return &EmptyIter[T]{} -} - -type CancellableIter[T any] struct { - ctx context.Context - Iterator[T] -} - -func (cii *CancellableIter[T]) Next() bool { - select { - case <-cii.ctx.Done(): - return false - default: - return cii.Iterator.Next() - } -} - -func (cii *CancellableIter[T]) Err() error { - if err := cii.ctx.Err(); err != nil { - return err - } - return cii.Iterator.Err() -} - -func NewCancelableIter[T any](ctx context.Context, itr Iterator[T]) *CancellableIter[T] { - return &CancellableIter[T]{ctx: ctx, Iterator: itr} -} - type NoopCloser struct { io.Writer } @@ -259,96 +83,3 @@ func PointerSlice[T any](xs []T) []*T { } return out } - -type CloseableIterator[T any] interface { - Iterator[T] - Close() error -} - -func NewCloseableIterator[T io.Closer](itr Iterator[T]) *CloseIter[T] { - return &CloseIter[T]{itr} -} - -type CloseIter[T io.Closer] struct { - Iterator[T] -} - -func (i *CloseIter[T]) Close() error { - return i.At().Close() -} - -type PeekingCloseableIterator[T any] interface { - PeekingIterator[T] - CloseableIterator[T] -} - -type PeekCloseIter[T any] struct { - *PeekIter[T] - close func() error -} - -func NewPeekCloseIter[T any](itr CloseableIterator[T]) *PeekCloseIter[T] { - return &PeekCloseIter[T]{PeekIter: NewPeekingIter[T](itr), close: itr.Close} -} - -func (it *PeekCloseIter[T]) Close() error { - return it.close() -} - -type ResettableIterator[T any] interface { - Reset() error - Iterator[T] -} - -type CloseableResettableIterator[T any] interface { - CloseableIterator[T] - ResettableIterator[T] -} - -type Predicate[T any] func(T) bool - -func NewFilterIter[T any](it Iterator[T], p Predicate[T]) *FilterIter[T] { - return &FilterIter[T]{ - Iterator: it, - match: p, - } -} - -type FilterIter[T any] struct { - Iterator[T] - match Predicate[T] -} - -func (i *FilterIter[T]) Next() bool { - hasNext := i.Iterator.Next() - for hasNext && !i.match(i.Iterator.At()) { - hasNext = i.Iterator.Next() - } - return hasNext -} - -type CounterIterator[T any] interface { - Iterator[T] - Count() int -} - -type CounterIter[T any] struct { - Iterator[T] // the underlying iterator - count int -} - -func NewCounterIter[T any](itr Iterator[T]) *CounterIter[T] { - return &CounterIter[T]{Iterator: itr} -} - -func (it *CounterIter[T]) Next() bool { - if it.Iterator.Next() { - it.count++ - return true - } - return false -} - -func (it *CounterIter[T]) Count() int { - return it.count -} diff --git a/pkg/storage/bloom/v1/versioned_builder.go b/pkg/storage/bloom/v1/versioned_builder.go index 8b262ee62e557..175d651dc460c 100644 --- a/pkg/storage/bloom/v1/versioned_builder.go +++ b/pkg/storage/bloom/v1/versioned_builder.go @@ -1,6 +1,10 @@ package v1 -import "github.com/pkg/errors" +import ( + "github.com/pkg/errors" + + iter "github.com/grafana/loki/v3/pkg/iter/v2" +) /* Each binary format (version) has it's own builder. This provides type-safe way to build the binary format @@ -34,7 +38,7 @@ type V2Builder struct { type SeriesWithBlooms struct { Series *Series - Blooms SizedIterator[*Bloom] + Blooms iter.SizedIterator[*Bloom] } func NewBlockBuilderV2(opts BlockOptions, writer BlockWriter) (*V2Builder, error) { @@ -59,7 +63,7 @@ func NewBlockBuilderV2(opts BlockOptions, writer BlockWriter) (*V2Builder, error }, nil } -func (b *V2Builder) BuildFrom(itr Iterator[SeriesWithBlooms]) (uint32, error) { +func (b *V2Builder) BuildFrom(itr iter.Iterator[SeriesWithBlooms]) (uint32, error) { for itr.Next() { at := itr.At() var offsets []BloomOffset @@ -160,7 +164,7 @@ func NewBlockBuilderV1(opts BlockOptions, writer BlockWriter) (*V1Builder, error }, nil } -func (b *V1Builder) BuildFrom(itr Iterator[SeriesWithBloom]) (uint32, error) { +func (b *V1Builder) BuildFrom(itr iter.Iterator[SeriesWithBloom]) (uint32, error) { for itr.Next() { at := itr.At() offset, err := b.AddBloom(at.Bloom) diff --git a/pkg/storage/bloom/v1/versioned_builder_test.go b/pkg/storage/bloom/v1/versioned_builder_test.go index eca86ef7aaa15..4b1103f1bbdac 100644 --- a/pkg/storage/bloom/v1/versioned_builder_test.go +++ b/pkg/storage/bloom/v1/versioned_builder_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/chunkenc" + v2 "github.com/grafana/loki/v3/pkg/iter/v2" "github.com/grafana/loki/v3/pkg/util/encoding" "github.com/grafana/loki/v3/pkg/util/mempool" ) @@ -47,8 +48,8 @@ func TestV1RoundTrip(t *testing.T) { b, err := NewBlockBuilderV1(opts, writer) require.NoError(t, err) - mapped := NewMapIter[SeriesWithLiteralBlooms]( - NewSliceIter(data), + mapped := v2.NewMapIter[SeriesWithLiteralBlooms]( + v2.NewSliceIter(data), func(s SeriesWithLiteralBlooms) SeriesWithBloom { return SeriesWithBloom{ Series: s.Series, @@ -68,7 +69,7 @@ func TestV1RoundTrip(t *testing.T) { t, func(t *testing.T, a SeriesWithLiteralBlooms, b *SeriesWithBlooms) { require.Equal(t, a.Series, b.Series) // ensure series equality - bs, err := Collect(b.Blooms) + bs, err := v2.Collect(b.Blooms) require.NoError(t, err) // ensure we only have one bloom in v1 @@ -81,7 +82,7 @@ func TestV1RoundTrip(t *testing.T) { require.Equal(t, encA.Get(), encB.Get()) }, - NewSliceIter(data), + v2.NewSliceIter(data), querier, ) } @@ -89,9 +90,9 @@ func TestV1RoundTrip(t *testing.T) { func TestV2Roundtrip(t *testing.T) { opts, data, writer, reader := setup(V2) - data, err := Collect( - NewMapIter[SeriesWithLiteralBlooms, SeriesWithLiteralBlooms]( - NewSliceIter(data), + data, err := v2.Collect( + v2.NewMapIter[SeriesWithLiteralBlooms, SeriesWithLiteralBlooms]( + v2.NewSliceIter(data), func(swlb SeriesWithLiteralBlooms) SeriesWithLiteralBlooms { return SeriesWithLiteralBlooms{ Series: swlb.Series, @@ -107,8 +108,8 @@ func TestV2Roundtrip(t *testing.T) { b, err := NewBlockBuilderV2(opts, writer) require.NoError(t, err) - mapped := NewMapIter[SeriesWithLiteralBlooms]( - NewSliceIter(data), + mapped := v2.NewMapIter[SeriesWithLiteralBlooms]( + v2.NewSliceIter(data), func(s SeriesWithLiteralBlooms) SeriesWithBlooms { return s.SeriesWithBlooms() }, @@ -125,7 +126,7 @@ func TestV2Roundtrip(t *testing.T) { t, func(t *testing.T, a SeriesWithLiteralBlooms, b *SeriesWithBlooms) { require.Equal(t, a.Series, b.Series) // ensure series equality - bs, err := Collect(b.Blooms) + bs, err := v2.Collect(b.Blooms) require.NoError(t, err) // ensure we only have one bloom in v1 @@ -141,7 +142,7 @@ func TestV2Roundtrip(t *testing.T) { encB.Reset() } }, - NewSliceIter(data), + v2.NewSliceIter(data), querier, ) } diff --git a/pkg/storage/lazy_chunk.go b/pkg/storage/lazy_chunk.go index 4c741228eee30..3ff1a3c891029 100644 --- a/pkg/storage/lazy_chunk.go +++ b/pkg/storage/lazy_chunk.go @@ -46,7 +46,7 @@ func (c *LazyChunk) Iterator( lokiChunk := c.Chunk.Data.(*chunkenc.Facade).LokiChunk() blocks := lokiChunk.Blocks(from, through) if len(blocks) == 0 { - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } its := make([]iter.EntryIterator, 0, len(blocks)) @@ -126,7 +126,7 @@ func (c *LazyChunk) SampleIterator( lokiChunk := c.Chunk.Data.(*chunkenc.Facade).LokiChunk() blocks := lokiChunk.Blocks(from, through) if len(blocks) == 0 { - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } its := make([]iter.SampleIterator, 0, len(blocks)) diff --git a/pkg/storage/store.go b/pkg/storage/store.go index 1900803637d7c..db4a0a498e17d 100644 --- a/pkg/storage/store.go +++ b/pkg/storage/store.go @@ -502,7 +502,7 @@ func (s *LokiStore) SelectLogs(ctx context.Context, req logql.SelectLogParams) ( } if len(lazyChunks) == 0 { - return iter.NoopIterator, nil + return iter.NoopEntryIterator, nil } expr, err := req.LogSelector() @@ -549,7 +549,7 @@ func (s *LokiStore) SelectSamples(ctx context.Context, req logql.SelectSamplePar } if len(lazyChunks) == 0 { - return iter.NoopIterator, nil + return iter.NoopSampleIterator, nil } expr, err := req.Expr() diff --git a/pkg/storage/store_test.go b/pkg/storage/store_test.go index 13bcaa9688a91..666ab241924a1 100644 --- a/pkg/storage/store_test.go +++ b/pkg/storage/store_test.go @@ -126,7 +126,7 @@ func Benchmark_store_SelectSample(b *testing.B) { } for iter.Next() { - _ = iter.Sample() + _ = iter.At() sampleCount++ } iter.Close() @@ -168,7 +168,7 @@ func benchmarkStoreQuery(b *testing.B, query *logproto.QueryRequest) { for iter.Next() { j++ printHeap(b, false) - res = append(res, iter.Entry()) + res = append(res, iter.At()) // limit result like the querier would do. if j == query.Limit { break @@ -928,7 +928,7 @@ func Test_PipelineWrapper(t *testing.T) { } defer logit.Close() for logit.Next() { - require.NoError(t, logit.Error()) // consume the iterator + require.NoError(t, logit.Err()) // consume the iterator } require.Equal(t, "test-user", wrapper.tenant) @@ -959,7 +959,7 @@ func Test_PipelineWrapper_disabled(t *testing.T) { } defer logit.Close() for logit.Next() { - require.NoError(t, logit.Error()) // consume the iterator + require.NoError(t, logit.Err()) // consume the iterator } require.Equal(t, "", wrapper.tenant) @@ -1044,7 +1044,7 @@ func Test_SampleWrapper(t *testing.T) { } defer it.Close() for it.Next() { - require.NoError(t, it.Error()) // consume the iterator + require.NoError(t, it.Err()) // consume the iterator } require.Equal(t, "test-user", wrapper.tenant) @@ -1074,7 +1074,7 @@ func Test_SampleWrapper_disabled(t *testing.T) { } defer it.Close() for it.Next() { - require.NoError(t, it.Error()) // consume the iterator + require.NoError(t, it.Err()) // consume the iterator } require.Equal(t, "", wrapper.tenant) @@ -1656,13 +1656,13 @@ func Test_OverlappingChunks(t *testing.T) { } defer it.Close() require.True(t, it.Next()) - require.Equal(t, "4", it.Entry().Line) + require.Equal(t, "4", it.At().Line) require.True(t, it.Next()) - require.Equal(t, "3", it.Entry().Line) + require.Equal(t, "3", it.At().Line) require.True(t, it.Next()) - require.Equal(t, "2", it.Entry().Line) + require.Equal(t, "2", it.At().Line) require.True(t, it.Next()) - require.Equal(t, "1", it.Entry().Line) + require.Equal(t, "1", it.At().Line) require.False(t, it.Next()) } @@ -2094,7 +2094,7 @@ func TestQueryReferencingStructuredMetadata(t *testing.T) { }, } } - require.Equal(t, expectedEntry, it.Entry()) + require.Equal(t, expectedEntry, it.At()) } require.False(t, it.Next()) diff --git a/pkg/storage/stores/shipper/bloomshipper/cache.go b/pkg/storage/stores/shipper/bloomshipper/cache.go index eab363866e883..bf533dac25b4b 100644 --- a/pkg/storage/stores/shipper/bloomshipper/cache.go +++ b/pkg/storage/stores/shipper/bloomshipper/cache.go @@ -11,6 +11,7 @@ import ( "github.com/grafana/dskit/multierror" "github.com/pkg/errors" + iter "github.com/grafana/loki/v3/pkg/iter/v2" v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" "github.com/grafana/loki/v3/pkg/storage/chunk/cache" "github.com/grafana/loki/v3/pkg/util" @@ -32,11 +33,11 @@ func (c *CloseableBlockQuerier) Close() error { return err.Err() } -func (c *CloseableBlockQuerier) SeriesIter() (v1.PeekingIterator[*v1.SeriesWithBlooms], error) { +func (c *CloseableBlockQuerier) SeriesIter() (iter.PeekIterator[*v1.SeriesWithBlooms], error) { if err := c.Reset(); err != nil { return nil, err } - return v1.NewPeekingIter[*v1.SeriesWithBlooms](c.BlockQuerier.Iter()), nil + return iter.NewPeekIter[*v1.SeriesWithBlooms](c.BlockQuerier.Iter()), nil } func LoadBlocksDirIntoCache(paths []string, c Cache, logger log.Logger) error {
chore
Make dedicated iterator package (#13273)
0b9e573140790862820a61f79e2cc653cd6a8ef4
2023-12-01 16:19:08
someStrangerFromTheAbyss
helm: Add extraContainers to write pods (#11319)
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index e471a343c0638..a322ff890663f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ ##### Enhancements +* [11319](https://github.com/grafana/loki/pull/11319) **someStrangerFromTheAbyss**: Helm: Add extraContainers to the write pods. * [11243](https://github.com/grafana/loki/pull/11243) **kavirajk**: Inflight-logging: Add extra metadata to inflight requests logging. * [11110](https://github.com/grafana/loki/pull/11003) **MichelHollands**: Change the default of the `metrics-namespace` flag to 'loki'. * [11086](https://github.com/grafana/loki/pull/11086) **kandrew5**: Helm: Allow topologySpreadConstraints diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 64f95131e15e0..8252a6fd103a3 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -4552,6 +4552,15 @@ null <td><pre lang="json"> [] </pre> +</td> + </tr> + <tr> + <td>write.extraContainers</td> + <td>list</td> + <td>Containers to add to the write pods</td> + <td><pre lang="json"> +[] +</pre> </td> </tr> <tr> diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index 6625682337052..cebffcfa5bacd 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -13,6 +13,10 @@ Entries should include a reference to the pull request that introduced the chang [//]: # (<AUTOMATED_UPDATES_LOCATOR> : do not remove this line. This locator is used by the CI pipeline to automatically create a changelog entry for each new Loki release. Add other chart versions and respective changelog entries bellow this line.) +## 5.40.0 + +- [CHANGE] Add extraContainers parameter for the write pod + ## 5.39.0 - [FEATURE] Add support for adding OpenStack swift container credentials via helm chart diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 721982213d464..287b448c7848b 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -3,7 +3,7 @@ name: loki description: Helm chart for Grafana Loki in simple, scalable mode type: application appVersion: 2.9.2 -version: 5.39.0 +version: 5.40.0 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index a5fc8bbfff201..a0ca45ce0dd5d 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 5.39.0](https://img.shields.io/badge/Version-5.39.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 2.9.2](https://img.shields.io/badge/AppVersion-2.9.2-informational?style=flat-square) +![Version: 5.40.0](https://img.shields.io/badge/Version-5.40.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 2.9.2](https://img.shields.io/badge/AppVersion-2.9.2-informational?style=flat-square) Helm chart for Grafana Loki in simple, scalable mode diff --git a/production/helm/loki/templates/write/statefulset-write.yaml b/production/helm/loki/templates/write/statefulset-write.yaml index fdbc2f04d20b3..8c5e426d3ffd6 100644 --- a/production/helm/loki/templates/write/statefulset-write.yaml +++ b/production/helm/loki/templates/write/statefulset-write.yaml @@ -138,6 +138,9 @@ spec: {{- end }} resources: {{- toYaml .Values.write.resources | nindent 12 }} + {{- with .Values.write.extraContainers }} + {{- toYaml . | nindent 8}} + {{- end }} {{- with .Values.write.affinity }} affinity: {{- tpl . $ | nindent 8 }} diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index 3271b09459c0f..738cf6ea25ae7 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -800,6 +800,8 @@ write: # https://github.com/grafana/loki/blob/main/docs/sources/operations/storage/wal.md#how-to-scale-updown # -- Init containers to add to the write pods initContainers: [] + # -- Containers to add to the write pods + extraContainers: [] # -- Volume mounts to add to the write pods extraVolumeMounts: [] # -- Volumes to add to the write pods
helm
Add extraContainers to write pods (#11319)
78c6aa49b4b4ae6f47ca8f0869df93675d4750bc
2019-08-14 02:48:13
Ed
feat(ksonnet): make our ksonnet a little more modular by parameterizing the chunk and index stores (#874)
false
diff --git a/production/ksonnet/loki/config.libsonnet b/production/ksonnet/loki/config.libsonnet index 7eaedd333b723..2186eb209355c 100644 --- a/production/ksonnet/loki/config.libsonnet +++ b/production/ksonnet/loki/config.libsonnet @@ -2,15 +2,82 @@ _config+: { namespace: error 'must define namespace', cluster: error 'must define cluster', - replication_factor: 3, + replication_factor: 3, memcached_replicas: 3, + // Default to GCS and Bigtable for chunk and index store + storage_backend: 'bigtable,gcs', + + enabledBackends: [ + backend + for backend in std.split($._config.storage_backend, ',') + ], + table_prefix: $._config.namespace, + + // Bigtable variables bigtable_instance: error 'must specify bigtable instance', bigtable_project: error 'must specify bigtable project', + + // GCS variables gcs_bucket_name: error 'must specify GCS bucket name', + // Cassandra variables + cassandra_keyspace: 'lokiindex', + cassandra_username: '', + cassandra_password: '', + cassandra_addresses: error 'must specify cassandra_addresses', + + // S3 variables + s3_access_key: '', + s3_secret_access_key: '', + s3_address: error 'must specify s3_address', + s3_bucket_name: error 'must specify s3_bucket_name', + s3_path_style: false, + + // Dynamodb variables + dynamodb_access_key: '', + dynamodb_secret_access_key: '', + dynamodb_region: error 'must specify dynamodb_region', + + client_configs: { + dynamo: { + dynamodbconfig: {} + if $._config.dynamodb_access_key != '' then { + dynamodb: 'dynamodb://' + $._config.dynamodb_access_key + ':' + $._config.dynamodb_secret_access_key + '@' + $._config.dynamodb_region, + } else { + dynamodb: 'dynamodb://' + $._config.dynamodb_region, + }, + }, + s3: { + s3forcepathstyle: $._config.s3_path_style, + } + ( + if $._config.s3_access_key != '' then { + s3: 's3://' + $._config.s3_access_key + ':' + $._config.s3_secret_access_key + '@' + $._config.s3_address + '/' + $._config.s3_bucket_name, + } else { + s3: 's3://' + $._config.s3_address + '/' + $._config.s3_bucket_name, + } + ), + cassandra: { + auth: false, + addresses: $._config.cassandra_addresses, + keyspace: $._config.cassandra_keyspace, + } + ( + if $._config.cassandra_username != '' then { + auth: true, + username: $._config.cassandra_username, + password: $._config.cassandra_password, + } else {} + ), + gcp: { + instance: $._config.bigtable_instance, + project: $._config.bigtable_project, + }, + gcs: { + bucket_name: $._config.gcs_bucket_name, + }, + }, + // December 11 is when we first launched to the public. // Assume we can ingest logs that are 5months old. schema_start_date: '2018-07-11', @@ -65,14 +132,6 @@ }, storage_config: { - bigtable: { - instance: $._config.bigtable_instance, - project: $._config.bigtable_project, - }, - gcs: { - bucket_name: $._config.gcs_bucket_name, - }, - index_queries_cache_config: { memcached: { batch_size: 100, @@ -84,7 +143,22 @@ service: 'memcached-client', }, }, - }, + } + + (if std.count($._config.enabledBackends, 'gcs') > 0 then { + gcs: $._config.client_configs.gcs, + } else {}) + + (if std.count($._config.enabledBackends, 's3') > 0 then { + aws+: $._config.client_configs.s3 + } else {}) + + (if std.count($._config.enabledBackends, 'bigtable') > 0 then { + bigtable: $._config.client_configs.gcp, + } else {}) + + (if std.count($._config.enabledBackends, 'cassandra') > 0 then { + cassandra: $._config.client_configs.cassandra, + } else {}) + + (if std.count($._config.enabledBackends, 'dynamodb') > 0 then { + aws+: $._config.client_configs.dynamo + } else {}), chunk_store_config: { chunk_cache_config: { @@ -113,6 +187,7 @@ max_look_back_period: 0, }, + // Default schema config is bigtable/gcs, this will need to be overriden for other stores schema_config: { configs: [{ from: '2018-04-15',
feat
make our ksonnet a little more modular by parameterizing the chunk and index stores (#874)
8b5c8899a44c286bc64d40db1b6cf3432301fc95
2020-05-01 01:14:29
Diana Payton
docs: Added labels content (#1999)
false
diff --git a/README.md b/README.md index 4fffd66a4057b..2779ada7f55a0 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ Started Guide](https://github.com/grafana/loki/tree/v1.4.1/docs/getting-started/ Commonly used sections (from the latest release v1.4.1): - [API documentation](https://github.com/grafana/loki/tree/v1.4.1/docs/api.md) for alternative ways of getting logs into Loki. +- [Labels](https://github.com/grafana/loki/blob/master/docs/getting-started/labels.md) - [Operations](https://github.com/grafana/loki/tree/v1.4.1/docs/operations) for important aspects of running Loki. - [Promtail](https://github.com/grafana/loki/tree/v1.4.1/docs/clients/promtail) is an agent which can tail your log files and push them to Loki. - [Pipelines](https://github.com/grafana/loki/tree/v1.4.1/docs/clients/promtail/pipelines.md) for detailed log processing pipeline documentation diff --git a/docs/README.md b/docs/README.md index 6f87f3b9fadca..b98a16f9fe67d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,10 +23,13 @@ simplifies the operation and significantly lowers the cost of Loki. 3. [Getting Started](getting-started/README.md) 1. [Grafana](getting-started/grafana.md) 2. [LogCLI](getting-started/logcli.md) + 3. [Labels](getting-started/labels.md) 4. [Troubleshooting](getting-started/troubleshooting.md) -4. [Configuration](configuration/README.md) +4. [Best Practices](best-practices/README.md) + 1. [Current Best Practices](best-practices/current-best-practices.md) +5. [Configuration](configuration/README.md) 1. [Examples](configuration/examples.md) -5. [Clients](clients/README.md) +6. [Clients](clients/README.md) 1. [Promtail](clients/promtail/README.md) 1. [Installation](clients/promtail/installation.md) 2. [Configuration](clients/promtail/configuration.md) @@ -37,8 +40,8 @@ simplifies the operation and significantly lowers the cost of Loki. 1. [Configuration](clients/docker-driver/configuration.md) 4. [Fluent Bit](../cmd/fluent-bit/README.md) 3. [Fluentd](clients/fluentd/README.md) -6. [LogQL](logql.md) -7. [Operations](operations/README.md) +7. [LogQL](logql.md) +8. [Operations](operations/README.md) 1. [Authentication](operations/authentication.md) 2. [Observability](operations/observability.md) 3. [Scalability](operations/scalability.md) @@ -48,11 +51,11 @@ simplifies the operation and significantly lowers the cost of Loki. 3. [BoltDB Shipper](operations/storage/boltdb-shipper.md) 5. [Multi-tenancy](operations/multi-tenancy.md) 6. [Loki Canary](operations/loki-canary.md) -8. [HTTP API](api.md) -9. [Architecture](architecture.md) -10. [Community](community/README.md) +9. [HTTP API](api.md) +10. [Architecture](architecture.md) +11. [Community](community/README.md) 1. [Governance](community/governance.md) 2. [Getting in Touch](community/getting-in-touch.md) 3. [Contributing to Loki](community/contributing.md) -11. [Loki Maintainers Guide](./maintaining/README.md) +12. [Loki Maintainers Guide](./maintaining/README.md) 1. [Releasing Loki](./maintaining/release.md) diff --git a/docs/best-practices/README.md b/docs/best-practices/README.md new file mode 100644 index 0000000000000..0694451671a80 --- /dev/null +++ b/docs/best-practices/README.md @@ -0,0 +1,3 @@ +# Best Practices + +1. [Current Best Practices](current-best-practices.md) includes a (hopefully) current guide for some best practices regarding Label usage and configuration in Loki. diff --git a/docs/best-practices/current-best-practices.md b/docs/best-practices/current-best-practices.md new file mode 100644 index 0000000000000..6b26283382c11 --- /dev/null +++ b/docs/best-practices/current-best-practices.md @@ -0,0 +1,88 @@ +# Loki label best practices + +Loki is under active development, and we are constantly working to improve performance. But here are some of the most current best practices for labels that will give you the best experience with Loki. + +## 1. Static labels are good + +Things like, host, application, and environment are great labels. They will be fixed for a given system/app and have bounded values. Use static labels to make it easier to query your logs in a logical sense (e.g. show me all the logs for a given application and specific environment, or show me all the logs for all the apps on a specific host). + +## 2. Use dynamic labels sparingly + +Too many label value combinations leads to too many streams. The penalties for that in Loki are a large index and small chunks in the store, which in turn can actually reduce performance. + +To avoid those issues, don't add a label for something until you know you need it! Use filter expressions ( |= “text”, |~ “regex”, …) and brute force those logs. It works -- and it's fast. + +From early on, we have set a label dynamically using promtail pipelines for `level`. This seemed intuitive for us as we often wanted to only show logs for `level=”error”`; however, we are re-evaluating this now as writing a query. `{app=”loki”} |= “level=error”` is proving to be just as fast for many of our applications as `{app=”loki”,level=”error”}`. + +This may seem surprising, but if applications have medium to low volume, that label causes one application's logs to be split into up to five streams, which means 5x chunks being stored. And loading chunks has an overhead associated with it. Imagine now if that query were `{app=”loki”,level!=”debug”}`. That would have to load **way** more chunks than `{app=”loki”} != “level=debug”`. + +Above, we mentioned not to add labels until you _need_ them, so when would you _need_ labels?? A little farther down is a section on `chunk_target_size`. If you set this to 1MB (which is reasonable), this will try to cut chunks at 1MB compressed size, which is about 5MB-ish of uncompressed logs (might be as much as 10MB depending on compression). If your logs have sufficient volume to write 5MB in less time than `max_chunk_age`, or **many** chunks in that timeframe, you might want to consider splitting it into separate streams with a dynamic label. + +What you want to avoid is splitting a log file into streams, which result in chunks getting flushed because the stream is idle or hits the max age before being full. As of [Loki 1.4.0](https://grafana.com/blog/2020/04/01/loki-v1.4.0-released-with-query-statistics-and-up-to-300x-regex-optimization/), there is a metric which can help you understand why chunks are flushed `sum by (reason) (rate(loki_ingester_chunks_flushed_total{cluster="dev"}[1m]))`. + +It’s not critical that every chunk be full when flushed, but it will improve many aspects of operation. As such, our current guidance here is to avoid dynamic labels as much as possible and instead favor filter expressions. For example, don’t add a `level` dynamic label, just `|= “level=debug”` instead. + +## 3. Label values must always be bounded + +If you are dynamically setting labels, never use a label which can have unbounded or infinite values. This will always result in big problems for Loki. + +Try to keep values bounded to as small a set as possible. We don't have perfect guidance as to what Loki can handle, but think single digits, or maybe 10’s of values for a dynamic label. This is less critical for static labels. For example, if you have 1,000 hosts in your environment it's going to be just fine to have a host label with 1,000 values. + +## 4. Be aware of dynamic labels applied by clients + +Loki has several client options: [Promtail](https://github.com/grafana/loki/tree/master/docs/clients/promtail) (which also supports systemd journal ingestion and TCP-based syslog ingestion), [FluentD](https://github.com/grafana/loki/tree/master/fluentd/fluent-plugin-grafana-loki), [Fluent Bit](https://github.com/grafana/loki/tree/master/cmd/fluent-bit), a [Docker plugin](https://grafana.com/blog/2019/07/15/lokis-path-to-ga-docker-logging-driver-plugin-support-for-systemd/), and more! + +Each of these come with ways to configure what labels are applied to create log streams. But be aware of what dynamic labels might be applied. Use the Loki series API to get an idea of what your log streams look like and see if there might be ways to reduce streams and cardinality. Details of the Series API can be found [here](https://github.com/grafana/loki/blob/master/docs/api.md#series), or you can use [logcli](https://github.com/grafana/loki/blob/master/docs/getting-started/logcli.md) to query Loki for series information. + +## 5. Configure caching + +Loki can cache data at many levels, which can drastically improve performance. Details of this will be in a future post. + +## 6. Logs must be in increasing time order per stream + +One issue many people have with Loki is their client receiving errors for out of order log entries. This happens because of this hard and fast rule within Loki: + +- For any single log stream, logs must always be sent in increasing time order. If a log is received with a timestamp older than the most recent log received for that stream, that log will be dropped. + +There are a few things to dissect from that statement. The first is this restriction is per stream. Let’s look at an example: + +``` +{job=”syslog”} 00:00:00 i’m a syslog! +{job=”syslog”} 00:00:01 i’m a syslog! +``` + +If Loki received these two lines which are for the same stream, everything would be fine. But what about this case: + +``` +{job=”syslog”} 00:00:00 i’m a syslog! +{job=”syslog”} 00:00:02 i’m a syslog! +{job=”syslog”} 00:00:01 i’m a syslog! <- Rejected out of order! +``` + +What can we do about this? What if this was because the sources of these logs were different systems? We can solve this with an additional label which is unique per system: + +``` +{job=”syslog”, instance=”host1”} 00:00:00 i’m a syslog! +{job=”syslog”, instance=”host1”} 00:00:02 i’m a syslog! +{job=”syslog”, instance=”host2”} 00:00:01 i’m a syslog! <- Accepted, this is a new stream! +{job=”syslog”, instance=”host1”} 00:00:03 i’m a syslog! <- Accepted, still in order for stream 1 +{job=”syslog”, instance=”host2”} 00:00:02 i’m a syslog! <- Accepted, still in order for stream 2 +``` + +But what if the application itself generated logs that were out of order? Well, I'm afraid this is a problem. If you are extracting the timestamp from the log line with something like [the promtail pipeline stage](https://github.com/grafana/loki/blob/master/docs/clients/promtail/stages/timestamp.md), you could instead _not_ do this and let Promtail assign a timestamp to the log lines. Or you can hopefully fix it in the application itself. + +But I want Loki to fix this! Why can’t you buffer streams and re-order them for me?! To be honest, because this would add a lot of memory overhead and complication to Loki, and as has been a common thread in this post, we want Loki to be simple and cost-effective. Ideally we would want to improve our clients to do some basic buffering and sorting as this seems a better place to solve this problem. + +It's also worth noting that the batching nature of the Loki push API can lead to some instances of out of order errors being received which are really false positives. (Perhaps a batch partially succeeded and was present; or anything that previously succeeded would return an out of order entry; or anything new would be accepted.) + +## 7. Use `chunk_target_size` + +This was added earlier this year when we [released v1.3.0 of Loki](https://grafana.com/blog/2020/01/22/loki-1.3.0-released/), and we've been experimenting with it for several months. We have `chunk_target_size: 1536000` in all our environments now. This instructs Loki to try to fill all chunks to a target _compressed_ size of 1.5MB. These larger chunks are more efficient for Loki to process. + +A couple other config variables affect how full a chunk can get. Loki has a default `max_chunk_age` of 1h and `chunk_idle_period` of 30m to limit the amount of memory used as well as the exposure of lost logs if the process crashes. + +Depending on the compression used (we have been using snappy which has less compressibility but faster performance), you need 5-10x or 7.5-10MB of raw log data to fill a 1.5MB chunk. Remembering that a chunk is per stream, the more streams you break up your log files into, the more chunks that sit in memory, and the higher likelihood they get flushed by hitting one of those timeouts mentioned above before they are filled. + +Lots of small, unfilled chunks are currently kryptonite for Loki. We are always working to improve this and may consider a compactor to improve this in some situations. But, in general, the guidance should stay about the same: Try your best to fill chunks! + +If you have an application that can log fast enough to fill these chunks quickly (much less than `max_chunk_age`), then it becomes more reasonable to use dynamic labels to break that up into separate streams. diff --git a/docs/getting-started/README.md b/docs/getting-started/README.md index 12509e61acc12..e92e2a2e6696d 100644 --- a/docs/getting-started/README.md +++ b/docs/getting-started/README.md @@ -2,5 +2,6 @@ 1. [Grafana](grafana.md) 2. [LogCLI](logcli.md) +3. [Labels](labels.md) 4. [Troubleshooting](troubleshooting.md) diff --git a/docs/getting-started/labels.md b/docs/getting-started/labels.md new file mode 100644 index 0000000000000..60a7d9517a9a4 --- /dev/null +++ b/docs/getting-started/labels.md @@ -0,0 +1,200 @@ +# Labels + +Labels are key value pairs and can be defined as anything! We like to refer to them as metadata to describe a log stream. If you are familiar with Prometheus, there are a few labels you are used to seeing like `job` and `instance`, and I will use those in the coming examples. + +The scrape configs we provide with Loki define these labels, too. If you are using Prometheus, having consistent labels between Loki and Prometheus is one of Loki's superpowers, making it incredibly [easy to correlate your application metrics with your log data](https://grafana.com/blog/2019/05/06/how-loki-correlates-metrics-and-logs-and-saves-you-money/). + +## How Loki uses labels + +Labels in Loki perform a very important task: They define a stream. More specifically, the combination of every label key and value defines the stream. If just one label value changes, this creates a new stream. + +If you are familiar with Prometheus, the term used there is series; however, Prometheus has an additional dimension: metric name. Loki simplifies this in that there are no metric names, just labels, and we decided to use streams instead of series. + +## Loki labels demo + +This series of examples will illustrate basic use cases and concepts for labeling in Loki. + +Let's take an example: + +```yaml +scrape_configs: + - job_name: system + pipeline_stages: + static_configs: + - targets: + - localhost + labels: + job: syslog + __path__: /var/log/syslog +``` + +This config will tail one file and assign one label: `job=syslog`. You could query it like this: + +``` +{job=”syslog”} +``` + +This will create one stream in Loki. + +Now let’s expand the example a little: + +```yaml +scrape_configs: + - job_name: system + pipeline_stages: + static_configs: + - targets: + - localhost + labels: + job: syslog + __path__: /var/log/syslog + - job_name: system + pipeline_stages: + static_configs: + - targets: + - localhost + labels: + job: apache + __path__: /var/log/apache.log +``` + +Now we are tailing two files. Each file gets just one label with one value so Loki will now be storing two streams. + +We can query these streams in a few ways: + + +``` +{job=”apache”} <- show me logs where the job label is apache +{job=”syslog”} <- show me logs where the job label is syslog +{job=~”apache|syslog”} <- show me logs where the job is apache **OR** syslog +``` + +In that last example, we used a regex label matcher to log streams that use the job label with two values. Now consider how an additional label could also be used: + +```yaml +scrape_configs: + - job_name: system + pipeline_stages: + static_configs: + - targets: + - localhost + labels: + job: syslog + env: dev + __path__: /var/log/syslog + - job_name: system + pipeline_stages: + static_configs: + - targets: + - localhost + labels: + job: apache + env: dev + __path__: /var/log/apache.log +``` + +Now instead of a regex, we could do this: + +``` +{env=”dev”} <- will return all logs with env=dev, in this case this includes both log streams +``` + +Hopefully now you are starting to see the power of labels. By using a single label, you can query many streams. By combining several different labels, you can create very flexible log queries. + +Labels are the index to Loki's log data. They are used to find the compressed log content, which is stored separately as chunks. Every unique combination of label and values defines a stream, and logs for a stream are batched up, compressed, and stored as chunks. + +For Loki to be efficient and cost-effective, we have to use labels responsibly. The next section will explore this in more detail. + +## Cardinality + +The two previous examples use statically defined labels with a single value; however, there are ways to dynamically define labels. Let's take a look using the Apache log and a massive regex you could use to parse such a log line: + +```nohighlight +11.11.11.11 - frank [25/Jan/2000:14:00:01 -0500] "GET /1986.js HTTP/1.1" 200 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +``` + +```yaml +- job_name: system + pipeline_stages: + - regex: + expression: "^(?P<ip>\\S+) (?P<identd>\\S+) (?P<user>\\S+) \\[(?P<timestamp>[\\w:/]+\\s[+\\-]\\d{4})\\] \"(?P<action>\\S+)\\s?(?P<path>\\S+)?\\s?(?P<protocol>\\S+)?\" (?P<status_code>\\d{3}|-) (?P<size>\\d+|-)\\s?\"?(?P<referer>[^\"]*)\"?\\s?\"?(?P<useragent>[^\"]*)?\"?$" + - labels: + action: + status_code: + static_configs: + - targets: + - localhost + labels: + job: apache + env: dev + __path__: /var/log/apache.log +``` + +This regex matches every component of the log line and extracts the value of each component into a capture group. Inside the pipeline code, this data is placed in a temporary data structure that allows using it for several purposes during the processing of that log line (at which point that temp data is discarded). Much more detail about this can be found [here](https://github.com/grafana/loki/blob/master/docs/clients/promtail/pipelines.md). + +From that regex, we will be using two of the capture groups to dynamically set two labels based on content from the log line itself: + +action (e.g. action=”GET”, action=”POST”) +status_code (e.g. status_code=”200”, status_code=”400”) + +And now let's walk through a few example lines: + +```nohighlight +11.11.11.11 - frank [25/Jan/2000:14:00:01 -0500] "GET /1986.js HTTP/1.1" 200 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +11.11.11.12 - frank [25/Jan/2000:14:00:02 -0500] "POST /1986.js HTTP/1.1" 200 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +11.11.11.13 - frank [25/Jan/2000:14:00:03 -0500] "GET /1986.js HTTP/1.1" 400 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +11.11.11.14 - frank [25/Jan/2000:14:00:04 -0500] "POST /1986.js HTTP/1.1" 400 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +``` + +In Loki the following streams would be created: + +``` +{job=”apache”,env=”dev”,action=”GET”,status_code=”200”} 11.11.11.11 - frank [25/Jan/2000:14:00:01 -0500] "GET /1986.js HTTP/1.1" 200 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +{job=”apache”,env=”dev”,action=”POST”,status_code=”200”} 11.11.11.12 - frank [25/Jan/2000:14:00:02 -0500] "POST /1986.js HTTP/1.1" 200 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +{job=”apache”,env=”dev”,action=”GET”,status_code=”400”} 11.11.11.13 - frank [25/Jan/2000:14:00:03 -0500] "GET /1986.js HTTP/1.1" 400 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +{job=”apache”,env=”dev”,action=”POST”,status_code=”400”} 11.11.11.14 - frank [25/Jan/2000:14:00:04 -0500] "POST /1986.js HTTP/1.1" 400 932 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB6" +``` + +Those four log lines would become four separate streams and start filling four separate chunks. + +Any additional log lines that match those combinations of label/values would be added to the existing stream. If another unique combination of labels comes in (e.g. status_code=”500”) another new stream is created. + +Imagine now if you set a label for `ip`. Not only does every request from a user become a unique stream. Every request with a different action or status_code from the same user will get its own stream. + +Doing some quick math, if there are maybe four common actions (GET, PUT, POST, DELETE) and maybe four common status codes (although there could be more than four!), this would be 16 streams and 16 separate chunks. Now multiply this by every user if we use a label for `ip`. You can quickly have thousands or tens of thousands of streams. + +This is high cardinality. This can kill Loki. + +When we talk about _cardinality_ we are referring to the combination of labels and values and the number of streams they create. High cardinality is using labels with a large range of possible values, such as `ip`, **or** combining many labels, even if they have a small and finite set of values, such as using `status_code` and `action`. + +High cardinality causes Loki to build a huge index (read: $$$$) and to flush thousands of tiny chunks to the object store (read: slow). Loki currently performs very poorly in this configuration and will be the least cost-effective and least fun to run and use. + +## Optimal Loki performance with parallelization + +Now you may be asking: If using lots of labels or labels with lots of values is bad, how am I supposed to query my logs? If none of the data is indexed, won't queries be really slow? + +As we see people using Loki who are accustomed to other index-heavy solutions, it seems like they feel obligated to define a lot of labels in order to query their logs effectively. After all, many other logging solutions are all about the index, and this is the common way of thinking. + +When using Loki, you may need to forget what you know and look to see how the problem can be solved differently with parallelization. Loki's superpower is breaking up queries into small pieces and dispatching them in parallel so that you can query huge amounts of log data in small amounts of time. + +This kind of brute force approach might not sound ideal, but let me explain why it is. + +Large indexes are complicated and expensive. Often a full-text index of your log data is the same size or bigger than the log data itself. To query your log data, you need this index loaded, and for performance, it should probably be in memory. This is difficult to scale, and as you ingest more logs, your index gets larger quickly. + +Now let's talk about Loki, where the index is typically an order of magnitude smaller than your ingested log volume. So if you are doing a good job of keeping your streams and stream churn to a minimum, the index grows very slowly compared to the ingested logs. + +Loki will effectively keep your static costs as low as possible (index size and memory requirements as well as static log storage) and make the query performance something you can control at runtime with horizontal scaling. + +To see how this works, let's look back at our example of querying your access log data for a specific IP address. We don't want to use a label to store the IP. Instead we use a [filter expression](https://github.com/grafana/loki/blob/master/docs/logql.md#filter-expression) to query for it: + +``` +{job=”apache”} |= “11.11.11.11” +``` + +Behind the scenes, Loki will break up that query into smaller pieces (shards), and open up each chunk for the streams matched by the labels and start looking for this IP address. + +The size of those shards and the amount of parallelization is configurable and based on the resources you provision. If you want to, you can configure the shard interval down to 5m, deploy 20 queriers, and process gigabytes of logs in seconds. Or you can go crazy and provision 200 queriers and process terabytes of logs! + +This trade-off of smaller index and parallel brute force querying vs. a larger/faster full-text index is what allows Loki to save on costs versus other systems. The cost and complexity of operating a large index is high and is typically fixed -- you pay for it 24 hours a day if you are querying it or not. + +The benefits of this design mean you can make the decision about how much query power you want to have, and you can change that on demand. Query performance becomes a function of how much money you want to spend on it. Meanwhile, the data is heavily compressed and stored in low-cost object stores like S3 and GCS. This drives the fixed operating costs to a minimum while still allowing for incredibly fast query capability.
docs
Added labels content (#1999)
3d6d35e97619f369182373bf25962494634fe653
2024-11-04 20:53:29
J Stickler
docs: update admonitions to new shortcode format (#14735)
false
diff --git a/docs/sources/alert/_index.md b/docs/sources/alert/_index.md index e12e073c3b889..b43b78e092b4a 100644 --- a/docs/sources/alert/_index.md +++ b/docs/sources/alert/_index.md @@ -202,18 +202,18 @@ Another great use case is alerting on high cardinality sources. These are things Creating these alerts in LogQL is attractive because these metrics can be extracted at _query time_, meaning we don't suffer the cardinality explosion in our metrics store. -{{% admonition type="note" %}} +{{< admonition type="note" >}} As an example, we can use LogQL v2 to help Loki to monitor _itself_, alerting us when specific tenants have queries that take longer than 10s to complete! To do so, we'd use the following query: `sum by (org_id) (rate({job="loki-prod/query-frontend"} |= "metrics.go" | logfmt | duration > 10s [1m])`. -{{% /admonition %}} +{{< /admonition >}} ## Interacting with the Ruler ### Lokitool Because the rule files are identical to Prometheus rule files, we can interact with the Loki Ruler via `lokitool`. -{{% admonition type="note" %}} +{{< admonition type="note" >}} lokitool is intended to run against multi-tenant Loki. The commands need an `--id=` flag set to the Loki instance ID or set the environment variable `LOKI_TENANT_ID`. If Loki is running in single tenant mode, the required ID is `fake`. -{{% /admonition %}} +{{< /admonition >}} An example workflow is included below: diff --git a/docs/sources/community/contributing.md b/docs/sources/community/contributing.md index f5918dfe82f43..e8553756ca342 100644 --- a/docs/sources/community/contributing.md +++ b/docs/sources/community/contributing.md @@ -30,10 +30,10 @@ $ git commit -m "docs: fix spelling error" $ git push -u fork HEAD ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} If you downloaded Loki using `go get`, the message `package github.com/grafana/loki: no Go files in /go/src/github.com/grafana/loki` is normal and requires no actions to resolve. -{{% /admonition %}} +{{< /admonition >}} ### Building diff --git a/docs/sources/community/design-documents/2021-01-Ordering-Constraint-Removal.md b/docs/sources/community/design-documents/2021-01-Ordering-Constraint-Removal.md index 64e59e21d07de..f50d9000343ca 100644 --- a/docs/sources/community/design-documents/2021-01-Ordering-Constraint-Removal.md +++ b/docs/sources/community/design-documents/2021-01-Ordering-Constraint-Removal.md @@ -129,9 +129,9 @@ The performance losses against the current approach includes: Loki regularly combines multiple blocks into a chunk and "flushes" it to storage. In order to ensure that reads over flushed chunks remain as performant as possible, we will re-order a possibly-overlapping set of blocks into a set of blocks that maintain monotonically increasing order between them. From the perspective of the rest of Loki’s components (queriers/rulers fetching chunks from storage), nothing has changed. -{{% admonition type="note" %}} +{{< admonition type="note" >}} **In the case that data for a stream is ingested in order, this is effectively a no-op, making it well optimized for in-order writes (which is both the requirement and default in Loki currently). Thus, this should have little performance impact on ordered data while enabling Loki to ingest unordered data.** -{{% /admonition %}} +{{< /admonition >}} #### Chunk Durations @@ -153,9 +153,9 @@ The second is simple to implement and an effective way to ensure Loki can ingest We also cut chunks according to the `sync_period`. The first timestamp ingested past this bound will trigger a cut. This process aids in increasing chunk determinism and therefore our deduplication ratio in object storage because chunks are [content addressed](https://en.wikipedia.org/wiki/Content-addressable_storage). With the removal of our ordering constraint, it's possible that in some cases the synchronization method will not be as effective, such as during concurrent writes to the same stream across this bound. -{{% admonition type="note" %}} +{{< admonition type="note" >}} **It's important to mention that this is possible today with the current ordering constraint, but we'll be increasing the likelihood by removing it.** -{{% /admonition %}} +{{< /admonition >}} ``` Figure 5 diff --git a/docs/sources/community/maintaining/release/create-release-branch.md b/docs/sources/community/maintaining/release/create-release-branch.md index 0c33d61d26e42..fa4d87db66a66 100644 --- a/docs/sources/community/maintaining/release/create-release-branch.md +++ b/docs/sources/community/maintaining/release/create-release-branch.md @@ -21,18 +21,18 @@ branch is then used for all the Stable Releases, and all Patch Releases for that The name of the release branch should be `release-VERSION_PREFIX`, such as `release-2.9.x`. - {{% admonition type="note" %}} + {{< admonition type="note" >}} Branches are only made for VERSION_PREFIX; do not create branches for the full VERSION such as `release-2.9.1`. - {{% /admonition %}} + {{< /admonition >}} - {{% admonition type="note" %}} + {{< admonition type="note" >}} Don't create any other branches that are prefixed with `release` when creating PRs or those branches will collide with our automated release build publish rules. - {{% /admonition %}} + {{< /admonition >}} 1. Create a label to make backporting PRs to this branch easy. The name of the label should be `backport release-VERSION_PREFIX`, such as `backport release-2.9.x`. - {{% admonition type="note" %}} + {{< admonition type="note" >}} Note there is space in the label name. The label name must follow this naming convention to trigger CI related jobs. - {{% /admonition %}} + {{< /admonition >}} diff --git a/docs/sources/community/maintaining/release/update-version-numbers.md b/docs/sources/community/maintaining/release/update-version-numbers.md index 17a43ca1d6c7c..79d1c9c0e2c17 100644 --- a/docs/sources/community/maintaining/release/update-version-numbers.md +++ b/docs/sources/community/maintaining/release/update-version-numbers.md @@ -24,6 +24,6 @@ Upgrade the Loki version to the new release version in documents, examples, json LOKI_NEW_VERSION=$VERSION ./tools/release_update_tags.sh ``` - {{% admonition type="note" %}} + {{< admonition type="note" >}} Do not upgrade the version numbers in the `operator/` directory as @periklis and team have a different process to upgrade the Operator version. - {{% /admonition %}} + {{< /admonition >}} diff --git a/docs/sources/get-started/deployment-modes.md b/docs/sources/get-started/deployment-modes.md index 60d3ccc74fbeb..7094dc4deb725 100644 --- a/docs/sources/get-started/deployment-modes.md +++ b/docs/sources/get-started/deployment-modes.md @@ -32,9 +32,9 @@ Query parallelization is limited by the number of instances and the setting `max The simple scalable deployment is the default configuration installed by the [Loki Helm Chart]({{< relref "../setup/install/helm" >}}). This deployment mode is the easiest way to deploy Loki at scale. It strikes a balance between deploying in [monolithic mode](#monolithic-mode) or deploying each component as a [separate microservice](#microservices-mode). -{{% admonition type="note" %}} +{{< admonition type="note" >}} This deployment mode is sometimes referred to by the acronym SSD for simple scalable deployment, not to be confused with solid state drives. Loki uses an object store. -{{% /admonition %}} +{{< /admonition >}} Loki’s simple scalable deployment mode separates execution paths into read, write, and backend targets. These targets can be scaled independently, letting you customize your Loki deployment to meet your business needs for log ingestion and log query so that your infrastructure costs better match how you use Loki. @@ -79,13 +79,13 @@ For release 3.2 the components are: - Ruler - Table Manager (deprecated) -{{% admonition type="tip" %}} +{{< admonition type="tip" >}} You can see the complete list of targets for your version of Loki by running Loki with the flag `-list-targets`, for example: ```bash docker run docker.io/grafana/loki:3.2.1 -config.file=/etc/loki/local-config.yaml -list-targets ``` -{{% /admonition %}} +{{< /admonition >}} ![Microservices mode diagram](../microservices-mode.png "Microservices mode") diff --git a/docs/sources/get-started/labels/_index.md b/docs/sources/get-started/labels/_index.md index 96625b2b13ab6..c9650befa70c9 100644 --- a/docs/sources/get-started/labels/_index.md +++ b/docs/sources/get-started/labels/_index.md @@ -19,10 +19,10 @@ Labels in Loki perform a very important task: They define a stream. More specifi If you are familiar with Prometheus, the term used there is series; however, Prometheus has an additional dimension: metric name. Loki simplifies this in that there are no metric names, just labels, and we decided to use streams instead of series. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Structured metadata do not define a stream, but are metadata attached to a log line. See [structured metadata]({{< relref "./structured-metadata" >}}) for more information. -{{% /admonition %}} +{{< /admonition >}} ## Format diff --git a/docs/sources/get-started/labels/structured-metadata.md b/docs/sources/get-started/labels/structured-metadata.md index ac91f58e0c87b..f1877139fef70 100644 --- a/docs/sources/get-started/labels/structured-metadata.md +++ b/docs/sources/get-started/labels/structured-metadata.md @@ -5,9 +5,9 @@ description: Describes how to enable structure metadata for logs and how to quer --- # What is structured metadata -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} Structured metadata was added to chunk format V4 which is used if the schema version is greater or equal to `13`. See [Schema Config](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/storage/#schema-config) for more details about schema versions. -{{% /admonition %}} +{{< /admonition >}} Selecting proper, low cardinality labels is critical to operating and querying Loki effectively. Some metadata, especially infrastructure related metadata, can be difficult to embed in log lines, and is too high cardinality to effectively store as indexed labels (and therefore reducing performance of the index). @@ -36,7 +36,7 @@ See the [Promtail: Structured metadata stage](https://grafana.com/docs/loki/<LOK With Loki version 1.2.0, support for structured metadata has been added to the Logstash output plugin. For more information, see [logstash](https://grafana.com/docs/loki/<LOKI_VERSION>/send-data/logstash/). -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} Structured metadata size is taken into account while asserting ingestion rate limiting. Along with that, there are separate limits on how much structured metadata can be attached per log line. ``` @@ -48,7 +48,7 @@ Along with that, there are separate limits on how much structured metadata can b # CLI flag: -limits.max-structured-metadata-entries-count [max_structured_metadata_entries_count: <int> | default = 128] ``` -{{% /admonition %}} +{{< /admonition >}} ## Querying structured metadata diff --git a/docs/sources/operations/authentication.md b/docs/sources/operations/authentication.md index 11949a1a9811a..44ef07c9bc391 100644 --- a/docs/sources/operations/authentication.md +++ b/docs/sources/operations/authentication.md @@ -18,11 +18,11 @@ A list of open-source reverse proxies you can use: - [OAuth2 proxy](https://github.com/oauth2-proxy/oauth2-proxy) - [HAProxy](https://www.haproxy.org/) -{{% admonition type="note" %}} +{{< admonition type="note" >}} When using Loki in multi-tenant mode, Loki requires the HTTP header `X-Scope-OrgID` to be set to a string identifying the tenant; the responsibility of populating this value should be handled by the authenticating reverse proxy. -For more information, read the [multi-tenancy]({{< relref "./multi-tenancy" >}}) documentation.{{% /admonition %}} +For more information, read the [multi-tenancy]({{< relref "./multi-tenancy" >}}) documentation.{{< /admonition >}} For information on authenticating Promtail, see the documentation for [how to configure Promtail]({{< relref "../send-data/promtail/configuration" >}}). diff --git a/docs/sources/operations/automatic-stream-sharding.md b/docs/sources/operations/automatic-stream-sharding.md index 04a46fbfe0826..2e876c89197f7 100644 --- a/docs/sources/operations/automatic-stream-sharding.md +++ b/docs/sources/operations/automatic-stream-sharding.md @@ -30,9 +30,9 @@ per-stream rate limit. ``` 1. Optionally enable `logging_enabled` for debugging stream sharding. - {{% admonition type="note" %}} + {{< admonition type="note" >}} This may affect the ingestion performance of Loki. - {{% /admonition %}} + {{< /admonition >}} ```yaml limits_config: diff --git a/docs/sources/operations/blocking-queries.md b/docs/sources/operations/blocking-queries.md index 1a88342bd3f16..ac286bbb3f849 100644 --- a/docs/sources/operations/blocking-queries.md +++ b/docs/sources/operations/blocking-queries.md @@ -35,9 +35,9 @@ overrides: - hash: 2943214005 # hash of {stream="stdout",pod="loki-canary-9w49x"} types: filter,limited ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Changes to these configurations **do not require a restart**; they are defined in the [runtime configuration file](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#runtime-configuration-file). -{{% /admonition %}} +{{< /admonition >}} The available query types are: @@ -53,9 +53,9 @@ is logged with every query request in the `query-frontend` and `querier` logs, f level=info ts=2023-03-30T09:08:15.2614555Z caller=metrics.go:152 component=frontend org_id=29 latency=fast query="{stream=\"stdout\",pod=\"loki-canary-9w49x\"}" query_hash=2943214005 query_type=limited range_type=range ... ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} The order of patterns is preserved, so the first matching pattern will be used. -{{% /admonition %}} +{{< /admonition >}} ## Observing blocked queries diff --git a/docs/sources/operations/bloom-filters.md b/docs/sources/operations/bloom-filters.md index a62e67efbc900..7394e26ec4f05 100644 --- a/docs/sources/operations/bloom-filters.md +++ b/docs/sources/operations/bloom-filters.md @@ -12,9 +12,9 @@ aliases: # Bloom filters (Experimental) -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} This feature is an [experimental feature](/docs/release-life-cycle/). Engineering and on-call support is not available. No SLA is provided. -{{% /admonition %}} +{{< /admonition >}} Loki leverages [bloom filters](https://en.wikipedia.org/wiki/Bloom_filter) to speed up queries by reducing the amount of data Loki needs to load from the store and iterate through. Loki is often used to run "needle in a haystack" queries; these are queries where a large number of log lines are searched, but only a few log lines match the query. diff --git a/docs/sources/operations/recording-rules.md b/docs/sources/operations/recording-rules.md index cd7bdd2d301cb..8c335740d5af6 100644 --- a/docs/sources/operations/recording-rules.md +++ b/docs/sources/operations/recording-rules.md @@ -30,11 +30,11 @@ is that Prometheus will, for example, reject a remote-write request with 100 sam When the `ruler` starts up, it will load the WALs for the tenants who have recording rules. These WAL files are stored on disk and are loaded into memory. -{{% admonition type="note" %}} +{{< admonition type="note" >}} WALs are loaded one at a time upon start-up. This is a current limitation of the Loki ruler. For this reason, it is adviseable that the number of rule groups serviced by a ruler be kept to a reasonable size, since _no rule evaluation occurs while WAL replay is in progress (this includes alerting rules)_. -{{% /admonition %}} +{{< /admonition >}} ### Truncation @@ -56,10 +56,10 @@ excessively large due to truncation. See Mimir's guide for [configuring Grafana Mimir hash rings](/docs/mimir/latest/configure/configure-hash-rings/) for scaling the ruler using a ring. -{{% admonition type="note" %}} +{{< admonition type="note" >}} The `ruler` shards by rule _group_, not by individual rules. This is an artifact of the fact that Prometheus recording rules need to run in order since one recording rule can reuse another - but this is not possible in Loki. -{{% /admonition %}} +{{< /admonition >}} ## Deployment diff --git a/docs/sources/operations/scalability.md b/docs/sources/operations/scalability.md index f7117ff103477..1cc6e87d12640 100644 --- a/docs/sources/operations/scalability.md +++ b/docs/sources/operations/scalability.md @@ -66,9 +66,9 @@ this will result in far lower `ruler` resource usage because the majority of the The LogQL queries coming from the `ruler` will be executed against the given `query-frontend` service. Requests will be load-balanced across all `query-frontend` IPs if the `dns:///` prefix is used. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Queries that fail to execute are _not_ retried. -{{% /admonition %}} +{{< /admonition >}} ### Limits and Observability diff --git a/docs/sources/operations/storage/_index.md b/docs/sources/operations/storage/_index.md index 74fa7620d9085..3b6bef94f9dce 100644 --- a/docs/sources/operations/storage/_index.md +++ b/docs/sources/operations/storage/_index.md @@ -77,9 +77,9 @@ See the [AWS deployment section](https://grafana.com/docs/loki/<LOKI_VERSION>/co ### DynamoDB -{{% admonition type="note" %}} +{{< admonition type="note" >}} DynamoDB support is deprecated and will be removed in a future release. -{{% /admonition %}} +{{< /admonition >}} When using DynamoDB for the index, the following permissions are needed: diff --git a/docs/sources/operations/storage/boltdb-shipper.md b/docs/sources/operations/storage/boltdb-shipper.md index 8fd7b9b085bf3..b43b8967df623 100644 --- a/docs/sources/operations/storage/boltdb-shipper.md +++ b/docs/sources/operations/storage/boltdb-shipper.md @@ -6,19 +6,19 @@ weight: 200 --- # Single Store BoltDB (boltdb-shipper) -{{% admonition type="note" %}} +{{< admonition type="note" >}} Single store BoltDB Shipper is a legacy storage option recommended for Loki 2.0 through 2.7.x and is not recommended for new deployments. The [TSDB](https://grafana.com/docs/loki/<LOKI_VERSION>/operations/storage/tsdb/) is the recommended index for Loki 2.8 and newer. -{{% /admonition %}} +{{< /admonition >}} BoltDB Shipper lets you run Grafana Loki without any dependency on NoSQL stores for storing index. It locally stores the index in BoltDB files instead and keeps shipping those files to a shared object store i.e the same object store which is being used for storing chunks. It also keeps syncing BoltDB files from shared object store to a configured local directory for getting index entries created by other services of same Loki cluster. This helps run Loki with one less dependency and also saves costs in storage since object stores are likely to be much cheaper compared to cost of a hosted NoSQL store or running a self hosted instance of Cassandra. -{{% admonition type="note" %}} +{{< admonition type="note" >}} BoltDB shipper works best with 24h periodic index files. It is a requirement to have the index period set to 24h for either active or upcoming usage of boltdb-shipper. If boltdb-shipper already has created index files with 7 days period, and you want to retain previous data, add a new schema config using boltdb-shipper with a future date and index files period set to 24h. -{{% /admonition %}} +{{< /admonition >}} ## Example Configuration @@ -76,9 +76,9 @@ they both having shipped files for day `18371` and `18372` with prefix `loki_ind ... ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Loki also adds a timestamp to names of the files to randomize the names to avoid overwriting files when running Ingesters with same name and not have a persistent storage. Timestamps not shown here for simplification. -{{% /admonition %}} +{{< /admonition >}} Let us talk about more in depth about how both Ingesters and Queriers work when running them with BoltDB Shipper. @@ -89,9 +89,9 @@ and the BoltDB Shipper looks for new and updated files in that directory at 1 mi When running Loki in microservices mode, there could be multiple ingesters serving write requests. Each ingester generates BoltDB files locally. -{{% admonition type="note" %}} +{{< admonition type="note" >}} To avoid any loss of index when an ingester crashes, we recommend running ingesters as a StatefulSet (when using Kubernetes) with a persistent storage for storing index files. -{{% /admonition %}} +{{< /admonition >}} When chunks are flushed, they are available for reads in the object store instantly. The index is not available instantly, since we upload every 15 minutes with the BoltDB shipper. Ingesters expose a new RPC for letting queriers query the ingester's local index for chunks which were recently flushed, but its index might not be available yet with queriers. @@ -137,9 +137,9 @@ While using `boltdb-shipper` avoid configuring WriteDedupe cache since it is use Compactor is a BoltDB Shipper specific service that reduces the index size by deduping the index and merging all the files to a single file per table. We recommend running a Compactor since a single Ingester creates 96 files per day which include a lot of duplicate index entries and querying multiple files per table adds up the overall query latency. -{{% admonition type="note" %}} +{{< admonition type="note" >}} There should be only one compactor instance running at a time that otherwise could create problems and may lead to data loss. -{{% /admonition %}} +{{< /admonition >}} Example compactor configuration with GCS: diff --git a/docs/sources/operations/storage/legacy-storage.md b/docs/sources/operations/storage/legacy-storage.md index 5ec0859833655..e474d5ec40619 100644 --- a/docs/sources/operations/storage/legacy-storage.md +++ b/docs/sources/operations/storage/legacy-storage.md @@ -6,11 +6,11 @@ weight: 1000 --- # Legacy storage -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} The concepts described on this page are considered legacy and pre-date the single store storage introduced in Loki 2.0. The usage of legacy storage for new installations is highly discouraged and documentation is meant for informational purposes in case of upgrade to a single store. -{{% /admonition %}} +{{< /admonition >}} The **chunk store** is the Loki long-term data store, designed to support interactive querying and sustained writing without the need for background @@ -27,11 +27,11 @@ maintenance tasks. It consists of: - [Amazon S3](https://aws.amazon.com/s3) - [Google Cloud Storage](https://cloud.google.com/storage/) -{{% admonition type="note" %}} +{{< admonition type="note" >}} Unlike the other core components of Loki, the chunk store is not a separate service, job, or process, but rather a library embedded in the two services that need to access Loki data: the [ingester]({{< relref "../../get-started/components#ingester" >}}) and [querier]({{< relref "../../get-started/components#querier" >}}). -{{% /admonition %}} +{{< /admonition >}} The chunk store relies on a unified interface to the "[NoSQL](https://en.wikipedia.org/wiki/NoSQL)" stores (DynamoDB, Bigtable, and diff --git a/docs/sources/operations/storage/logs-deletion.md b/docs/sources/operations/storage/logs-deletion.md index eef99609ffd32..ddbb23d8d6dd5 100644 --- a/docs/sources/operations/storage/logs-deletion.md +++ b/docs/sources/operations/storage/logs-deletion.md @@ -22,9 +22,9 @@ Log entry deletion relies on configuration of the custom logs retention workflow Enable log entry deletion by setting `retention_enabled` to true in the compactor's configuration and setting and `deletion_mode` to `filter-only` or `filter-and-delete` in the runtime config. `delete_request_store` also needs to be configured when retention is enabled to process delete requests, this determines the storage bucket that stores the delete requests. -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} Be very careful when enabling retention. It is strongly recommended that you also enable versioning on your objects in object storage to allow you to recover from accidental misconfiguration of a retention setting. If you want to enable deletion but not not want to enforce retention, configure the `retention_period` setting with a value of `0s`. -{{% /admonition %}} +{{< /admonition >}} Because it is a runtime configuration, `deletion_mode` can be set per-tenant, if desired. diff --git a/docs/sources/operations/storage/retention.md b/docs/sources/operations/storage/retention.md index d211109786384..2ef39b7a3b930 100644 --- a/docs/sources/operations/storage/retention.md +++ b/docs/sources/operations/storage/retention.md @@ -9,24 +9,24 @@ weight: 600 Retention in Grafana Loki is achieved through the [Compactor](#compactor). By default the `compactor.retention-enabled` flag is not set, so the logs sent to Loki live forever. -{{% admonition type="note" %}} +{{< admonition type="note" >}} If you have a lifecycle policy configured on the object store, please ensure that it is longer than the retention period. -{{% /admonition %}} +{{< /admonition >}} Granular retention policies to apply retention at per tenant or per stream level are also supported by the Compactor. -{{% admonition type="note" %}} +{{< admonition type="note" >}} The Compactor does not support retention on [legacy index types](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/storage/#index-storage). Please use the [Table Manager](https://grafana.com/docs/loki/<LOKI_VERSION>/operations/storage/table-manager/) when using legacy index types. Both the Table manager and legacy index types are deprecated and may be removed in future major versions of Loki. -{{% /admonition %}} +{{< /admonition >}} ## Compactor The Compactor is responsible for compaction of index files and applying log retention. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Run the Compactor as a singleton (a single instance). -{{% /admonition %}} +{{< /admonition >}} The Compactor loops to apply compaction and retention at every `compactor.compaction-interval`, or as soon as possible if running behind. Both compaction and retention are idempotent. If the Compactor restarts, it will continue from where it left off. @@ -49,9 +49,9 @@ Chunks cannot be deleted immediately for the following reasons: - It provides a short window of time in which to cancel chunk deletion in the case of a configuration mistake. Marker files should be stored on a persistent disk to ensure that the chunks pending for deletion are processed even if the Compactor process restarts. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Grafana Labs recommends running Compactor as a stateful deployment (StatefulSet when using Kubernetes) with a persistent storage for storing marker files. -{{% /admonition %}} +{{< /admonition >}} ### Retention Configuration @@ -82,9 +82,9 @@ storage_config: bucket_name: loki ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Retention is only available if the index period is 24h. Single store TSDB and single store BoltDB require 24h index period. -{{% /admonition %}} +{{< /admonition >}} `retention_enabled` should be set to true. Without this, the Compactor will only compact tables. @@ -107,9 +107,9 @@ There are two ways of setting retention policies: - `retention_period` which is applied globally for all log streams. - `retention_stream` which is only applied to log streams matching the selector. -{{% admonition type="note" %}} +{{< admonition type="note" >}} The minimum retention period is 24h. -{{% /admonition %}} +{{< /admonition >}} This example configures global retention that applies to all tenants (unless overridden by configuring per-tenant overrides): @@ -125,9 +125,9 @@ limits_config: ... ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} You can only use label matchers in the `selector` field of a `retention_stream` definition. Arbitrary LogQL expressions are not supported. -{{% /admonition %}} +{{< /admonition >}} Per tenant retention can be defined by configuring [runtime overrides](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#runtime-configuration-file). For example: @@ -156,9 +156,9 @@ Retention period for a given stream is decided based on the first match in this 4. The global `retention_period` will be applied if none of the above match. 5. If no global `retention_period` is specified, the default value of `744h` (30days) retention is used. -{{% admonition type="note" %}} +{{< admonition type="note" >}} The larger the priority value, the higher the priority. -{{% /admonition %}} +{{< /admonition >}} Stream matching uses the same syntax as Prometheus label matching: @@ -194,16 +194,16 @@ Alternatively, the `table-manager.retention-period` and provided retention period needs to be a duration represented as a string that can be parsed using the Prometheus common model [ParseDuration](https://pkg.go.dev/github.com/prometheus/common/model#ParseDuration). Examples: `7d`, `1w`, `168h`. -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} The retention period must be a multiple of the index and chunks table `period`, configured in the [`period_config`](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#period_config) block. See the [Table Manager](https://grafana.com/docs/loki/<LOKI_VERSION>/operations/storage/table-manager/#retention) documentation for more information. -{{% /admonition %}} +{{< /admonition >}} -{{% admonition type="note" %}} +{{< admonition type="note" >}} To avoid querying of data beyond the retention period,`max_query_lookback` config in [`limits_config`](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#limits_config) must be set to a value less than or equal to what is set in `table_manager.retention_period`. -{{% /admonition %}} +{{< /admonition >}} When using S3 or GCS, the bucket storing the chunks needs to have the expiry policy set correctly. For more details check diff --git a/docs/sources/operations/storage/table-manager/_index.md b/docs/sources/operations/storage/table-manager/_index.md index 6016b6bb12b93..5e3061cc9f8f8 100644 --- a/docs/sources/operations/storage/table-manager/_index.md +++ b/docs/sources/operations/storage/table-manager/_index.md @@ -6,9 +6,9 @@ weight: --- # Table manager -{{% admonition type="note" %}} +{{< admonition type="note" >}} Table manager is only needed if you are using a multi-store [backend](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/storage/). If you are using either TSDB (recommended), or BoltDB (deprecated) you do not need the Table Manager. -{{% /admonition %}} +{{< /admonition >}} Grafana Loki supports storing indexes and chunks in table-based data storages. When such a storage type is used, multiple tables are created over the time: each @@ -141,11 +141,11 @@ number_of_tables_to_keep = floor(retention_period / table_period) + 1 {{< figure alt="retention" align="center" src="./table-manager-retention.png" >}} -{{% admonition type="note" %}} +{{< admonition type="note" >}} It's important to note that - due to the internal implementation - the table `period` and `retention_period` **must** be multiples of `24h` in order to get the expected behavior. -{{% /admonition %}} +{{< /admonition >}} For detailed information on configuring the retention, refer to the [Loki Storage Retention]({{< relref "../retention" >}}) diff --git a/docs/sources/query/log_queries/_index.md b/docs/sources/query/log_queries/_index.md index 5e429b2f3b86c..52650aa753298 100644 --- a/docs/sources/query/log_queries/_index.md +++ b/docs/sources/query/log_queries/_index.md @@ -661,9 +661,9 @@ the result will be The `| keep` expression will keep only the specified labels in the pipeline and drop all the other labels. -{{% admonition type="note" %}} +{{< admonition type="note" >}} The keep stage will not drop the __error__ or __error_details__ labels added by Loki at query time. To drop these labels, refer to [drop](#drop-labels-expression) stage. -{{% /admonition %}} +{{< /admonition >}} Query examples: diff --git a/docs/sources/query/logcli.md b/docs/sources/query/logcli.md index ee282ac73a6de..97f5f9f3d5ad0 100644 --- a/docs/sources/query/logcli.md +++ b/docs/sources/query/logcli.md @@ -70,11 +70,11 @@ without needing a username and password: export LOKI_ADDR=http://localhost:3100 ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} If you are running Loki behind a proxy server and you have authentication configured, you will also have to pass in LOKI_USERNAME and LOKI_PASSWORD, LOKI_BEARER_TOKEN or LOKI_BEARER_TOKEN_FILE accordingly. -{{% /admonition %}} +{{< /admonition >}} ```bash $ logcli labels job @@ -860,9 +860,9 @@ You can consume log lines from your `stdin` instead of Loki servers. Say you have log files in your local, and just want to do run some LogQL queries for that, `--stdin` flag can help. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Currently it doesn't support any type of metric queries. -{{% /admonition %}} +{{< /admonition >}} You may have to use `stdin` flag for several reasons 1. Quick way to check and validate a LogQL expressions. diff --git a/docs/sources/query/query_accceleration.md b/docs/sources/query/query_accceleration.md index ab377b828243c..48998fffb9dda 100644 --- a/docs/sources/query/query_accceleration.md +++ b/docs/sources/query/query_accceleration.md @@ -10,9 +10,9 @@ keywords: # Query acceleration (Experimental) -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} Query acceleration using blooms is an [experimental feature](/docs/release-life-cycle/). Engineering and on-call support is not available. No SLA is provided. -{{% /admonition %}} +{{< /admonition >}} If [bloom filters][] are enabled, you can write LogQL queries using [structured metadata][] to benefit from query acceleration. diff --git a/docs/sources/reference/loki-http-api.md b/docs/sources/reference/loki-http-api.md index 55d724160abdb..dbf0d38a0aedf 100644 --- a/docs/sources/reference/loki-http-api.md +++ b/docs/sources/reference/loki-http-api.md @@ -12,10 +12,10 @@ weight: 500 Loki exposes an HTTP API for pushing, querying, and tailing log data, as well as for viewing and managing cluster information. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Note that authorization is not part of the Loki API. Authorization needs to be done separately, for example, using an open-source load-balancer such as NGINX. -{{% /admonition %}} +{{< /admonition >}} ## Endpoints @@ -30,9 +30,9 @@ A [list of clients]({{< relref "../send-data" >}}) can be found in the clients d ### Query endpoints -{{% admonition type="note" %}} +{{< admonition type="note" >}} Requests sent to the query endpoints must use valid LogQL syntax. For more information, see the [LogQL]({{< relref "../query" >}}) section of the documentation. -{{% /admonition %}} +{{< /admonition >}} These HTTP endpoints are exposed by the `querier`, `query-frontend`, `read`, and `all` components: @@ -112,10 +112,10 @@ These HTTP endpoints are exposed by all individual components: ### Deprecated endpoints -{{% admonition type="note" %}} +{{< admonition type="note" >}} The following endpoints are deprecated.While they still exist and work, they should not be used for new deployments. Existing deployments should upgrade to use the supported endpoints. -{{% /admonition %}} +{{< /admonition >}} | Deprecated | Replacement | | ---------- | ----------- | @@ -154,9 +154,9 @@ The API accepts several formats for timestamps: - A floating point number is a Unix timestamp with fractions of a second. - A string in `RFC3339` and `RFC3339Nano` format, as supported by Go's [time](https://pkg.go.dev/time) package. -{{% admonition type="note" %}} +{{< admonition type="note" >}} When using `/api/v1/push`, you must send the timestamp as a string and not a number, otherwise the endpoint will return a 400 error. -{{% /admonition %}} +{{< /admonition >}} ### Statistics @@ -1440,9 +1440,9 @@ Query parameters: - `request_id=<request_id>`: Identifies the delete request to cancel; IDs are found using the `delete` endpoint. - `force=<boolean>`: When the `force` query parameter is true, partially completed delete requests will be canceled. - {{% admonition type="note" %}} + {{< admonition type="note" >}} some data from the request may still be deleted and the deleted request will be listed as 'processed'. - {{% /admonition %}} + {{< /admonition >}} A 204 response indicates success. diff --git a/docs/sources/release-notes/cadence.md b/docs/sources/release-notes/cadence.md index ef6fbcaf072fd..1059fb7f95cf5 100644 --- a/docs/sources/release-notes/cadence.md +++ b/docs/sources/release-notes/cadence.md @@ -15,12 +15,12 @@ naming scheme: `MAJOR`.`MINOR`.`PATCH`. - `MINOR` (roughly once a quarter): these releases include new features which generally do not break backwards-compatibility, but from time to time we might introduce _minor_ breaking changes, and we will specify these in our upgrade docs. - `PATCH` (roughly once or twice a month): these releases include bug and security fixes which do not break backwards-compatibility. -{{% admonition type="note" %}} +{{< admonition type="note" >}} While our naming scheme resembles [Semantic Versioning](https://semver.org/), at this time we do not strictly follow its guidelines to the letter. Our goal is to provide regular releases that are as stable as possible, and we take backwards-compatibility seriously. As with any software, always read the [release notes](https://grafana.com/docs/loki/<LOKI_VERSION>/release-notes/) and the [upgrade guide](https://grafana.com/docs/loki/<LOKI_VERSION>/setup/upgrade/) whenever choosing a new version of Loki to install. -{{% /admonition %}} +{{< /admonition >}} New releases are based of a [weekly release](#weekly-releases) which we have vetted for stability over a number of weeks. diff --git a/docs/sources/release-notes/v2-3.md b/docs/sources/release-notes/v2-3.md index 49ae7c76a798f..87aff23ed0e99 100644 --- a/docs/sources/release-notes/v2-3.md +++ b/docs/sources/release-notes/v2-3.md @@ -78,8 +78,8 @@ List of security fixes for 2.3.x. * [4020](https://github.com/grafana/loki/pull/4020) **simonswine**: Restrict path segments in TenantIDs (CVE-2021-36156 CVE-2021-36157). -{{% admonition type="note" %}} -Exploitation of this vulnerability requires the ability for an attacker to craft and send directly to Loki an `X-Scope-OrgID` header, end users should not have the ability to create and send this header directly to Loki as it controls access to tenants and is important to control setting of this header for proper tenant isolation and security. We always recommend having a proxy or gateway be responsible for setting the `X-Scope-OrgID`.{{% /admonition %}} +{{< admonition type="note" >}} +Exploitation of this vulnerability requires the ability for an attacker to craft and send directly to Loki an `X-Scope-OrgID` header, end users should not have the ability to create and send this header directly to Loki as it controls access to tenants and is important to control setting of this header for proper tenant isolation and security. We always recommend having a proxy or gateway be responsible for setting the `X-Scope-OrgID`.{{< /admonition >}} ## Bug fixes diff --git a/docs/sources/send-data/_index.md b/docs/sources/send-data/_index.md index 0ef9432d3caf3..411f0f4367042 100644 --- a/docs/sources/send-data/_index.md +++ b/docs/sources/send-data/_index.md @@ -37,9 +37,9 @@ For more information, see [Ingesting logs to Loki using OpenTelemetry Collector] The following clients have been developed by the Loki community or other third-parties and can be used to send log data to Loki. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Grafana Labs cannot provide support for third-party clients. Once an issue has been determined to be with the client and not Loki, it is the responsibility of the customer to work with the associated vendor or project for bug fixes to these clients. -{{% /admonition %}} +{{< /admonition >}} The following are popular third-party Loki clients: diff --git a/docs/sources/send-data/docker-driver/_index.md b/docs/sources/send-data/docker-driver/_index.md index f262829d58fd7..092857732c807 100644 --- a/docs/sources/send-data/docker-driver/_index.md +++ b/docs/sources/send-data/docker-driver/_index.md @@ -12,9 +12,9 @@ Grafana Loki officially supports a Docker plugin that will read logs from Docker containers and ship them to Loki. The plugin can be configured to send the logs to a private Loki instance or [Grafana Cloud](/oss/loki). -{{% admonition type="note" %}} +{{< admonition type="note" >}} Docker plugins are not supported on Windows; see the [Docker Engine managed plugin system](https://docs.docker.com/engine/extend) documentation for more information. -{{% /admonition %}} +{{< /admonition >}} Documentation on configuring the Loki Docker Driver can be found on the [configuration page]({{< relref "./configuration" >}}). @@ -58,9 +58,9 @@ docker plugin upgrade loki grafana/loki-docker-driver:2.9.2 --grant-all-permissi docker plugin enable loki systemctl restart docker ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Update the version number to the appropriate version. -{{% /admonition %}} +{{< /admonition >}} ## Uninstall the Docker driver client diff --git a/docs/sources/send-data/docker-driver/configuration.md b/docs/sources/send-data/docker-driver/configuration.md index afa982b0b57cb..b2038c97335d5 100644 --- a/docs/sources/send-data/docker-driver/configuration.md +++ b/docs/sources/send-data/docker-driver/configuration.md @@ -33,11 +33,11 @@ docker run --log-driver=loki \ --log-opt loki-batch-size=400 \ grafana/grafana ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} The Loki logging driver still uses the json-log driver in combination with sending logs to Loki, this is mainly useful to keep the `docker logs` command working. You can adjust file size and rotation using the respective log option `max-size` and `max-file`. Keep in mind that default values for these options are not taken from json-log configuration. You can deactivate this behavior by setting the log option `no-file` to true. -{{% /admonition %}} +{{< /admonition >}} ## Change the default logging driver @@ -65,11 +65,11 @@ Options for the logging driver can also be configured with `log-opts` in the } } ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} log-opt configuration options in daemon.json must be provided as > strings. Boolean and numeric values (such as the value for loki-batch-size in > the example above) must therefore be enclosed in quotes (`"`). -{{% /admonition %}} +{{< /admonition >}} After changing `daemon.json`, restart the Docker daemon for the changes to take effect. All **newly created** containers from that host will then send logs to Loki via the driver. @@ -104,9 +104,9 @@ docker-compose -f docker-compose.yaml up Once deployed, the Grafana service will send its logs to Loki. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Stack name and service name for each swarm service and project name and service name for each compose service are automatically discovered and sent as Loki labels, this way you can filter by them in Grafana. -{{% /admonition %}} +{{< /admonition >}} ## Labels @@ -150,9 +150,9 @@ services: - "3000:3000" ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Note the `loki-pipeline-stages: |` letting you keep the indentation correct. -{{% /admonition %}} +{{< /admonition >}} When using docker run you can also pass the value via a string parameter like such: diff --git a/docs/sources/send-data/fluentd/_index.md b/docs/sources/send-data/fluentd/_index.md index c712b0bb166b0..35a682e92dffd 100644 --- a/docs/sources/send-data/fluentd/_index.md +++ b/docs/sources/send-data/fluentd/_index.md @@ -71,9 +71,9 @@ services: ## Usage -{{% admonition type="note" %}} +{{< admonition type="note" >}} Use either `<label>...</label>` or `extra_labels` to set at least one label. -{{% /admonition %}} +{{< /admonition >}} In your Fluentd configuration, add `@type loki`. Additional configuration is optional. Default values would look like this: diff --git a/docs/sources/send-data/lambda-promtail/_index.md b/docs/sources/send-data/lambda-promtail/_index.md index 49b1795a7c303..4f2b41bd713d1 100644 --- a/docs/sources/send-data/lambda-promtail/_index.md +++ b/docs/sources/send-data/lambda-promtail/_index.md @@ -99,9 +99,9 @@ Ephemeral jobs can quite easily run afoul of cardinality best practices. During For those using Cloudwatch and wishing to test out Loki in a low-risk way, this workflow allows piping Cloudwatch logs to Loki regardless of the event source (EC2, Kubernetes, Lambda, ECS, etc) without setting up a set of Promtail daemons across their infrastructure. However, running Promtail as a daemon on your infrastructure is the best-practice deployment strategy in the long term for flexibility, reliability, performance, and cost. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Propagating logs from Cloudwatch to Loki means you'll still need to _pay_ for Cloudwatch. -{{% /admonition %}} +{{< /admonition >}} ### VPC Flow logs @@ -165,9 +165,9 @@ Incoming logs can have seven special labels assigned to them which can be used i ### Promtail labels -{{% admonition type="note" %}} +{{< admonition type="note" >}} This section is relevant if running Promtail between lambda-promtail and the end Loki deployment and was used to circumvent `out of order` problems prior to the v2.4 Loki release which removed the ordering constraint. -{{% /admonition %}} +{{< /admonition >}} As stated earlier, this workflow moves the worst case stream cardinality from `number_of_log_streams` -> `number_of_log_groups` * `number_of_promtails`. For this reason, each Promtail must have a unique label attached to logs it processes (ideally via something like `--client.external-labels=promtail=${HOSTNAME}`) and it's advised to run a small number of Promtails behind a load balancer according to your throughput and redundancy needs. @@ -195,9 +195,9 @@ The provided Terraform and CloudFormation files are meant to cover the default u ## Example Promtail Config -{{% admonition type="note" %}} +{{< admonition type="note" >}} This should be run in conjunction with a Promtail-specific label attached, ideally via a flag argument like `--client.external-labels=promtail=${HOSTNAME}`. It will receive writes via the push-api on ports `3500` (http) and `3600` (grpc). -{{% /admonition %}} +{{< /admonition >}} ```yaml server: diff --git a/docs/sources/send-data/otel/_index.md b/docs/sources/send-data/otel/_index.md index 690df4f5b544b..176cd0afd4109 100644 --- a/docs/sources/send-data/otel/_index.md +++ b/docs/sources/send-data/otel/_index.md @@ -93,9 +93,9 @@ Since the OpenTelemetry protocol differs from the Loki storage model, here is ho - service.name - service.namespace - {{% admonition type="note" %}} + {{< admonition type="note" >}} Because Loki has a default limit of 15 index labels, we recommend storing only select resource attributes as index labels. Although the default config selects more than 15 Resource Attributes, it should be fine since a few are mutually exclusive. - {{% /admonition %}} + {{< /admonition >}} - Timestamp: One of `LogRecord.TimeUnixNano` or `LogRecord.ObservedTimestamp`, based on which one is set. If both are not set, the ingestion timestamp will be used. diff --git a/docs/sources/send-data/promtail/configuration.md b/docs/sources/send-data/promtail/configuration.md index 32e4d01a70e34..0cd4d4eccc431 100644 --- a/docs/sources/send-data/promtail/configuration.md +++ b/docs/sources/send-data/promtail/configuration.md @@ -73,12 +73,12 @@ ${VAR:-default_value} Where default_value is the value to use if the environment variable is undefined. -{{% admonition type="note" %}} +{{< admonition type="note" >}} With `expand-env=true` the configuration will first run through [envsubst](https://pkg.go.dev/github.com/drone/envsubst) which will replace double backslashes with single backslashes. Because of this every use of a backslash `\` needs to be replaced with a double backslash `\\`. -{{% /admonition %}} +{{< /admonition >}} ### Generic placeholders diff --git a/docs/sources/send-data/promtail/stages/drop.md b/docs/sources/send-data/promtail/stages/drop.md index 77b66020bb23f..0c6c15a1feda9 100644 --- a/docs/sources/send-data/promtail/stages/drop.md +++ b/docs/sources/send-data/promtail/stages/drop.md @@ -126,9 +126,9 @@ Would drop this log line: #### Drop old log lines -{{% admonition type="note" %}} +{{< admonition type="note" >}} For `older_than` to work, you must be using the [timestamp]({{< relref "./timestamp" >}}) stage to set the timestamp from the ingested log line _before_ applying the `drop` stage. -{{% /admonition %}} +{{< /admonition >}} Given the pipeline: diff --git a/docs/sources/send-data/promtail/stages/json.md b/docs/sources/send-data/promtail/stages/json.md index 6babe1f60700e..79a4c2438fb8d 100644 --- a/docs/sources/send-data/promtail/stages/json.md +++ b/docs/sources/send-data/promtail/stages/json.md @@ -134,7 +134,7 @@ The following key-value pairs would be created in the set of extracted data: - `stream`: `stderr` - `timestamp`: `2019-04-30T02:12:41.8443515` -{{% admonition type="note" %}} +{{< admonition type="note" >}} Referring to `grpc.stream` without the combination of double quotes wrapped in single quotes will not work properly. -{{% /admonition %}} +{{< /admonition >}} diff --git a/docs/sources/send-data/promtail/stages/match.md b/docs/sources/send-data/promtail/stages/match.md index e9351350f4b3c..c76a3a8dc8340 100644 --- a/docs/sources/send-data/promtail/stages/match.md +++ b/docs/sources/send-data/promtail/stages/match.md @@ -14,9 +14,9 @@ or drop entries when a log entry matches a configurable LogQL [stream selector]({{< relref "../../../query/log_queries#log-stream-selector" >}}) and [filter expressions]({{< relref "../../../query/log_queries#line-filter-expression" >}}). -{{% admonition type="note" %}} +{{< admonition type="note" >}} The filters do not include label filter expressions such as `| label == "foobar"`. -{{% /admonition %}} +{{< /admonition >}} ## Schema diff --git a/docs/sources/send-data/promtail/stages/structured_metadata.md b/docs/sources/send-data/promtail/stages/structured_metadata.md index 369ceecfba3fd..129dd757c4a25 100644 --- a/docs/sources/send-data/promtail/stages/structured_metadata.md +++ b/docs/sources/send-data/promtail/stages/structured_metadata.md @@ -8,11 +8,11 @@ description: The 'structured_metadata' Promtail pipeline stage The `structured_metadata` stage is an action stage that takes data from the extracted map and modifies the [structured metadata]({{< relref "../../../get-started/labels/structured-metadata" >}}) that is sent to Loki with the log entry. -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} Structured metadata will be rejected by Loki unless you enable the `allow_structured_metadata` per tenant configuration (in the `limits_config`). Structured metadata was added to chunk format V4 which is used if the schema version is greater or equal to **13**. (See Schema Config for more details about schema versions. ) -{{% /admonition %}} +{{< /admonition >}} ## Schema diff --git a/docs/sources/setup/migrate/migrate-to-tsdb/_index.md b/docs/sources/setup/migrate/migrate-to-tsdb/_index.md index 5be15a42b22d8..b67e19b37196e 100644 --- a/docs/sources/setup/migrate/migrate-to-tsdb/_index.md +++ b/docs/sources/setup/migrate/migrate-to-tsdb/_index.md @@ -20,9 +20,9 @@ we strongly recommend migrating to TSDB. To begin the migration, add a new [period_config](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#period_config) entry in your [schema_config](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/#schema_config). You can read more about schema config [here](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/storage/#schema-config). -{{% admonition type="note" %}} +{{< admonition type="note" >}} You must roll out the new `period_config` change to all Loki components in order for it to take effect. -{{% /admonition %}} +{{< /admonition >}} This example adds a new `period_config` which configures Loki to start using the TSDB index for the data ingested starting from `2023-10-20`. diff --git a/docs/sources/setup/upgrade/_index.md b/docs/sources/setup/upgrade/_index.md index 07cb5863c4dba..ae4a80e8909ac 100644 --- a/docs/sources/setup/upgrade/_index.md +++ b/docs/sources/setup/upgrade/_index.md @@ -48,10 +48,10 @@ Loki changes the default value of `-ruler.alertmanager-use-v2` from `false` to ` ### Experimental Bloom Filters -{{% admonition type="note" %}} +{{< admonition type="note" >}} Experimental features are subject to rapid change and/or removal, which can introduce breaking changes even between minor version. They also don't follow the deprecation lifecycle of regular features. -{{% /admonition %}} +{{< /admonition >}} The bloom compactor component, which builds bloom filter blocks for query acceleration, has been removed in favor of two new components: bloom planner and bloom builder. Please consult the [Query Acceleration with Blooms](https://grafana.com/docs/loki/<LOKI_VERSION>/operations/query-acceleration-blooms/) docs for more information. @@ -78,11 +78,11 @@ All other CLI arguments (and their YAML counterparts) prefixed with `-bloom-comp ## 3.0.0 -{{% admonition type="note" %}} +{{< admonition type="note" >}} If you have questions about upgrading to Loki 3.0, please join us on the [community Slack](https://slack.grafana.com/) in the `#loki-3` channel. Or leave a comment on this [Github Issue](https://github.com/grafana/loki/issues/12506). -{{% /admonition %}} +{{< /admonition >}} {{< admonition type="tip" >}} If you have not yet [migrated to TSDB](https://grafana.com/docs/loki/<LOKI_VERSION>/setup/migrate/migrate-to-tsdb/), do so before you upgrade to Loki 3.0. @@ -165,11 +165,11 @@ This enforces chunks and index files to reside together in the same storage buck We are removing the shared store setting in an effort to simplify storage configuration and reduce the possibility for misconfiguration. -{{% admonition type="warning" %}} +{{< admonition type="warning" >}} With this change Loki no longer allows storing chunks and indexes for a given period in different storage buckets. This is a breaking change for setups that store chunks and indexes in different storage buckets by setting `-boltdb.shipper.shared-store` or `-tsdb.shipper.shared-store` to a value different from `object_store` in `period_config`. -{{% /admonition %}} +{{< /admonition >}} - If you have not configured `-boltdb.shipper.shared-store`,`-tsdb.shipper.shared-store` or their corresponding YAML setting before, no changes are required as part of the upgrade. - If you have configured `-boltdb.shipper.shared-store` or its YAML setting: @@ -194,9 +194,9 @@ period_config: period: 24h ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} `path_prefix` only applies to TSDB and BoltDB indexes. This setting has no effect on [legacy indexes](https://grafana.com/docs/loki/<LOKI_VERSION>/configure/storage/#index-storage). -{{% /admonition %}} +{{< /admonition >}} `path_prefix` defaults to `index/` which is same as the default value of the removed configurations. @@ -290,7 +290,7 @@ This new metric will provide a more clear signal that there is an issue with ing #### Changes to default configuration values in 3.0 -{{% responsive-table %}} +{{< responsive-table >}} | configuration | new default | old default | notes | | ------------------------------------------------------ | ----------- | ----------- | -------- | `compactor.delete-max-interval` | 24h | 0 | splits the delete requests into intervals no longer than `delete_max_interval` | @@ -310,7 +310,7 @@ This new metric will provide a more clear signal that there is an issue with ing | `query-scheduler.max-outstanding-requests-per-tenant` | 32000 | 100 | - | | `validation.max-label-names-per-series` | 15 | 30 | - | | `legacy-read-mode` | false | true | Deprecated. It will be removed in the next minor release. | -{{% /responsive-table %}} +{{< /responsive-table >}} #### Automatic stream sharding is enabled by default @@ -529,10 +529,10 @@ limits_config: retention_period: 744h ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} In previous versions, the zero value of `0` or `0s` will result in **immediate deletion of all logs**, only in 2.8 and forward releases does the zero value disable retention. -{{% /admonition %}} +{{< /admonition >}} #### metrics.go log line `subqueries` replaced with `splits` and `shards` @@ -546,9 +546,9 @@ In 2.8 we no longer include `subqueries` in metrics.go, it does still exist in t Instead, now you can use `splits` to see how many split by time intervals were created and `shards` to see the total number of shards created for a query. -{{% admonition type="note" %}} +{{< admonition type="note" >}} Currently not every query can be sharded and a shards value of zero is a good indicator the query was not able to be sharded. -{{% /admonition %}} +{{< /admonition >}} ### Promtail @@ -579,9 +579,9 @@ ruler: #### query-frontend Kubernetes headless service changed to load balanced service -{{% admonition type="note" %}} +{{< admonition type="note" >}} This is relevant only if you are using [jsonnet for deploying Loki in Kubernetes](/docs/loki/<LOKI_VERSION>/installation/tanka/). -{{% /admonition %}} +{{< /admonition >}} The `query-frontend` Kubernetes service was previously headless and was used for two purposes: * Distributing the Loki query requests amongst all the available Query Frontend pods. @@ -1114,9 +1114,9 @@ In Loki 2.2 we changed the internal version of our chunk format from v2 to v3, t This makes it important to first upgrade to 2.0, 2.0.1, or 2.1 **before** upgrading to 2.2 so that if you need to rollback for any reason you can do so easily. -{{% admonition type="note" %}} +{{< admonition type="note" >}} 2.0 and 2.0.1 are identical in every aspect except 2.0.1 contains the code necessary to read the v3 chunk format. Therefor if you are on 2.0 and ugrade to 2.2, if you want to rollback, you must rollback to 2.0.1. -{{% /admonition %}} +{{< /admonition >}} ### Loki Config @@ -1260,14 +1260,14 @@ This likely only affects a small portion of tanka users because the default sche } ``` -{{% admonition type="note" %}} +{{< admonition type="note" >}} If you had set `index_period_hours` to a value other than 168h (the previous default) you must update this in the above config `period:` to match what you chose. -{{% /admonition %}} +{{< /admonition >}} -{{% admonition type="note" %}} +{{< admonition type="note" >}} We have changed the default index store to `boltdb-shipper` it's important to add `using_boltdb_shipper: false,` until you are ready to change (if you want to change) -{{% /admonition %}} +{{< /admonition >}} Changing the jsonnet config to use the `boltdb-shipper` type is the same as [below](#upgrading-schema-to-use-boltdb-shipper-andor-v11-schema) where you need to add a new schema section. @@ -1309,9 +1309,9 @@ _THIS BEING SAID_ we are not expecting problems, our testing so far has not unco Report any problems via GitHub issues or reach us on the #loki slack channel. -{{% admonition type="note" %}} +{{< admonition type="note" >}} If are using boltdb-shipper and were running with high availability and separate filesystems, this was a poorly documented and even more experimental mode we toyed with using boltdb-shipper. For now we removed the documentation and also any kind of support for this mode. -{{% /admonition %}} +{{< /admonition >}} To use boltdb-shipper in 2.0 you need a shared storage (S3, GCS, etc), the mode of running with separate filesystem stores in HA using a ring is not officially supported. @@ -1454,9 +1454,9 @@ schema_config: ``` If you are not on `schema: v11` this would be a good opportunity to make that change _in the new schema config_ also. -{{% admonition type="note" %}} +{{< admonition type="note" >}} If the current time in your timezone is after midnight UTC already, set the date one additional day forward. -{{% /admonition %}} +{{< /admonition >}} There was also a significant overhaul to how boltdb-shipper internals, this should not be visible to a user but as this feature is experimental and under development bug are possible! @@ -1515,9 +1515,9 @@ Defaulting to `gcs,bigtable` was confusing for anyone using ksonnet with other s ## 1.5.0 -{{% admonition type="note" %}} +{{< admonition type="note" >}} The required upgrade path outlined for version 1.4.0 below is still true for moving to 1.5.0 from any release older than 1.4.0 (e.g. 1.3.0 -> 1.5.0 needs to also look at the 1.4.0 upgrade requirements). -{{% /admonition %}} +{{< /admonition >}} ### Breaking config changes! @@ -1571,9 +1571,9 @@ Not every environment will allow this capability however, it's possible to restr #### Filesystem -{{% admonition type="note" %}} +{{< admonition type="note" >}} The location Loki is looking for files with the provided config in the docker image has changed. -{{% /admonition %}} +{{< /admonition >}} In 1.4.0 and earlier the included config file in the docker container was using directories:
docs
update admonitions to new shortcode format (#14735)
8ff27e243bac7a9ac6b9b9682be353ea545c3ec7
2021-12-08 00:34:49
Karen Miller
docs: Reorganize architecture section (#4873)
false
diff --git a/docs/sources/fundamentals/architecture/_index.md b/docs/sources/fundamentals/architecture/_index.md index d3cfe97e6fc6a..76bc961c79101 100644 --- a/docs/sources/fundamentals/architecture/_index.md +++ b/docs/sources/fundamentals/architecture/_index.md @@ -14,307 +14,6 @@ is running in multi-tenant mode. When Loki is **not** in multi-tenant mode, the header is ignored and the tenant ID is set to "fake", which will appear in the index and in stored chunks. -## Modes of operation - -As an application, -Loki is built out of many component microservices, -and is designed to run as a horizontally-scalable distributed system. -Loki's unique design compiles the code of the entire distributed system into -a single binary or Docker image. -The behavior of that single binary is controlled with -the `-target` command-line flag and defines one of three modes of operation. - -Configuration for each deployed instance of the binary -further specifies which components it runs. - -Loki is designed to easily redeploy a cluster under a different mode -as your needs change, -with no configuration changes or minimal configuration changes. - -### Monolithic mode - -The simplest mode of operation sets `-target=all`. -This is the default target, -and it does not need to be specified. -This is monolithic mode; -it runs all of Loki’s microservice components inside a single process -as a single binary or Docker image. - -![monolithic mode diagram](monolithic-mode.png) - -Monolithic mode is useful for getting started quickly to experiment with Loki, -as well as for small read/write volumes of up to approximately 100GB per day. - -Horizontally scale up a monolithic mode deployment to more instances -by using a shared object store, and by configuring the -[`memberlist_config` section](../../configuration/#memberlist_config) -to share state between all instances. - -High availability can be configured by running two Loki instances -using `memberlist_config` configuration and a shared object store. - -Route traffic to all the Loki instances in a round robin fashion. - -Query parallelization is limited to the quantity of instances -and the query parallelism defined. - -### Simple scalable deployment mode - -If your volume of logs exceeds a few hundred GB a day, -or if you would like to separate read and write concerns, -Loki provides the simple scalable deployment mode. -This deployment mode can scale to several TBs of logs per day and more. -Consider the microservices mode approach for very large Loki installations. - -![simple scalable deployment mode diagram](simple-scalable.png) - -In this mode the component microservices of Loki are bundled into two targets: -`-target=read` and `-target=write`. - -There are advantages to separating the read and write paths: - -* higher availability of write path by providing dedicated nodes -* separately scalable read path to add/remove query performance on demand - -The simple scalable deployment mode requires a load balancer in front of Loki, -which directs `/loki/api/v1/push` traffic to the write nodes. -All other requests go to the read nodes. -Traffic should be sent in a round robin fashion. - -The simple scalable deployment of Loki can scale to -several TBs of logs per day and more. - -### Microservices mode - -The microservices deployment mode instantiates components of Loki -as distinct processes. -Each process is invoked specifying its `target`: - -* ingester -* distributor -* query-frontend -* query-scheduler -* querier -* index-gateway -* ruler -* compactor - -![microservices mode diagram](microservices-mode.png) - -Running components as individual microservices allows scaling up -by increasing the quantity of microservices. -The customized cluster has better observability of the individual components. -Microservices mode deployments are the most efficient Loki installations. -However, they are also the most complex to set up and maintain. - -Microservices mode is recommended for very large Loki clusters -or for clusters that require more control over scaling and cluster operations. - -Microservices mode works best with Kubernetes deployments. -There are Jsonnet and distributed Helm chart installations. - -## Components - -![components_diagram](loki_architecture_components.svg) - -### Distributor - -The **distributor** service is responsible for handling incoming streams by -clients. It's the first stop in the write path for log data. Once the -distributor receives a set of streams, each stream is validated for correctness -and to ensure that it is within the configured tenant (or global) limits. Valid -chunks are then split into batches and sent to multiple [ingesters](#ingester) -in parallel. - -For more information, see the [Distributor](./distributor) page. - -#### Hashing - -Distributors use consistent hashing in conjunction with a configurable -replication factor to determine which instances of the ingester service should -receive a given stream. - -A stream is a set of logs associated to a tenant and a unique labelset. The -stream is hashed using both the tenant ID and the labelset and then the hash is -used to find the ingesters to send the stream to. - -A hash ring stored in [Consul](https://www.consul.io) is used to achieve -consistent hashing; all [ingesters](#ingester) register themselves into the hash -ring with a set of tokens they own. Each token is a random unsigned 32-bit -number. Along with a set of tokens, ingesters register their state into the -hash ring. The state JOINING, and ACTIVE may all receive write requests, while -ACTIVE and LEAVING ingesters may receive read requests. When doing a hash -lookup, distributors only use tokens for ingesters who are in the appropriate -state for the request. - -To do the hash lookup, distributors find the smallest appropriate token whose -value is larger than the hash of the stream. When the replication factor is -larger than 1, the next subsequent tokens (clockwise in the ring) that belong to -different ingesters will also be included in the result. - -The effect of this hash set up is that each token that an ingester owns is -responsible for a range of hashes. If there are three tokens with values 0, 25, -and 50, then a hash of 3 would be given to the ingester that owns the token 25; -the ingester owning token 25 is responsible for the hash range of 1-25. - -#### Quorum consistency - -Since all distributors share access to the same hash ring, write requests can be -sent to any distributor. - -To ensure consistent query results, Loki uses -[Dynamo-style](https://www.cs.princeton.edu/courses/archive/fall15/cos518/studpres/dynamo.pdf) -quorum consistency on reads and writes. This means that the distributor will wait -for a positive response of at least one half plus one of the ingesters to send -the sample to before responding to the client that initiated the send. - -### Ingester - -The **ingester** service is responsible for writing log data to long-term -storage backends (DynamoDB, S3, Cassandra, etc.) on the write path and returning -log data for in-memory queries on the read path. - -Ingesters contain a _lifecycler_ which manages the lifecycle of an ingester in -the hash ring. Each ingester has a state of either `PENDING`, `JOINING`, -`ACTIVE`, `LEAVING`, or `UNHEALTHY`: - -**Deprecated: the WAL (write ahead log) supersedes this feature** -1. `PENDING` is an Ingester's state when it is waiting for a handoff from - another ingester that is `LEAVING`. - -1. `JOINING` is an Ingester's state when it is currently inserting its tokens - into the ring and initializing itself. It may receive write requests for - tokens it owns. - -1. `ACTIVE` is an Ingester's state when it is fully initialized. It may receive - both write and read requests for tokens it owns. - -1. `LEAVING` is an Ingester's state when it is shutting down. It may receive - read requests for data it still has in memory. - -1. `UNHEALTHY` is an Ingester's state when it has failed to heartbeat to - Consul. `UNHEALTHY` is set by the distributor when it periodically checks the ring. - -Each log stream that an ingester receives is built up into a set of many -"chunks" in memory and flushed to the backing storage backend at a configurable -interval. - -Chunks are compressed and marked as read-only when: - -1. The current chunk has reached capacity (a configurable value). -1. Too much time has passed without the current chunk being updated -1. A flush occurs. - -Whenever a chunk is compressed and marked as read-only, a writable chunk takes -its place. - -If an ingester process crashes or exits abruptly, all the data that has not yet -been flushed will be lost. Loki is usually configured to replicate multiple -replicas (usually 3) of each log to mitigate this risk. - -When a flush occurs to a persistent storage provider, the chunk is hashed based -on its tenant, labels, and contents. This means that multiple ingesters with the -same copy of data will not write the same data to the backing store twice, but -if any write failed to one of the replicas, multiple differing chunk objects -will be created in the backing store. See [Querier](#querier) for how data is -deduplicated. - -#### Timestamp Ordering - -Loki can be configured to [accept out-of-order writes](../../configuration/#accept-out-of-order-writes). - -When not configured to accept out-of-order writes, the ingester validates that ingested log lines are in order. When an -ingester receives a log line that doesn't follow the expected order, the line -is rejected and an error is returned to the user. - -The ingester validates that log lines are received in -timestamp-ascending order. Each log has a timestamp that occurs at a later -time than the log before it. When the ingester receives a log that does not -follow this order, the log line is rejected and an error is returned. - -Logs from each unique set of labels are built up into "chunks" in memory and -then flushed to the backing storage backend. - -If an ingester process crashes or exits abruptly, all the data that has not yet -been flushed could be lost. Loki is usually configured with a [Write Ahead Log](../../operations/storage/wal) which can be _replayed_ on restart as well as with a `replication_factor` (usually 3) of each log to mitigate this risk. - -When not configured to accept out-of-order writes, -all lines pushed to Loki for a given stream (unique combination of -labels) must have a newer timestamp than the line received before it. There are, -however, two cases for handling logs for the same stream with identical -nanosecond timestamps: - -1. If the incoming line exactly matches the previously received line (matching - both the previous timestamp and log text), the incoming line will be treated - as an exact duplicate and ignored. - -2. If the incoming line has the same timestamp as the previous line but - different content, the log line is accepted. This means it is possible to - have two different log lines for the same timestamp. - -#### Handoff - Deprecated in favor of the [WAL](../../operations/storage/wal) - -By default, when an ingester is shutting down and tries to leave the hash ring, -it will wait to see if a new ingester tries to enter before flushing and will -try to initiate a handoff. The handoff will transfer all of the tokens and -in-memory chunks owned by the leaving ingester to the new ingester. - -Before joining the hash ring, ingesters will wait in `PENDING` state for a -handoff to occur. After a configurable timeout, ingesters in the `PENDING` state -that have not received a transfer will join the ring normally, inserting a new -set of tokens. - -This process is used to avoid flushing all chunks when shutting down, which is a -slow process. - -#### Filesystem Support - -While ingesters do support writing to the filesystem through BoltDB, this only -works in single-process mode as [queriers](#querier) need access to the same -back-end store and BoltDB only allows one process to have a lock on the DB at a -given time. - -### Query frontend - -The **query frontend** is an **optional service** providing the querier's API endpoints and can be used to accelerate the read path. When the query frontend is in place, incoming query requests should be directed to the query frontend instead of the queriers. The querier service will be still required within the cluster, in order to execute the actual queries. - -The query frontend internally performs some query adjustments and holds queries in an internal queue. In this setup, queriers act as workers which pull jobs from the queue, execute them, and return them to the query-frontend for aggregation. Queriers need to be configured with the query frontend address (via the `-querier.frontend-address` CLI flag) in order to allow them to connect to the query frontends. - -Query frontends are **stateless**. However, due to how the internal queue works, it's recommended to run a few query frontend replicas to reap the benefit of fair scheduling. Two replicas should suffice in most cases. - -#### Queueing - -The query frontend queuing mechanism is used to: - -- Ensure that large queries, that could cause an out-of-memory (OOM) error in the querier, will be retried on failure. This allows administrators to under-provision memory for queries, or optimistically run more small queries in parallel, which helps to reduce the TCO. -- Prevent multiple large requests from being convoyed on a single querier by distributing them across all queriers using a first-in/first-out queue (FIFO). -- Prevent a single tenant from denial-of-service-ing (DOSing) other tenants by fairly scheduling queries between tenants. - -#### Splitting - -The query frontend splits larger queries into multiple smaller queries, executing these queries in parallel on downstream queriers and stitching the results back together again. This prevents large (multi-day, etc) queries from causing out of memory issues in a single querier and helps to execute them faster. - -#### Caching - -##### Metric Queries - -The query frontend supports caching metric query results and reuses them on subsequent queries. If the cached results are incomplete, the query frontend calculates the required subqueries and executes them in parallel on downstream queriers. The query frontend can optionally align queries with their step parameter to improve the cacheability of the query results. The result cache is compatible with any loki caching backend (currently memcached, redis, and an in-memory cache). - -##### Log Queries - Coming soon! - -Caching log (filter, regexp) queries are under active development. - -### Querier - -The **querier** service handles queries using the [LogQL](../../logql/) query -language, fetching logs both from the ingesters and from long-term storage. - -Queriers query all ingesters for in-memory data before falling back to -running the same query against the backend store. Because of the replication -factor, it is possible that the querier may receive duplicate data. To resolve -this, the querier internally **deduplicates** data that has the same nanosecond -timestamp, label set, and log message. - ## Chunk Format ``` diff --git a/docs/sources/fundamentals/architecture/components.md b/docs/sources/fundamentals/architecture/components.md new file mode 100644 index 0000000000000..3e9e79398617f --- /dev/null +++ b/docs/sources/fundamentals/architecture/components.md @@ -0,0 +1,234 @@ +--- +title: Components +weight: 30 +--- +# Components + +![components_diagram](../loki_architecture_components.svg) + +## Distributor + +The **distributor** service is responsible for handling incoming streams by +clients. It's the first stop in the write path for log data. Once the +distributor receives a set of streams, each stream is validated for correctness +and to ensure that it is within the configured tenant (or global) limits. Valid +chunks are then split into batches and sent to multiple [ingesters](#ingester) +in parallel. + +It is important that a load balancer sits in front of the distributor in order to properly balance traffic to them. + +The distributor is a stateless component. This makes it easy to scale and offload as much work as possible from the ingesters, which are the most critical component on the write path. The ability to independently scale these validation operations mean that Loki can also protect itself against denial of service attacks (either malicious or not) that could otherwise overload the ingesters. They act like the bouncer at the front door, ensuring everyone is appropriately dressed and has an invitation. It also allows us to fan-out writes according to our replication factor. + +### Validation + +The first step the distributor takes is to ensure that all incoming data is according to specification. This includes things like checking that the labels are valid Prometheus labels as well as ensuring the timestamps aren't too old or too new or the log lines aren't too long. + +### Preprocessing + +Currently the only way the distributor mutates incoming data is by normalizing labels. What this means is making `{foo="bar", bazz="buzz"}` equivalent to `{bazz="buzz", foo="bar"}`, or in other words, sorting the labels. This allows Loki to cache and hash them deterministically. + +### Rate limiting + +The distributor can also rate limit incoming logs based on the maximum per-tenant bitrate. It does this by checking a per tenant limit and dividing it by the current number of distributors. This allows the rate limit to be specified per tenant at the cluster level and enables us to scale the distributors up or down and have the per-distributor limit adjust accordingly. For instance, say we have 10 distributors and tenant A has a 10MB rate limit. Each distributor will allow up to 1MB/second before limiting. Now, say another large tenant joins the cluster and we need to spin up 10 more distributors. The now 20 distributors will adjust their rate limits for tenant A to `(10MB / 20 distributors) = 500KB/s`! This is how global limits allow much simpler and safer operation of the Loki cluster. + +**Note: The distributor uses the `ring` component under the hood to register itself amongst it's peers and get the total number of active distributors. This is a different "key" than the ingesters use in the ring and comes from the distributor's own [ring configuration](../../../configuration#distributor_config).** + +### Forwarding + +Once the distributor has performed all of it's validation duties, it forwards data to the ingester component which is ultimately responsible for acknowledging the write. + +#### Replication factor + +In order to mitigate the chance of _losing_ data on any single ingester, the distributor will forward writes to a _replication_factor_ of them. Generally, this is `3`. Replication allows for ingester restarts and rollouts without failing writes and adds additional protection from data loss for some scenarios. Loosely, for each label set (called a _stream_) that is pushed to a distributor, it will hash the labels and use the resulting value to look up `replication_factor` ingesters in the `ring` (which is a subcomponent that exposes a [distributed hash table](https://en.wikipedia.org/wiki/Distributed_hash_table)). It will then try to write the same data to all of them. This will error if less than a _quorum_ of writes succeed. A quorum is defined as `floor(replication_factor / 2) + 1`. So, for our `replication_factor` of `3`, we require that two writes succeed. If less than two writes succeed, the distributor returns an error and the write can be retried. + +**Caveat: There's also an edge case where we acknowledge a write if 2 of the three ingesters do which means that in the case where 2 writes succeed, we can only lose one ingester before suffering data loss.** + +Replication factor isn't the only thing that prevents data loss, though, and arguably these days it's main purpose it to allow writes to continue uninterrupted during rollouts & restarts. The `ingester` component now includes a [write ahead log](https://en.wikipedia.org/wiki/Write-ahead_logging) which persists incoming writes to disk to ensure they're not lost as long as the disk isn't corrupted. The complementary nature of replication factor and WAL ensures data isn't lost unless there are significant failures in both mechanisms (i.e. multiple ingesters die and lose/corrupt their disks). + +### Hashing + +Distributors use consistent hashing in conjunction with a configurable +replication factor to determine which instances of the ingester service should +receive a given stream. + +A stream is a set of logs associated to a tenant and a unique labelset. The +stream is hashed using both the tenant ID and the labelset and then the hash is +used to find the ingesters to send the stream to. + +A hash ring stored in [Consul](https://www.consul.io) is used to achieve +consistent hashing; all [ingesters](#ingester) register themselves into the hash +ring with a set of tokens they own. Each token is a random unsigned 32-bit +number. Along with a set of tokens, ingesters register their state into the +hash ring. The state JOINING, and ACTIVE may all receive write requests, while +ACTIVE and LEAVING ingesters may receive read requests. When doing a hash +lookup, distributors only use tokens for ingesters who are in the appropriate +state for the request. + +To do the hash lookup, distributors find the smallest appropriate token whose +value is larger than the hash of the stream. When the replication factor is +larger than 1, the next subsequent tokens (clockwise in the ring) that belong to +different ingesters will also be included in the result. + +The effect of this hash set up is that each token that an ingester owns is +responsible for a range of hashes. If there are three tokens with values 0, 25, +and 50, then a hash of 3 would be given to the ingester that owns the token 25; +the ingester owning token 25 is responsible for the hash range of 1-25. + +### Quorum consistency + +Since all distributors share access to the same hash ring, write requests can be +sent to any distributor. + +To ensure consistent query results, Loki uses +[Dynamo-style](https://www.cs.princeton.edu/courses/archive/fall15/cos518/studpres/dynamo.pdf) +quorum consistency on reads and writes. This means that the distributor will wait +for a positive response of at least one half plus one of the ingesters to send +the sample to before responding to the client that initiated the send. + +## Ingester + +The **ingester** service is responsible for writing log data to long-term +storage backends (DynamoDB, S3, Cassandra, etc.) on the write path and returning +log data for in-memory queries on the read path. + +Ingesters contain a _lifecycler_ which manages the lifecycle of an ingester in +the hash ring. Each ingester has a state of either `PENDING`, `JOINING`, +`ACTIVE`, `LEAVING`, or `UNHEALTHY`: + +**Deprecated: the WAL (write ahead log) supersedes this feature** +1. `PENDING` is an Ingester's state when it is waiting for a handoff from + another ingester that is `LEAVING`. + +1. `JOINING` is an Ingester's state when it is currently inserting its tokens + into the ring and initializing itself. It may receive write requests for + tokens it owns. + +1. `ACTIVE` is an Ingester's state when it is fully initialized. It may receive + both write and read requests for tokens it owns. + +1. `LEAVING` is an Ingester's state when it is shutting down. It may receive + read requests for data it still has in memory. + +1. `UNHEALTHY` is an Ingester's state when it has failed to heartbeat to + Consul. `UNHEALTHY` is set by the distributor when it periodically checks the ring. + +Each log stream that an ingester receives is built up into a set of many +"chunks" in memory and flushed to the backing storage backend at a configurable +interval. + +Chunks are compressed and marked as read-only when: + +1. The current chunk has reached capacity (a configurable value). +1. Too much time has passed without the current chunk being updated +1. A flush occurs. + +Whenever a chunk is compressed and marked as read-only, a writable chunk takes +its place. + +If an ingester process crashes or exits abruptly, all the data that has not yet +been flushed will be lost. Loki is usually configured to replicate multiple +replicas (usually 3) of each log to mitigate this risk. + +When a flush occurs to a persistent storage provider, the chunk is hashed based +on its tenant, labels, and contents. This means that multiple ingesters with the +same copy of data will not write the same data to the backing store twice, but +if any write failed to one of the replicas, multiple differing chunk objects +will be created in the backing store. See [Querier](#querier) for how data is +deduplicated. + +### Timestamp Ordering + +Loki can be configured to [accept out-of-order writes](../../configuration/#accept-out-of-order-writes). + +When not configured to accept out-of-order writes, the ingester validates that ingested log lines are in order. When an +ingester receives a log line that doesn't follow the expected order, the line +is rejected and an error is returned to the user. + +The ingester validates that log lines are received in +timestamp-ascending order. Each log has a timestamp that occurs at a later +time than the log before it. When the ingester receives a log that does not +follow this order, the log line is rejected and an error is returned. + +Logs from each unique set of labels are built up into "chunks" in memory and +then flushed to the backing storage backend. + +If an ingester process crashes or exits abruptly, all the data that has not yet +been flushed could be lost. Loki is usually configured with a [Write Ahead Log](../../operations/storage/wal) which can be _replayed_ on restart as well as with a `replication_factor` (usually 3) of each log to mitigate this risk. + +When not configured to accept out-of-order writes, +all lines pushed to Loki for a given stream (unique combination of +labels) must have a newer timestamp than the line received before it. There are, +however, two cases for handling logs for the same stream with identical +nanosecond timestamps: + +1. If the incoming line exactly matches the previously received line (matching + both the previous timestamp and log text), the incoming line will be treated + as an exact duplicate and ignored. + +2. If the incoming line has the same timestamp as the previous line but + different content, the log line is accepted. This means it is possible to + have two different log lines for the same timestamp. + +### Handoff - Deprecated in favor of the [WAL](../../operations/storage/wal) + +By default, when an ingester is shutting down and tries to leave the hash ring, +it will wait to see if a new ingester tries to enter before flushing and will +try to initiate a handoff. The handoff will transfer all of the tokens and +in-memory chunks owned by the leaving ingester to the new ingester. + +Before joining the hash ring, ingesters will wait in `PENDING` state for a +handoff to occur. After a configurable timeout, ingesters in the `PENDING` state +that have not received a transfer will join the ring normally, inserting a new +set of tokens. + +This process is used to avoid flushing all chunks when shutting down, which is a +slow process. + +### Filesystem Support + +While ingesters do support writing to the filesystem through BoltDB, this only +works in single-process mode as [queriers](#querier) need access to the same +back-end store and BoltDB only allows one process to have a lock on the DB at a +given time. + +## Query frontend + +The **query frontend** is an **optional service** providing the querier's API endpoints and can be used to accelerate the read path. When the query frontend is in place, incoming query requests should be directed to the query frontend instead of the queriers. The querier service will be still required within the cluster, in order to execute the actual queries. + +The query frontend internally performs some query adjustments and holds queries in an internal queue. In this setup, queriers act as workers which pull jobs from the queue, execute them, and return them to the query-frontend for aggregation. Queriers need to be configured with the query frontend address (via the `-querier.frontend-address` CLI flag) in order to allow them to connect to the query frontends. + +Query frontends are **stateless**. However, due to how the internal queue works, it's recommended to run a few query frontend replicas to reap the benefit of fair scheduling. Two replicas should suffice in most cases. + +### Queueing + +The query frontend queuing mechanism is used to: + +- Ensure that large queries, that could cause an out-of-memory (OOM) error in the querier, will be retried on failure. This allows administrators to under-provision memory for queries, or optimistically run more small queries in parallel, which helps to reduce the TCO. +- Prevent multiple large requests from being convoyed on a single querier by distributing them across all queriers using a first-in/first-out queue (FIFO). +- Prevent a single tenant from denial-of-service-ing (DOSing) other tenants by fairly scheduling queries between tenants. + +### Splitting + +The query frontend splits larger queries into multiple smaller queries, executing these queries in parallel on downstream queriers and stitching the results back together again. This prevents large (multi-day, etc) queries from causing out of memory issues in a single querier and helps to execute them faster. + +### Caching + +#### Metric Queries + +The query frontend supports caching metric query results and reuses them on subsequent queries. If the cached results are incomplete, the query frontend calculates the required subqueries and executes them in parallel on downstream queriers. The query frontend can optionally align queries with their step parameter to improve the cacheability of the query results. The result cache is compatible with any loki caching backend (currently memcached, redis, and an in-memory cache). + +#### Log Queries - Coming soon! + +Caching log (filter, regexp) queries are under active development. + +## Querier + +The **querier** service handles queries using the [LogQL](../../logql/) query +language, fetching logs both from the ingesters and from long-term storage. + +Queriers query all ingesters for in-memory data before falling back to +running the same query against the backend store. Because of the replication +factor, it is possible that the querier may receive duplicate data. To resolve +this, the querier internally **deduplicates** data that has the same nanosecond +timestamp, label set, and log message. + diff --git a/docs/sources/fundamentals/architecture/deployment-modes.md b/docs/sources/fundamentals/architecture/deployment-modes.md new file mode 100644 index 0000000000000..135f38c8352d3 --- /dev/null +++ b/docs/sources/fundamentals/architecture/deployment-modes.md @@ -0,0 +1,102 @@ +--- +title: Deployment modes +weight: 20 +--- +# Deployment modes + +As an application, +Loki is built out of many component microservices, +and is designed to run as a horizontally-scalable distributed system. +Loki's unique design compiles the code of the entire distributed system into +a single binary or Docker image. +The behavior of that single binary is controlled with +the `-target` command-line flag and defines one of three modes of operation. + +Configuration for each deployed instance of the binary +further specifies which components it runs. + +Loki is designed to easily redeploy a cluster under a different mode +as your needs change, +with no configuration changes or minimal configuration changes. + +## Monolithic mode + +The simplest mode of operation sets `-target=all`. +This is the default target, +and it does not need to be specified. +This is monolithic mode; +it runs all of Loki’s microservice components inside a single process +as a single binary or Docker image. + +![monolithic mode diagram](monolithic-mode.png) + +Monolithic mode is useful for getting started quickly to experiment with Loki, +as well as for small read/write volumes of up to approximately 100GB per day. + +Horizontally scale up a monolithic mode deployment to more instances +by using a shared object store, and by configuring the +[`memberlist_config` section](../../configuration/#memberlist_config) +to share state between all instances. + +High availability can be configured by running two Loki instances +using `memberlist_config` configuration and a shared object store. + +Route traffic to all the Loki instances in a round robin fashion. + +Query parallelization is limited to the quantity of instances +and the query parallelism defined. + +## Simple scalable deployment mode + +If your volume of logs exceeds a few hundred GB a day, +or if you would like to separate read and write concerns, +Loki provides the simple scalable deployment mode. +This deployment mode can scale to several TBs of logs per day and more. +Consider the microservices mode approach for very large Loki installations. + +![simple scalable deployment mode diagram](simple-scalable.png) + +In this mode the component microservices of Loki are bundled into two targets: +`-target=read` and `-target=write`. + +There are advantages to separating the read and write paths: + +* higher availability of write path by providing dedicated nodes +* separately scalable read path to add/remove query performance on demand + +The simple scalable deployment mode requires a load balancer in front of Loki, +which directs `/loki/api/v1/push` traffic to the write nodes. +All other requests go to the read nodes. +Traffic should be sent in a round robin fashion. + +The simple scalable deployment of Loki can scale to +several TBs of logs per day and more. + +## Microservices mode + +The microservices deployment mode instantiates components of Loki +as distinct processes. +Each process is invoked specifying its `target`: + +* ingester +* distributor +* query-frontend +* query-scheduler +* querier +* index-gateway +* ruler +* compactor + +![microservices mode diagram](microservices-mode.png) + +Running components as individual microservices allows scaling up +by increasing the quantity of microservices. +The customized cluster has better observability of the individual components. +Microservices mode deployments are the most efficient Loki installations. +However, they are also the most complex to set up and maintain. + +Microservices mode is recommended for very large Loki clusters +or for clusters that require more control over scaling and cluster operations. + +Microservices mode works best with Kubernetes deployments. +There are Jsonnet and distributed Helm chart installations. diff --git a/docs/sources/fundamentals/architecture/distributor.md b/docs/sources/fundamentals/architecture/distributor.md deleted file mode 100644 index adbca4e69685d..0000000000000 --- a/docs/sources/fundamentals/architecture/distributor.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Distributor -weight: 1000 ---- -# Distributor Component - -Distributors are stateless and communicate with ingesters via [gRPC](https://grpc.io). The quantity of distributors can be increased or decreased as needed. - -## Where does it live? - -The distributor is the first component on Grafana Loki's write path downstream from any gateways providing auth or load balancing. It's responsible for validating, preprocessing, and applying a subset of rate limiting to incoming data before sending it to the ingester component. It is important that a load balancer sits in front of the distributor in order to properly balance traffic to them. - -## What does it do? - -### Validation - -The first step the distributor takes is to ensure that all incoming data is according to specification. This includes things like checking that the labels are valid Prometheus labels as well as ensuring the timestamps aren't too old or too new or the log lines aren't too long. - -### Preprocessing - -Currently the only way the distributor mutates incoming data is by normalizing labels. What this means is making `{foo="bar", bazz="buzz"}` equivalent to `{bazz="buzz", foo="bar"}`, or in other words, sorting the labels. This allows Loki to cache and hash them deterministically. - -### Rate limiting - -The distributor can also rate limit incoming logs based on the maximum per-tenant bitrate. It does this by checking a per tenant limit and dividing it by the current number of distributors. This allows the rate limit to be specified per tenant at the cluster level and enables us to scale the distributors up or down and have the per-distributor limit adjust accordingly. For instance, say we have 10 distributors and tenant A has a 10MB rate limit. Each distributor will allow up to 1MB/second before limiting. Now, say another large tenant joins the cluster and we need to spin up 10 more distributors. The now 20 distributors will adjust their rate limits for tenant A to `(10MB / 20 distributors) = 500KB/s`! This is how global limits allow much simpler and safer operation of the Loki cluster. - -**Note: The distributor uses the `ring` component under the hood to register itself amongst it's peers and get the total number of active distributors. This is a different "key" than the ingesters use in the ring and comes from the distributor's own [ring configuration](../../../configuration#distributor_config).** - -### Forwarding - -Once the distributor has performed all of it's validation duties, it forwards data to the ingester component which is ultimately responsible for acknowledging the write. - -#### Replication factor - -In order to mitigate the chance of _losing_ data on any single ingester, the distributor will forward writes to a _replication_factor_ of them. Generally, this is `3`. Replication allows for ingester restarts and rollouts without failing writes and adds additional protection from data loss for some scenarios. Loosely, for each label set (called a _stream_) that is pushed to a distributor, it will hash the labels and use the resulting value to look up `replication_factor` ingesters in the `ring` (which is a subcomponent that exposes a [distributed hash table](https://en.wikipedia.org/wiki/Distributed_hash_table)). It will then try to write the same data to all of them. This will error if less than a _quorum_ of writes succeed. A quorum is defined as `floor(replication_factor / 2) + 1`. So, for our `replication_factor` of `3`, we require that two writes succeed. If less than two writes succeed, the distributor returns an error and the write can be retried. - -**Caveat: There's also an edge case where we acknowledge a write if 2 of the three ingesters do which means that in the case where 2 writes succeed, we can only lose one ingester before suffering data loss.** - -Replication factor isn't the only thing that prevents data loss, though, and arguably these days it's main purpose it to allow writes to continue uninterrupted during rollouts & restarts. The `ingester` component now includes a [write ahead log](https://en.wikipedia.org/wiki/Write-ahead_logging) which persists incoming writes to disk to ensure they're not lost as long as the disk isn't corrupted. The complementary nature of replication factor and WAL ensures data isn't lost unless there are significant failures in both mechanisms (i.e. multiple ingesters die and lose/corrupt their disks). - -## Why does it deserve it's own component? - -Notably, the distributor is a stateless component. This makes it easy to scale and offload as much work as possible from the ingesters, which are the most critical component on the write path. The ability to independently scale these validation operations mean that Loki can also protect itself against denial of service attacks (either malicious or not) that could otherwise overload the ingesters. They act like the bouncer at the front door, ensuring everyone is appropriately dressed and has an invitation. It also allows us to fan-out writes according to our replication factor as described earlier. diff --git a/docs/sources/fundamentals/architecture/rings.md b/docs/sources/fundamentals/architecture/rings.md new file mode 100644 index 0000000000000..1758155175620 --- /dev/null +++ b/docs/sources/fundamentals/architecture/rings.md @@ -0,0 +1,7 @@ +--- +title: Consistent Hash Rings +weight: 40 +--- +# Consistent Hash Rings + +TODO: describe why and how consistent hash rings are used.
docs
Reorganize architecture section (#4873)
0a697f9f30dcd54588a59c7db7a3ef14ca2c9095
2025-03-05 05:49:51
renovate[bot]
fix(deps): update module github.com/prometheus/client_golang to v1.21.1 (main) (#16552)
false
diff --git a/go.mod b/go.mod index 7eebf6b76a3a2..0d0bcd1532d40 100644 --- a/go.mod +++ b/go.mod @@ -83,7 +83,7 @@ require ( // github.com/pierrec/lz4 v2.0.5+incompatible github.com/pierrec/lz4/v4 v4.1.22 github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.21.0 + github.com/prometheus/client_golang v1.21.1 github.com/prometheus/client_model v0.6.1 github.com/prometheus/common v0.62.0 github.com/prometheus/prometheus v0.302.1 diff --git a/go.sum b/go.sum index fe065e8b85401..b86294f4cd5ae 100644 --- a/go.sum +++ b/go.sum @@ -1025,8 +1025,8 @@ github.com/prometheus/client_golang v1.6.1-0.20200604110148-03575cad4e55/go.mod github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.21.0 h1:DIsaGmiaBkSangBgMtWdNfxbMNdku5IK6iNhrEqWvdA= -github.com/prometheus/client_golang v1.21.0/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= +github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= +github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= diff --git a/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go b/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go deleted file mode 100644 index b65896a31955b..0000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "sync/atomic" - "time" -) - -// atomicUpdateFloat atomically updates the float64 value pointed to by bits -// using the provided updateFunc, with an exponential backoff on contention. -func atomicUpdateFloat(bits *uint64, updateFunc func(float64) float64) { - const ( - // both numbers are derived from empirical observations - // documented in this PR: https://github.com/prometheus/client_golang/pull/1661 - maxBackoff = 320 * time.Millisecond - initialBackoff = 10 * time.Millisecond - ) - backoff := initialBackoff - - for { - loadedBits := atomic.LoadUint64(bits) - oldFloat := math.Float64frombits(loadedBits) - newFloat := updateFunc(oldFloat) - newBits := math.Float64bits(newFloat) - - if atomic.CompareAndSwapUint64(bits, loadedBits, newBits) { - break - } else { - // Exponential backoff with sleep and cap to avoid infinite wait - time.Sleep(backoff) - backoff *= 2 - if backoff > maxBackoff { - backoff = maxBackoff - } - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go index 2996aef6a0ad2..4ce84e7a80e50 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go @@ -134,9 +134,13 @@ func (c *counter) Add(v float64) { return } - atomicUpdateFloat(&c.valBits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + oldBits := atomic.LoadUint64(&c.valBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + v) + if atomic.CompareAndSwapUint64(&c.valBits, oldBits, newBits) { + return + } + } } func (c *counter) AddWithExemplar(v float64, e Labels) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go index aa18463654f1d..dd2eac940675b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go @@ -120,9 +120,13 @@ func (g *gauge) Dec() { } func (g *gauge) Add(val float64) { - atomicUpdateFloat(&g.valBits, func(oldVal float64) float64 { - return oldVal + val - }) + for { + oldBits := atomic.LoadUint64(&g.valBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + val) + if atomic.CompareAndSwapUint64(&g.valBits, oldBits, newBits) { + return + } + } } func (g *gauge) Sub(val float64) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 1a279035b30b7..c453b754a7f6f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -1647,9 +1647,13 @@ func waitForCooldown(count uint64, counts *histogramCounts) { // atomicAddFloat adds the provided float atomically to another float // represented by the bit pattern the bits pointer is pointing to. func atomicAddFloat(bits *uint64, v float64) { - atomicUpdateFloat(bits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + loadedBits := atomic.LoadUint64(bits) + newBits := math.Float64bits(math.Float64frombits(loadedBits) + v) + if atomic.CompareAndSwapUint64(bits, loadedBits, newBits) { + break + } + } } // atomicDecUint32 atomically decrements the uint32 p points to. See diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go index 50eb860a68210..0a61b984613fe 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go @@ -11,6 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build darwin && !ios + package prometheus import ( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.c similarity index 98% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.c index 1554f674d8507..d00a24315deef 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.c @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build darwin && cgo +//go:build darwin && !ios && cgo #include <mach/mach_init.h> #include <mach/task.h> diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.go similarity index 97% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.go index b375c3a77198d..9ac53f999252f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_cgo_darwin.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build darwin && cgo +//go:build darwin && !ios && cgo package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_nocgo_darwin.go similarity index 97% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_nocgo_darwin.go index 5165047311e8e..8ddb0995d6ae3 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_mem_nocgo_darwin.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build darwin && !cgo +//go:build darwin && !ios && !cgo package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go similarity index 95% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go index c68f7f85187f5..7732b7f376484 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build wasip1 || js -// +build wasip1 js +//go:build wasip1 || js || ios +// +build wasip1 js ios package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go similarity index 100% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index 76a9e12f4a48f..ac5203c6faa5d 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -471,9 +471,13 @@ func (s *noObjectivesSummary) Observe(v float64) { n := atomic.AddUint64(&s.countAndHotIdx, 1) hotCounts := s.counts[n>>63] - atomicUpdateFloat(&hotCounts.sumBits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + oldBits := atomic.LoadUint64(&hotCounts.sumBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + v) + if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) { + break + } + } // Increment count last as we take it as a signal that the observation // is complete. atomic.AddUint64(&hotCounts.count, 1) @@ -515,13 +519,14 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error { // Finally add all the cold counts to the new hot counts and reset the cold counts. atomic.AddUint64(&hotCounts.count, count) atomic.StoreUint64(&coldCounts.count, 0) - - // Use atomicUpdateFloat to update hotCounts.sumBits atomically. - atomicUpdateFloat(&hotCounts.sumBits, func(oldVal float64) float64 { - return oldVal + sum.GetSampleSum() - }) - atomic.StoreUint64(&coldCounts.sumBits, 0) - + for { + oldBits := atomic.LoadUint64(&hotCounts.sumBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + sum.GetSampleSum()) + if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) { + atomic.StoreUint64(&coldCounts.sumBits, 0) + break + } + } return nil } diff --git a/vendor/modules.txt b/vendor/modules.txt index 504e5795d45dc..fca350182a972 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1480,7 +1480,7 @@ github.com/power-devops/perfstat ## explicit; go 1.22.0 github.com/prometheus/alertmanager/api/v2/models github.com/prometheus/alertmanager/pkg/modtimevfs -# github.com/prometheus/client_golang v1.21.0 +# github.com/prometheus/client_golang v1.21.1 ## explicit; go 1.21 github.com/prometheus/client_golang/api github.com/prometheus/client_golang/api/prometheus/v1
fix
update module github.com/prometheus/client_golang to v1.21.1 (main) (#16552)
8c4eb428c3491b6efa41217e4e721eeca0da1a53
2025-03-12 20:02:38
Robert Fratto
chore(dataobj): Download pages in 16MB batches (#16689)
false
diff --git a/pkg/dataobj/internal/encoding/dataset_logs.go b/pkg/dataobj/internal/encoding/dataset_logs.go index 35c6f469360a6..ce04cf7e1e44d 100644 --- a/pkg/dataobj/internal/encoding/dataset_logs.go +++ b/pkg/dataobj/internal/encoding/dataset_logs.go @@ -40,30 +40,52 @@ func (ds *logsDataset) ListColumns(ctx context.Context) result.Seq[dataset.Colum } func (ds *logsDataset) ListPages(ctx context.Context, columns []dataset.Column) result.Seq[dataset.Pages] { - // TODO(rfratto): Switch to batch retrieval instead of iterating over each column. + // We unwrap columns to get the underlying metadata and rewrap to + // dataset.Page to be able to allow the underlying decoder to read multiple + // column metadatas in a single call. return result.Iter(func(yield func(dataset.Pages) bool) error { - for _, column := range columns { - pages, err := result.Collect(column.ListPages(ctx)) - if err != nil { - return err - } else if !yield(pages) { - return nil + descs := make([]*logsmd.ColumnDesc, len(columns)) + for i, column := range columns { + column, ok := column.(*logsDatasetColumn) + if !ok { + return fmt.Errorf("unexpected column type: got=%T want=*logsDatasetColumn", column) } + descs[i] = column.desc } + for result := range ds.dec.Pages(ctx, descs) { + pagesDescs, err := result.Value() + + pages := make([]dataset.Page, len(pagesDescs)) + for i, pageDesc := range pagesDescs { + pages[i] = &logsDatasetPage{dec: ds.dec, desc: pageDesc} + } + if err != nil || !yield(pages) { + return err + } + } return nil }) } func (ds *logsDataset) ReadPages(ctx context.Context, pages []dataset.Page) result.Seq[dataset.PageData] { - // TODO(rfratto): Switch to batch retrieval instead of iterating over each page. + // We unwrap columns to get the underlying metadata and rewrap to + // dataset.Page to be able to allow the underlying decoder to read multiple + // pages in a single call. return result.Iter(func(yield func(dataset.PageData) bool) error { - for _, page := range pages { - data, err := page.ReadPage(ctx) - if err != nil { + descs := make([]*logsmd.PageDesc, len(pages)) + for i, page := range pages { + page, ok := page.(*logsDatasetPage) + if !ok { + return fmt.Errorf("unexpected page type: got=%T want=*logsDatasetPage", page) + } + descs[i] = page.desc + } + + for result := range ds.dec.ReadPages(ctx, descs) { + data, err := result.Value() + if err != nil || !yield(data) { return err - } else if !yield(data) { - return nil } } diff --git a/pkg/dataobj/internal/encoding/dataset_streams.go b/pkg/dataobj/internal/encoding/dataset_streams.go index 9442a50686d19..d7592d3cf2b03 100644 --- a/pkg/dataobj/internal/encoding/dataset_streams.go +++ b/pkg/dataobj/internal/encoding/dataset_streams.go @@ -40,30 +40,52 @@ func (ds *streamsDataset) ListColumns(ctx context.Context) result.Seq[dataset.Co } func (ds *streamsDataset) ListPages(ctx context.Context, columns []dataset.Column) result.Seq[dataset.Pages] { - // TODO(rfratto): Switch to batch retrieval instead of iterating over each column. + // We unwrap columns to get the underlying metadata and rewrap to + // dataset.Page to be able to allow the underlying decoder to read multiple + // column metadatas in a single call. return result.Iter(func(yield func(dataset.Pages) bool) error { - for _, column := range columns { - pages, err := result.Collect(column.ListPages(ctx)) - if err != nil { - return err - } else if !yield(pages) { - return nil + descs := make([]*streamsmd.ColumnDesc, len(columns)) + for i, column := range columns { + column, ok := column.(*streamsDatasetColumn) + if !ok { + return fmt.Errorf("unexpected column type: got=%T want=*streamsDatasetColumn", column) } + descs[i] = column.desc } + for result := range ds.dec.Pages(ctx, descs) { + pagesDescs, err := result.Value() + + pages := make([]dataset.Page, len(pagesDescs)) + for i, pageDesc := range pagesDescs { + pages[i] = &streamsDatasetPage{dec: ds.dec, desc: pageDesc} + } + if err != nil || !yield(pages) { + return err + } + } return nil }) } func (ds *streamsDataset) ReadPages(ctx context.Context, pages []dataset.Page) result.Seq[dataset.PageData] { - // TODO(rfratto): Switch to batch retrieval instead of iterating over each page. + // We unwrap columns to get the underlying metadata and rewrap to + // dataset.Page to be able to allow the underlying decoder to read multiple + // pages in a single call. return result.Iter(func(yield func(dataset.PageData) bool) error { - for _, page := range pages { - data, err := page.ReadPage(ctx) - if err != nil { + descs := make([]*streamsmd.PageDesc, len(pages)) + for i, page := range pages { + page, ok := page.(*streamsDatasetPage) + if !ok { + return fmt.Errorf("unexpected page type: got=%T want=*streamsDatasetPage", page) + } + descs[i] = page.desc + } + + for result := range ds.dec.ReadPages(ctx, descs) { + data, err := result.Value() + if err != nil || !yield(data) { return err - } else if !yield(data) { - return nil } } diff --git a/pkg/dataobj/internal/encoding/decoder_range.go b/pkg/dataobj/internal/encoding/decoder_range.go index 19d5847d2f1db..22b9083868d1d 100644 --- a/pkg/dataobj/internal/encoding/decoder_range.go +++ b/pkg/dataobj/internal/encoding/decoder_range.go @@ -1,6 +1,7 @@ package encoding import ( + "bytes" "context" "fmt" "io" @@ -12,6 +13,16 @@ import ( "github.com/grafana/loki/v3/pkg/dataobj/internal/result" ) +// windowSize specifies the maximum amount of data to download at once from +// object storage. 16MB is chosen based on S3's [recommendations] for +// Byte-Range fetches, which recommends either 8MB or 16MB. +// +// As windowing is designed to reduce the number of requests made to object +// storage, 16MB is chosen over 8MB, as it will lead to fewer requests. +// +// [recommendations]: https://docs.aws.amazon.com/whitepapers/latest/s3-optimizing-performance-best-practices/use-byte-range-fetches.html +const windowSize = 16_000_000 + // rangeReader is an interface that can read a range of bytes from an object. type rangeReader interface { // Size returns the full size of the object. @@ -114,31 +125,54 @@ func (rd *rangeStreamsDecoder) Columns(ctx context.Context, section *filemd.Sect } func (rd *rangeStreamsDecoder) Pages(ctx context.Context, columns []*streamsmd.ColumnDesc) result.Seq[[]*streamsmd.PageDesc] { - getPages := func(ctx context.Context, column *streamsmd.ColumnDesc) ([]*streamsmd.PageDesc, error) { - rc, err := rd.rr.ReadRange(ctx, int64(column.Info.MetadataOffset), int64(column.Info.MetadataSize)) - if err != nil { - return nil, fmt.Errorf("reading column metadata: %w", err) + return result.Iter(func(yield func([]*streamsmd.PageDesc) bool) error { + results := make([][]*streamsmd.PageDesc, len(columns)) + + columnInfo := func(c *streamsmd.ColumnDesc) (uint64, uint64) { + return c.GetInfo().MetadataOffset, c.GetInfo().MetadataSize } - defer rc.Close() - br, release := getBufioReader(rc) - defer release() + for window := range iterWindows(columns, columnInfo, windowSize) { + if len(window) == 0 { + continue + } - md, err := decodeStreamsColumnMetadata(br) - if err != nil { - return nil, err - } - return md.Pages, nil - } + var ( + windowOffset = window.Start().GetInfo().MetadataOffset + windowSize = (window.End().GetInfo().MetadataOffset + window.End().GetInfo().MetadataSize) - windowOffset + ) - // TODO(rfratto): this retrieves all pages for all columns individually; we - // may be able to batch requests to minimize roundtrips. - return result.Iter(func(yield func([]*streamsmd.PageDesc) bool) error { - for _, column := range columns { - pages, err := getPages(ctx, column) + rc, err := rd.rr.ReadRange(ctx, int64(windowOffset), int64(windowSize)) + if err != nil { + return fmt.Errorf("reading column data: %w", err) + } + data, err := readAndClose(rc, windowSize) if err != nil { - return err - } else if !yield(pages) { + return fmt.Errorf("read column data: %w", err) + } + + for _, wp := range window { + // Find the slice in the data for this column. + var ( + columnOffset = wp.Data.GetInfo().MetadataOffset + dataOffset = columnOffset - windowOffset + ) + + r := bytes.NewReader(data[dataOffset : dataOffset+wp.Data.GetInfo().MetadataSize]) + + md, err := decodeStreamsColumnMetadata(r) + if err != nil { + return err + } + + // wp.Position is the position of the column in the original pages + // slice; this retains the proper order of data in results. + results[wp.Position] = md.Pages + } + } + + for _, data := range results { + if !yield(data) { return nil } } @@ -147,32 +181,61 @@ func (rd *rangeStreamsDecoder) Pages(ctx context.Context, columns []*streamsmd.C }) } +// readAndClose reads exactly size bytes from rc and then closes it. +func readAndClose(rc io.ReadCloser, size uint64) ([]byte, error) { + defer rc.Close() + + data := make([]byte, size) + if _, err := io.ReadFull(rc, data); err != nil { + return nil, fmt.Errorf("read column data: %w", err) + } + return data, nil +} + func (rd *rangeStreamsDecoder) ReadPages(ctx context.Context, pages []*streamsmd.PageDesc) result.Seq[dataset.PageData] { - getPageData := func(ctx context.Context, page *streamsmd.PageDesc) (dataset.PageData, error) { - rc, err := rd.rr.ReadRange(ctx, int64(page.Info.DataOffset), int64(page.Info.DataSize)) - if err != nil { - return nil, fmt.Errorf("reading page data: %w", err) + return result.Iter(func(yield func(dataset.PageData) bool) error { + results := make([]dataset.PageData, len(pages)) + + pageInfo := func(p *streamsmd.PageDesc) (uint64, uint64) { + return p.GetInfo().DataOffset, p.GetInfo().DataSize } - defer rc.Close() - br, release := getBufioReader(rc) - defer release() + // TODO(rfratto): If there are many windows, it may make sense to read them + // in parallel. + for window := range iterWindows(pages, pageInfo, windowSize) { + if len(window) == 0 { + continue + } - data := make([]byte, page.Info.DataSize) - if _, err := io.ReadFull(br, data); err != nil { - return nil, fmt.Errorf("read page data: %w", err) - } - return dataset.PageData(data), nil - } + var ( + windowOffset = window.Start().GetInfo().DataOffset + windowSize = (window.End().GetInfo().DataOffset + window.End().GetInfo().DataSize) - windowOffset + ) - // TODO(rfratto): this retrieves all pages for all columns individually; we - // may be able to batch requests to minimize roundtrips. - return result.Iter(func(yield func(dataset.PageData) bool) error { - for _, page := range pages { - data, err := getPageData(ctx, page) + rc, err := rd.rr.ReadRange(ctx, int64(windowOffset), int64(windowSize)) + if err != nil { + return fmt.Errorf("reading page data: %w", err) + } + data, err := readAndClose(rc, windowSize) if err != nil { - return err - } else if !yield(data) { + return fmt.Errorf("read page data: %w", err) + } + + for _, wp := range window { + // Find the slice in the data for this page. + var ( + pageOffset = wp.Data.GetInfo().DataOffset + dataOffset = pageOffset - windowOffset + ) + + // wp.Position is the position of the page in the original pages slice; + // this retains the proper order of data in results. + results[wp.Position] = dataset.PageData(data[dataOffset : dataOffset+wp.Data.GetInfo().DataSize]) + } + } + + for _, data := range results { + if !yield(data) { return nil } } @@ -206,31 +269,54 @@ func (rd *rangeLogsDecoder) Columns(ctx context.Context, section *filemd.Section } func (rd *rangeLogsDecoder) Pages(ctx context.Context, columns []*logsmd.ColumnDesc) result.Seq[[]*logsmd.PageDesc] { - getPages := func(ctx context.Context, column *logsmd.ColumnDesc) ([]*logsmd.PageDesc, error) { - rc, err := rd.rr.ReadRange(ctx, int64(column.Info.MetadataOffset), int64(column.Info.MetadataSize)) - if err != nil { - return nil, fmt.Errorf("reading column metadata: %w", err) + return result.Iter(func(yield func([]*logsmd.PageDesc) bool) error { + results := make([][]*logsmd.PageDesc, len(columns)) + + columnInfo := func(c *logsmd.ColumnDesc) (uint64, uint64) { + return c.GetInfo().MetadataOffset, c.GetInfo().MetadataSize } - defer rc.Close() - br, release := getBufioReader(rc) - defer release() + for window := range iterWindows(columns, columnInfo, windowSize) { + if len(window) == 0 { + continue + } - md, err := decodeLogsColumnMetadata(br) - if err != nil { - return nil, err - } - return md.Pages, nil - } + var ( + windowOffset = window.Start().GetInfo().MetadataOffset + windowSize = (window.End().GetInfo().MetadataOffset + window.End().GetInfo().MetadataSize) - windowOffset + ) - // TODO(rfratto): this retrieves all pages for all columns individually; we - // may be able to batch requests to minimize roundtrips. - return result.Iter(func(yield func([]*logsmd.PageDesc) bool) error { - for _, column := range columns { - pages, err := getPages(ctx, column) + rc, err := rd.rr.ReadRange(ctx, int64(windowOffset), int64(windowSize)) if err != nil { - return err - } else if !yield(pages) { + return fmt.Errorf("reading column data: %w", err) + } + data, err := readAndClose(rc, windowSize) + if err != nil { + return fmt.Errorf("read page data: %w", err) + } + + for _, wp := range window { + // Find the slice in the data for this column. + var ( + columnOffset = wp.Data.GetInfo().MetadataOffset + dataOffset = columnOffset - windowOffset + ) + + r := bytes.NewReader(data[dataOffset : dataOffset+wp.Data.GetInfo().MetadataSize]) + + md, err := decodeLogsColumnMetadata(r) + if err != nil { + return err + } + + // wp.Position is the position of the column in the original pages + // slice; this retains the proper order of data in results. + results[wp.Position] = md.Pages + } + } + + for _, data := range results { + if !yield(data) { return nil } } @@ -240,31 +326,49 @@ func (rd *rangeLogsDecoder) Pages(ctx context.Context, columns []*logsmd.ColumnD } func (rd *rangeLogsDecoder) ReadPages(ctx context.Context, pages []*logsmd.PageDesc) result.Seq[dataset.PageData] { - getPageData := func(ctx context.Context, page *logsmd.PageDesc) (dataset.PageData, error) { - rc, err := rd.rr.ReadRange(ctx, int64(page.Info.DataOffset), int64(page.Info.DataSize)) - if err != nil { - return nil, fmt.Errorf("reading page data: %w", err) + return result.Iter(func(yield func(dataset.PageData) bool) error { + results := make([]dataset.PageData, len(pages)) + + pageInfo := func(p *logsmd.PageDesc) (uint64, uint64) { + return p.GetInfo().DataOffset, p.GetInfo().DataSize } - defer rc.Close() - br, release := getBufioReader(rc) - defer release() + // TODO(rfratto): If there are many windows, it may make sense to read them + // in parallel. + for window := range iterWindows(pages, pageInfo, windowSize) { + if len(window) == 0 { + continue + } - data := make([]byte, page.Info.DataSize) - if _, err := io.ReadFull(br, data); err != nil { - return nil, fmt.Errorf("read page data: %w", err) - } - return dataset.PageData(data), nil - } + var ( + windowOffset = window.Start().GetInfo().DataOffset + windowSize = (window.End().GetInfo().DataOffset + window.End().GetInfo().DataSize) - windowOffset + ) - // TODO(rfratto): this retrieves all pages for all columns individually; we - // may be able to batch requests to minimize roundtrips. - return result.Iter(func(yield func(dataset.PageData) bool) error { - for _, page := range pages { - data, err := getPageData(ctx, page) + rc, err := rd.rr.ReadRange(ctx, int64(windowOffset), int64(windowSize)) if err != nil { - return err - } else if !yield(data) { + return fmt.Errorf("reading page data: %w", err) + } + data, err := readAndClose(rc, windowSize) + if err != nil { + return fmt.Errorf("read page data: %w", err) + } + + for _, wp := range window { + // Find the slice in the data for this page. + var ( + pageOffset = wp.Data.GetInfo().DataOffset + dataOffset = pageOffset - windowOffset + ) + + // wp.Position is the position of the page in the original pages slice; + // this retains the proper order of data in results. + results[wp.Position] = dataset.PageData(data[dataOffset : dataOffset+wp.Data.GetInfo().DataSize]) + } + } + + for _, data := range results { + if !yield(data) { return nil } } diff --git a/pkg/dataobj/internal/encoding/windowing.go b/pkg/dataobj/internal/encoding/windowing.go new file mode 100644 index 0000000000000..6237d0ea37a9c --- /dev/null +++ b/pkg/dataobj/internal/encoding/windowing.go @@ -0,0 +1,109 @@ +package encoding + +import ( + "cmp" + "iter" + "slices" +) + +// The windowing utilities allow for grouping subsections of a file into +// windows of a specified size; for example, given a slices of pages to +// download and a window size of 16MB, pages will be grouped such that the +// first byte of the first page and the last byte of the last page are no more +// than 16MB apart. + +// window represents a window of file subsections. +type window[T any] []windowedElement[T] + +// Start returns the first element in the window. +func (w window[T]) Start() T { + var zero T + if len(w) == 0 { + return zero + } + return w[0].Data +} + +// End returns the last element in the window. +func (w window[T]) End() T { + var zero T + if len(w) == 0 { + return zero + } + return w[len(w)-1].Data +} + +type windowedElement[T any] struct { + Data T // Windowed data. + Position int // Position of the element in the original slice pre-windowing. +} + +type getElementInfo[T any] func(v T) (offset, size uint64) + +// iterWindows groups elements into windows of a specified size, returning an +// iterator over the windows. The input slice is not modified. +func iterWindows[T any](elements []T, getInfo getElementInfo[T], windowSize int64) iter.Seq[window[T]] { + // Sort elements by their start position. + sortedElements := make(window[T], len(elements)) + for i, element := range elements { + sortedElements[i] = windowedElement[T]{Data: element, Position: i} + } + slices.SortFunc(sortedElements, func(a, b windowedElement[T]) int { + aOffset, _ := getInfo(a.Data) + bOffset, _ := getInfo(b.Data) + return cmp.Compare(aOffset, bOffset) + }) + + return func(yield func(window[T]) bool) { + var start, end int + + for end < len(sortedElements) { + startElement := sortedElements[start] + currentElement := sortedElements[end] + + var ( + startOffset, _ = getInfo(startElement.Data) + endOffset, endSize = getInfo(currentElement.Data) + ) + + var ( + startByte = startOffset + endByte = endOffset + endSize + ) + + switch { + case endByte-startByte > uint64(windowSize) && start == end: + // We have an empty window and the element is larger than the current + // window size. We want to immediately add the page into the window and + // yield what we have. + end++ + + if !yield(sortedElements[start:end]) { + return + } + start = end + + case endByte-startByte > uint64(windowSize) && start < end: + // Including end in the window would exceed the window size; we yield + // everything up to end and start a new window from end. + // + // We *do not* increment end here; if we did, we would start with two + // elements in the next window. + if !yield(sortedElements[start:end]) { + return + } + start = end + + default: + // The element fits within the window size; move end forward so it gets + // included. + end++ + } + } + + // Yield all remaining elements. + if start < len(sortedElements) { + yield(sortedElements[start:]) + } + } +} diff --git a/pkg/dataobj/internal/encoding/windowing_test.go b/pkg/dataobj/internal/encoding/windowing_test.go new file mode 100644 index 0000000000000..4482ca53a513c --- /dev/null +++ b/pkg/dataobj/internal/encoding/windowing_test.go @@ -0,0 +1,147 @@ +package encoding + +import ( + "fmt" + "slices" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/grafana/loki/v3/pkg/dataobj/internal/metadata/datasetmd" +) + +func Test_windowPages(t *testing.T) { + tt := []struct { + name string + pages []*fakePageDesc + windowSize int64 + expect []window[*fakePageDesc] + }{ + { + name: "empty pages", + pages: nil, + windowSize: 1_000_000, + expect: nil, + }, + { + name: "single page smaller than window", + pages: []*fakePageDesc{newFakePage(0, 100)}, + windowSize: 1_000_000, + expect: []window[*fakePageDesc]{ + {{Data: newFakePage(0, 100), Position: 0}}, + }, + }, + { + name: "single page larger than window", + pages: []*fakePageDesc{newFakePage(0, 5_000_000)}, + windowSize: 5_000_000, + expect: []window[*fakePageDesc]{ + {{Data: newFakePage(0, 5_000_000), Position: 0}}, + }, + }, + { + name: "basic grouping", + pages: []*fakePageDesc{ + newFakePage(0, 100), + newFakePage(100, 100), + newFakePage(200, 100), + + newFakePage(1500, 100), + newFakePage(1600, 100), + }, + windowSize: 1000, + expect: []window[*fakePageDesc]{ + { + {Data: newFakePage(0, 100), Position: 0}, + {Data: newFakePage(100, 100), Position: 1}, + {Data: newFakePage(200, 100), Position: 2}, + }, + { + {Data: newFakePage(1500, 100), Position: 3}, + {Data: newFakePage(1600, 100), Position: 4}, + }, + }, + }, + { + name: "basic grouping (unordered)", + pages: []*fakePageDesc{ + newFakePage(1500, 100), + newFakePage(200, 100), + newFakePage(100, 100), + + newFakePage(1600, 100), + newFakePage(0, 100), + }, + windowSize: 1000, + expect: []window[*fakePageDesc]{ + { + {Data: newFakePage(0, 100), Position: 4}, + {Data: newFakePage(100, 100), Position: 2}, + {Data: newFakePage(200, 100), Position: 1}, + }, + { + {Data: newFakePage(1500, 100), Position: 0}, + {Data: newFakePage(1600, 100), Position: 3}, + }, + }, + }, + { + name: "grouping with large page", + pages: []*fakePageDesc{ + newFakePage(0, 100), + newFakePage(100, 100), + newFakePage(200, 1000), + newFakePage(300, 100), + newFakePage(400, 100), + }, + windowSize: 500, + expect: []window[*fakePageDesc]{ + { + {Data: newFakePage(0, 100), Position: 0}, + {Data: newFakePage(100, 100), Position: 1}, + }, + { + {Data: newFakePage(200, 1000), Position: 2}, + }, + { + {Data: newFakePage(300, 100), Position: 3}, + {Data: newFakePage(400, 100), Position: 4}, + }, + }, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + getInfo := func(p *fakePageDesc) (uint64, uint64) { + return p.Info.DataOffset, p.Info.DataSize + } + actual := slices.Collect(iterWindows(tc.pages, getInfo, tc.windowSize)) + + for wi, w := range actual { + for pi, p := range w { + t.Logf("window %d page %d: %#v\n", wi, pi, p.Data) + } + } + + require.Equal(t, tc.expect, actual) + }) + } +} + +type fakePageDesc struct{ Info *datasetmd.PageInfo } + +func (f *fakePageDesc) GetInfo() *datasetmd.PageInfo { return f.Info } + +func (f *fakePageDesc) GoString() string { + return fmt.Sprintf("(start: %d, size: %d)", f.Info.DataOffset, f.Info.DataSize) +} + +func newFakePage(offset, size uint64) *fakePageDesc { + return &fakePageDesc{ + Info: &datasetmd.PageInfo{ + DataOffset: offset, + DataSize: size, + }, + } +}
chore
Download pages in 16MB batches (#16689)
6442ec1bdddd810ab261d18bceb604e40f6835a3
2023-04-04 14:26:50
Danny Kopping
mixins: check that `memcached_index_writes` exists before using it in `boltdb_shipper` (#8995)
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 57f89c228746c..7949f421b9fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,14 @@ * [8988](https://github.com/grafana/loki/pull/8988) **darxriggs**: Promtail: Prevent logging errors on normal shutdown. +#### Mixins + +#### Enhancements + +#### Fixes + +* [8995](https://github.com/grafana/loki/pull/8995) **dannykopping**: Mixins: Fix Jsonnet `RUNTIME ERROR` that occurs when you try to use the mixins with `use_boltdb_shipper: false`. + ## 2.8.0 (2023-03-??) #### Loki diff --git a/production/ksonnet/loki/boltdb_shipper.libsonnet b/production/ksonnet/loki/boltdb_shipper.libsonnet index 5877e1f82e4ff..4c0ef90ca57bb 100644 --- a/production/ksonnet/loki/boltdb_shipper.libsonnet +++ b/production/ksonnet/loki/boltdb_shipper.libsonnet @@ -32,7 +32,8 @@ }, // we don't dedupe index writes when using boltdb-shipper so don't deploy a cache for it. - memcached_index_writes: if $._config.using_boltdb_shipper then {} else super.memcached_index_writes, + memcached_index_writes: if $._config.using_boltdb_shipper then {} else + if 'memcached_index_writes' in super then super.memcached_index_writes else {}, // Use PVC for compactor instead of node disk. compactor_data_pvc:: if $._config.using_boltdb_shipper then
mixins
check that `memcached_index_writes` exists before using it in `boltdb_shipper` (#8995)
ac284ca00ed065907341ee2a7adf329c8e485a7a
2024-07-12 20:50:22
Ned Andreev
feat: improve placeholder replacement of byte sizes (#13508)
false
diff --git a/pkg/pattern/tokenization/replacer.go b/pkg/pattern/tokenization/replacer.go index 35d9259236be2..cc725cb5b9874 100644 --- a/pkg/pattern/tokenization/replacer.go +++ b/pkg/pattern/tokenization/replacer.go @@ -314,6 +314,10 @@ restore: // should be faster than a defer return false } +// 'b' and 'B' are not present here because of the way we check for byte size +// units below. If they were present, then suffixes like 'Bb', 'bb', etc. would +// be considered valid byte sizes. Also, only integer numbers are accepted as +// valid bytesizes in bytes, so we handle bytes with special cases instead. var byteSizes = [256]bool{'k': true, 'K': true, 'm': true, 'M': true, 'g': true, 'G': true, 't': true, 'T': true, 'p': true, 'P': true} // Only moves the head forward if it successfully matches a duration @@ -339,6 +343,22 @@ func (r *replacer) advanceBytesize(c1 byte) (matched bool) { return false } +func (r *replacer) advanceSpacedBytesize(canBeBytes bool) (matched bool) { + // Get the next character after the space + c1, hasNext := r.advance() + if !hasNext { + return false + } + if canBeBytes && (c1 == 'b' || c1 == 'B') && r.peekNextIsBoundary() { + return true + } + if r.advanceBytesize(c1) { + return true + } + r.backtrack() + return false +} + func (r *replacer) advance() (c byte, advanced bool) { if r.head >= len(r.source) { return 0, false @@ -394,6 +414,14 @@ func (r *replacer) handleHexOrUnit(hasMinusPrefix bool, n1, l1 uint, c1 byte) (e c1 = r.peekFirstNonInt() } + // Special case, this might be a byte size + if (c1 == 'b' || c1 == 'B') && r.peekNextIsBoundary() { + // We do not subsume a minus sign - byte sizes are unlikely to be + // negative, it's more likely this is a dash as a part of a range + r.emit(hasMinusPrefix, placeholderBytesize) + return true + } + // Maybe we are at the start of a hex string, either something like // "[0-9]+[a-f]", "[0-9]+[A-F]", or "0x". We support both lower and upper // case letters, but to avoid false positives, we want hex replacements to @@ -489,6 +517,14 @@ func (r *replacer) handleNumberWithDecimal(hasMinusPrefix bool, n1 uint, l1 uint return r.handlePotentialUnitWithDecimal(hasMinusPrefix, b2) } + // This can be a byte size with a space, e.g. "3.14 GiB" + if b2 == ' ' && r.advanceSpacedBytesize(false) { + // We do not subsume a minus sign - byte sizes are unlikely to be + // negative, it's more likely this is a dash as a part of a range + r.emit(hasMinusPrefix, placeholderBytesize) + return true + } + // We have a decimal number followed by a non-dot boundary, so this is not // an IP or a version number or anything like that. if b2 != '.' { @@ -633,6 +669,11 @@ func (r *replacer) handleNumberStart(hasMinusPrefix bool) (endsWithBoundary bool case n1 <= maxYear && l1 <= 4 && (b1 == '-' || b1 == '/'): return r.handleSaneTimestamp(hasMinusPrefix, n1, b1) + // This might be a byte size with a space, e.g. "2 b", "3 GiB" + case b1 == ' ' && r.advanceSpacedBytesize(true): + r.emit(hasMinusPrefix, placeholderBytesize) + return true + // Weird RFC822 dates like "02 Jan 06 15:04 MST" case n1 <= 31 && l1 <= 2 && b1 == ' ': if r.advanceMonthName() && r.advanceChar(' ') && r.advanceYear() && r.advanceChar(' ') && r.advanceTime(true) && r.advanceStringOrNumericTimeZone(false) { diff --git a/pkg/pattern/tokenization/tokenization_test.go b/pkg/pattern/tokenization/tokenization_test.go index 9e9e4c75fb02c..dde2814a2fe91 100644 --- a/pkg/pattern/tokenization/tokenization_test.go +++ b/pkg/pattern/tokenization/tokenization_test.go @@ -145,8 +145,11 @@ var tokenizationCornerTestCases = []tokenizationTestCase{ []string{"<NUM>.<DURATION>", "3h121m3.<DURATION>", "1h0.<DURATION>", "100usa", "0.12msa"}, }, { - "2Mib 0.12KB-5GB 3.12kb 123Gbps 124mbit:512Tbit", - []string{"<BYTESIZE>", "<BYTESIZE>-<BYTESIZE>", "<BYTESIZE>", "<BYTESIZE>", "<BYTESIZE>:<BYTESIZE>"}, + // We only consider integers to be valid bytesizes in bytes (0.2B doesn't make sense) + "2Mib 0.12KB-5GB 3.12kb 123Gbps 124mbit:512Tbit 5 B;124.1 KB/3b - 2b or 2 BeNot 13.37 b 3 b", + []string{ + "<BYTESIZE>", "<BYTESIZE>-<BYTESIZE>", "<BYTESIZE>", "<BYTESIZE>", "<BYTESIZE>:<BYTESIZE>", + "<BYTESIZE>;<BYTESIZE>/<BYTESIZE>", "-", "<BYTESIZE>", "or", "<NUM>", "BeNot", "<NUM>", "b", "<BYTESIZE>"}, }, { `status=123 status_code:500 status 200 status="-1" status_code:"404" httpStatus=200`, @@ -175,6 +178,13 @@ var tokenizationRealisticTestCases = []tokenizationTestCase{ "level=debug", "ts=<TIMESTAMP>", "caller=shard_resolver.go:<NUM>", "bytes=<BYTESIZE>", "chunks=<NUM>", "streams=<NUM>", "entries=<NUM>", `msg="queried index"`, "type=single", `matchers="{stream=\"stdout\", pod=\"loki-canary-v75j4\"}"`, "duration=<DURATION>", "from=<TIMESTAMP>", "through=<TIMESTAMP>", "length=<DURATION>", }, }, + // tricky loki distributor message: + { + `level=debug ts=2024-07-12T12:25:06.175464934Z caller=push.go:146 org_id=29 traceID=7af4f918eab1c80f msg="push request parsed" path=/loki/api/v1/push contentType=application/x-protobuf contentEncoding= bodySize="8.8 kB" streams=11 entries=43 streamLabelsSize="3.4 kB" entriesSize="19 kB" structuredMetadataSize="71 B" totalSize="22 kB" mostRecentLagMs=167 adaptiveLogsDroppedLines=10 adaptiveLogsDroppedSize=4965 adaptiveLogsMatchedLines=37`, + []string{ + "level=debug", "ts=<TIMESTAMP>", "caller=push.go:<NUM>", "org_id=<NUM>", "traceID=<HEX>", `msg="push request parsed"`, "path=/loki/api/v1/push", "contentType=application/x-protobuf", "contentEncoding=", `bodySize="<BYTESIZE>"`, "streams=<NUM>", "entries=<NUM>", `streamLabelsSize="<BYTESIZE>"`, `entriesSize="<BYTESIZE>"`, `structuredMetadataSize="<BYTESIZE>"`, `totalSize="<BYTESIZE>"`, "mostRecentLagMs=<NUM>", "adaptiveLogsDroppedLines=<NUM>", "adaptiveLogsDroppedSize=<NUM>", "adaptiveLogsMatchedLines=<NUM>", + }, + }, // random JSON logs { `{"timestamp": "2022-12-23T12:34:56Z", "level": "debug", "message": "Server starting", "server_id": "abcdefghij", "start_time": "2022-12-23T12:30:00Z"}`,
feat
improve placeholder replacement of byte sizes (#13508)
e21b52567447d65292ee0ce80a78382573227a70
2024-01-18 03:09:40
Ed Welch
loki: increase the limit for query length from 5k to 128k (#11701)
false
diff --git a/pkg/logql/syntax/parser.go b/pkg/logql/syntax/parser.go index 710bf7132c4c8..79213049f376c 100644 --- a/pkg/logql/syntax/parser.go +++ b/pkg/logql/syntax/parser.go @@ -31,7 +31,13 @@ var parserPool = sync.Pool{ }, } -const maxInputSize = 5120 +// (E.Welch) We originally added this limit from fuzz testing and realizing there should be some maximum limit to an allowed query size. +// The original limit was 5120 based on some internet searching and a best estimate of what a reasonable limit would be. +// We have seen use cases with queries containing a lot of filter expressions or long expanded variable names where this limit was too small. +// Apparently the spec does not specify a limit, and more internet searching suggests almost all browsers will handle 100k+ length urls without issue +// Some limit here still seems prudent however, so the new limit is now 128k. +// Also note this is used to allocate the buffer for reading the query string, so there is some memory cost to making this larger. +const maxInputSize = 131072 func init() { // Improve the error messages coming out of yacc.
loki
increase the limit for query length from 5k to 128k (#11701)